react-semaphor 0.1.35 → 0.1.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{dashboard-plus-CVpMi6Iz.js → dashboard-plus-Clk-B8Ss.js} +2 -2
- package/dist/chunks/{dashboard-plus-Zf5r_PKH.js → dashboard-plus-DehpYCed.js} +569 -566
- package/dist/chunks/{index-Crl1Y5gC.js → index-Ia329lYL.js} +159 -159
- package/dist/chunks/{index-CJ6zHW9j.js → index-s15_8jgm.js} +13264 -13186
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +3 -3
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";const e=require("react/jsx-runtime"),s=require("./index-
|
|
1
|
+
"use strict";const e=require("react/jsx-runtime"),s=require("./index-Ia329lYL.js"),k=require("react"),Vt=require("react-dom");function zt(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>t[a]})}}return n.default=t,Object.freeze(n)}const ss=zt(k);/**
|
|
2
2
|
* @license lucide-react v0.453.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -253,7 +253,7 @@
|
|
|
253
253
|
*
|
|
254
254
|
* This source code is licensed under the ISC license.
|
|
255
255
|
* See the LICENSE file in the root directory of this source tree.
|
|
256
|
-
*/const ya=s.createLucideIcon("Wand",[["path",{d:"M15 4V2",key:"z1p9b7"}],["path",{d:"M15 16v-2",key:"px0unx"}],["path",{d:"M8 9h2",key:"1g203m"}],["path",{d:"M20 9h2",key:"19tzq7"}],["path",{d:"M17.8 11.8 19 13",key:"yihg8r"}],["path",{d:"M15 9h.01",key:"x1ddxp"}],["path",{d:"M17.8 6.2 19 5",key:"fd4us0"}],["path",{d:"m3 21 9-9",key:"1jfql5"}],["path",{d:"M12.2 6.2 11 5",key:"i3da3b"}]]);function Na(){const{setTheme:t}=s.useTheme(),n=s.useDashboardStore(a=>a.actions.setDashboardTheme);return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"h-7 p-2",variant:"ghost",size:"sm",children:[e.jsx(ga,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(ca,{strokeWidth:1.5,className:"absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),e.jsx("span",{className:"sr-only",children:"Toggle theme"})]})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuItem,{onClick:()=>{t("light"),n("light")},children:"Light"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("dark"),n("dark")},children:"Dark"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("system"),n("system")},children:"System"})]})]})}function Ke(t){var n;return{...t,sheets:(n=t==null?void 0:t.sheets)==null?void 0:n.map(a=>{var r;return{...a,frames:(r=a.frames)==null?void 0:r.map(l=>{var c;return{...l,cards:(c=l.cards)==null?void 0:c.map(d=>Ys(d))}})}})}}function Ys(t){return{...t,customCfg:Ca(t.customCfg),data:[]}}function Ca(t){var n,a;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(a=(n=t==null?void 0:t.data)==null?void 0:n.datasets)==null?void 0:a.map(r=>({...r,data:[]}))}}:null}async function Sa(t,n,a,r,l){if(!l)return null;const c=JSON.stringify(a),d=`${t}/v1/lens`;return await s.postRequest(d,l,{name:n,template:c,filterValues:r,operation:"create"})}async function ts(t,n,a){if(!a)return null;const{id:r,template:l,filterValues:c,isDefault:d,shared:o}=n,i=`${t}/v1/lens`;return await s.postRequest(i,a,{lensId:r,template:l,filterValues:c,isDefault:d,shared:o,operation:"update"})}async function wa(t,n,a){if(!a)return null;const r=`${t}/v1/lens`;return await s.postRequest(r,a,{operation:"delete",lensId:n})}function Da(){const[t,n]=k.useState(""),[a,r]=k.useState(!1),l=s.useDashboardStore(j=>j.lenses),{setLenses:c,setSelectedLensId:d}=s.useDashboardActions(),[o,i]=k.useState(!1),[u,m]=k.useState(!1),x=s.useDashboardStore(j=>j.dashboard),h=s.useDashboardStore(j=>j.filterValues),{authToken:p,tokenProps:b}=s.useSemaphorContext();async function f(){i(!0);const j=Ke(x),N=await Sa(b.apiServiceUrl,t,j,h,p==null?void 0:p.accessToken);N&&(c([...l||[],N]),d(N.id),m(!1)),i(!1)}return e.jsxs(s.Dialog,{open:u,onOpenChange:m,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange:j=>{n(j.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),a&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:f,disabled:o,children:o?"Creating...":"Add"})})]})]})}function Ta(){const[t,n]=k.useState(!1),a=s.useDashboardStore(x=>x.lenses),r=s.useDashboardStore(x=>x.selectedLensId),{setLenses:l,setSelectedLensId:c}=s.useDashboardActions(),{authToken:d,tokenProps:o}=s.useSemaphorContext();async function i(x){c(x)}async function u(x){if(await wa(o.apiServiceUrl,x,d==null?void 0:d.accessToken)){const p=a==null?void 0:a.filter(b=>b.id!==x);l(p||[]),c("original")}}async function m(x){const h=a==null?void 0:a.map(f=>f.id===x.id?{...f,isDefault:!x.isDefault}:{...f,isDefault:!1});l(h||[]);const p={...x,isDefault:!x.isDefault};await ts(o.apiServiceUrl,p,d==null?void 0:d.accessToken);const b=a==null?void 0:a.find(f=>f.isDefault);if(b&&b.id!==x.id){const f={...b,isDefault:!1};await ts(o.apiServiceUrl,f,d==null?void 0:d.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:n,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(ea,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:i,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),a==null?void 0:a.map(x=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:x.id,children:[e.jsx("p",{children:x.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:h=>{h.preventDefault(),m(x)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!x.isDefault,"text-green-500":x.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:h=>{h.preventDefault(),u(x.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},x.id))]})]})]})}function ka({iconClassName:t}){const[n,a]=k.useState(!1),[r,l]=k.useState(""),[c,d]=k.useState(!1),o=s.useDashboardStore(x=>x.isDownloadingPdf),{tokenProps:i}=s.useSemaphorContext();async function u(){const x=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(i.apiServiceUrl),s.ue.dismiss(x),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(h){s.ue.dismiss(x),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",h)}}async function m(){if(!r)return;a(!1),l(""),d(!1);const x=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(i.apiServiceUrl,r),s.ue.dismiss(x),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(h){s.ue.dismiss(x),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",h)}}return e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:o,children:e.jsx(s.Download,{className:s.cn("size-4",t)})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsxs(s.DropdownMenuItem,{onClick:u,children:[e.jsx(s.File,{className:"mr-2 h-4 w-4"}),"Download PDF"]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>a(!0),children:[e.jsx(s.Lock,{className:"mr-2 h-4 w-4"}),"Download Protected PDF"]})]})]}),e.jsx(s.Dialog,{open:n,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Download Protected PDF"}),e.jsx(s.DialogDescription,{children:"Enter a password to protect your PDF. The PDF will be encrypted and require this password to open."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Input,{id:"password",type:c?"text":"password",value:r,onChange:x=>l(x.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:x=>{x.key==="Enter"&&r&&m()}}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>d(!c),children:c?e.jsx(s.EyeOff,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(s.Eye,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:m,disabled:!r,children:"Download"})]})]})})]})}function qs({triggerButtonClassName:t}){const[n,a]=k.useState(!1),r=s.useDashboardStore(o=>{var i;return(i=o.dashboard)==null?void 0:i.id}),l=s.useDashboardStore(o=>{var i;return(i=o.dashboard)==null?void 0:i.title}),c=s.useDashboardStore(o=>{var i;return(i=o.dashboard)==null?void 0:i.sheets}),d=s.useDashboardStore(o=>o.selectedSheetId);return c==null||c.find(o=>o.id===d),r?e.jsxs(e.Fragment,{children:[e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),onClick:()=>a(!0),children:e.jsx(s.Clock,{className:"size-4"})}),e.jsx(s.EmailScheduleDialog,{open:n,onOpenChange:a,dashboardId:r,dashboardName:l})]}):null}function Qe({value:t,onChange:n,placeholder:a="Search users by name, email, or department..."}){return e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:a,value:t,onChange:r=>n(r.target.value),className:"pl-9"})]})}function Ae({currentRole:t,onRoleChange:n,roleOptions:a,disabled:r=!1,className:l="",allowDropdown:c=!0}){var i;const d=((i=a.find(u=>u.value===t))==null?void 0:i.label)||t,o=a.filter(u=>u.value!==t);return c?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${l}`,children:d})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:o.map(u=>e.jsx(s.DropdownMenuItem,{onClick:()=>n(u.value),disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})},u.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${l}`,children:d})}function Ks({selectedUsers:t,selectedUserObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(c=>a(c.id)),className:"h-7 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.map(c=>{const d=t.find(i=>i.id===c.id),o=l(c.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[c.name,e.jsx(Ae,{currentRole:(d==null?void 0:d.role)||"VIEWER",onRoleChange:i=>r(c.id,i),roleOptions:o}),e.jsx("button",{onClick:()=>a(c.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},c.id)})}),e.jsx(s.Separator,{})]})}function Qs({usersToRemove:t,allUsers:n,onRemove:a}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium text-destructive",children:["Users to Remove Access (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(r=>a(r)),className:"h-auto p-1 text-xs text-destructive hover:text-destructive",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>a(r.id),className:"ml-1 rounded-full p-0.5 hover:bg-destructive-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},r.id))}),e.jsx(s.Separator,{})]})}function Hs({usersToUpdate:t,allUsers:n,onRemove:a,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),c=o=>{const i=n.find(u=>u.id===o);return(i==null?void 0:i.name)||"Unknown User"},d=o=>{const i=l.find(u=>u.value===o);return(i==null?void 0:i.label)||o};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(o=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:c(o.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:d(o.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:d(o.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>a(o.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},o.id))})]})}function Ws(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,l=k.useRef(null);return k.useEffect(()=>{const c=d=>{const o=d.target;l.current&&l.current.contains(o)||o instanceof Element&&(o.closest("[data-radix-popper-content-wrapper]")||o.closest("[data-radix-select-content]")||o.closest("[data-radix-popover-content]")||o.closest("[data-radix-dropdown-menu-content]")||o.closest("[data-radix-tooltip-content]")||o.closest('[role="listbox"]')||o.closest('[role="option"]')||o.closest('[role="combobox"]'))||o instanceof Element&&o.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,c),()=>{document.removeEventListener(r,c)}},[t,a,r]),l}function Ne(t,n){var a;return((a=n.find(r=>r.value===t))==null?void 0:a.label)||t}function Ea(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function Js(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function Ia(t,n,a){const r=Js(t),l=(a==null?void 0:a.type)||"organization";if(!(!n||!n.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in n.shares)return(n.shares.specificOrgUsers||[]).find(o=>o.orgUserId===t.id)}else return(n.shares.specificTenantUsers||[]).find(o=>o.tenantUserId===t.id);else return(n.shares.specificTenantUsers||[]).find(o=>o.tenantUserId===t.id)}function Aa({user:t}){return Js(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 Ma({user:t,userShare:n,usersToUpdate:a,currentUser:r,getRoleOptions:l,handleUpdateAccess:c}){if(!(n!=null&&n.role))return null;const d=Ea((r==null?void 0:r.type)||""),o=a.some(x=>x.id===t.id),i=a.find(x=>x.id===t.id),u=i?i.newRole:n==null?void 0:n.role,m=l(t.type);return n?e.jsx("div",{className:"flex items-center gap-2",children:d?e.jsx(Ae,{currentRole:u,onRoleChange:x=>{c(t.id,n.role,x)},roleOptions:m,disabled:!d,allowDropdown:d,className:o?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:Ne(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function Ra({hasAccess:t,isUserRemoving:n,isSelected:a,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!n&&e.jsxs(s.Badge,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Has Access"]}),n&&e.jsxs(s.Badge,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[e.jsx(s.X,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),a&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(Ie,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function La({isUserRemoving:t,isRemoving:n}){return e.jsx(e.Fragment,{children:t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:n?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"})})}function Fa({existingShares:t,allUsers:n,getRoleOptions:a,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const d=t.shares,o=d.specificOrgUsers||[],i=d.specificTenantUsers||[],u=d.orgWide||[],m=d.orgUsersOnly||[],x=d.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",o.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[o.slice(0,3).map((h,p)=>{var N,C;const b=((N=n.find(L=>L.id===h.orgUserId))==null?void 0:N.name)||"Unknown User",f=((C=n.find(L=>L.id===h.orgUserId))==null?void 0:C.type)||"",j=Ne(h.role,a(f));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:b}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},p)}),o.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),i.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 (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((h,p)=>{var N,C;const b=((N=n.find(L=>L.id===h.tenantUserId))==null?void 0:N.name)||"Unknown User",f=((C=n.find(L=>L.id===h.tenantUserId))==null?void 0:C.type)||"",j=Ne(h.role,a(f));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:b}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},p)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.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((h,p)=>{const b=Ne(h.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},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((h,p)=>{const b=Ne(h.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},p)})})]}),x.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:x.map((h,p)=>{const b=Ne(h.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},p)})})]}),!o.length&&!i.length&&!u.length&&!m.length&&!x.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const d=t.shares.specificTenantUsers||[],o=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[d.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",d.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[d.slice(0,3).map((i,u)=>{var p,b;const m=((p=n.find(f=>f.id===i.tenantUserId))==null?void 0:p.name)||"Unknown User",x=((b=n.find(f=>f.id===i.tenantUserId))==null?void 0:b.type)||"",h=Ne(i.role,a(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},u)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:o.map((i,u)=>{const m=Ne(i.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},u)})})]}),!d.length&&!o.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],d=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((o,i)=>{var h,p;const u=((h=n.find(b=>b.id===o.tenantUserId))==null?void 0:h.name)||"Unknown User",m=((p=n.find(b=>b.id===o.tenantUserId))==null?void 0:p.type)||"",x=Ne(o.role,a(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:x})]},i)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),d.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:d.map((o,i)=>{const u=Ne(o.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},i)})})]}),!c.length&&!d.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function Oa({isInitialLoading:t,searchQuery:n,availableUsers:a}){return t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):a.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:n?"No users found matching your search.":"No users available to share with."}):null}function Pa({user:t,userShare:n,isUserRemoving:a,hasAccess:r,hasAccessFromAPI:l,isSelected:c,selectedUser:d,roleOptions:o,currentUser:i,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:x,handleUpdateAccess:h,handleUserRoleChange:p}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!a?"border border-green-200 bg-green-50":a?"border border-red-200 bg-red-50":c?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:l?!a:c,onCheckedChange:()=>{l?a?m(t.id):x(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(Aa,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!a?e.jsx(Ae,{currentRole:n==null?void 0:n.role,onRoleChange:b=>h(t.id,n.role,b),roleOptions:o,disabled:!1,allowDropdown:!0}):e.jsx(Ma,{user:t,userShare:n,usersToUpdate:u,currentUser:i,getRoleOptions:()=>o,handleUpdateAccess:h}),c&&!l&&e.jsx("div",{onClick:b=>b.stopPropagation(),children:e.jsx(Ae,{currentRole:(d==null?void 0:d.role)||"VIEWER",onRoleChange:b=>p(t.id,b),roleOptions:o,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(Ra,{hasAccess:r,isUserRemoving:a,isSelected:c,hasAccessFromAPI:l}),e.jsx(La,{isUserRemoving:a,isSelected:c,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function Xs({existingShares:t,isInitialLoading:n,isSearching:a,getRoleOptions:r,allUsers:l=[],currentUser:c,handleUserToggle:d,handleUserRoleChange:o,handleRemoveAccess:i,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),x=s.useShareUsersToRemove(),h=s.useShareUsersToUpdate(),p=s.useShareSearchQuery(),b=s.useShareManagementActions(),f=d||(w=>{const D=m.some(y=>y.id===w),g=x.includes(w);D?b.removeSelectedUser(w):g?b.removeUserFromRemove(w):b.addSelectedUser({id:w,role:"VIEWER"})}),j=o||b.updateSelectedUserRole,N=i||b.addUserToRemove,C=u||((w,D,g)=>{b.addUserToUpdate({id:w,currentRole:D,newRole:g})}),L=l.filter(w=>w.id!==(c==null?void 0:c.id)),A=x;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 (",(L??[]).length,")"]}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:e.jsx(s.Info,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{className:"w-48 max-w-sm",children:e.jsx(Fa,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:c})})]})})]}),(L==null?void 0:L.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===L.length?b.setSelectedUsers([]):b.setSelectedUsers(L.map(w=>({id:w.id,role:"VIEWER"})))},className:"h-7 text-xs",children:m.length===L.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(Oa,{isInitialLoading:n,isSearching:a,searchQuery:p,availableUsers:L||[]}),!n&&!a&&(L==null?void 0:L.length)>0&&L.map(w=>{const D=t?Ia(w,t,c):void 0,g=A.includes(w.id),y=!!D,v=y&&!g,R=m.some(I=>I.id===w.id),S=m.find(I=>I.id===w.id),F=r(w.type);return e.jsx(Pa,{user:w,userShare:D,isUserRemoving:g,hasAccess:v,hasAccessFromAPI:y,isSelected:R,selectedUser:S,roleOptions:F,currentUser:c,usersToUpdate:h,handleUserToggle:f,handleRemoveAccess:N,handleUpdateAccess:C,handleUserRoleChange:j},w.id)})]})]})}function ls({shareType:t,onShareTypeChange:n,currentUser:a,options:r}){const l=(a==null?void 0:a.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:n,className:`grid grid-cols-${r.length} gap-4`,children:r.map(c=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:c.value,id:c.value,className:"peer sr-only",disabled:c.disabled}),e.jsxs(s.Label,{htmlFor:c.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 ${c.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[c.icon||e.jsx(s.User,{className:"mb-3 h-6 w-6"}),e.jsxs("div",{className:"space-y-1 text-center",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:c.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:c.description})]})]})]},c.value))}),!l&&r.some(c=>c.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 ye=()=>[{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 Ba({currentUser:t,currentShare:n,isSharing:a,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:c=!1,isUpdating:d=!1,isRemoving:o=!1}){const i=s.useShareCurrentMode(),u=ye().filter(C=>C.value==="VIEWER"||C.value==="EDITOR"||C.value==="CONTRIBUTOR"),m=n.role!=="NONE"?n.role:"NONE",x=l?l.newRole:m,h=n.role!=="NONE"&&!c&&(!l||l.newRole===m),p=l!==null&&l.newRole!==m,b=c,f=m==="NONE"||!m,j=C=>{switch(C){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(ha,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},N=C=>{r(m,C)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",p&&!b&&!f?"border-orange-300 bg-orange-50":h?"border-green-300 bg-green-50":b||f?"border-destructive bg-destructive/10":""),children:[e.jsxs(s.CardHeader,{children:[e.jsxs(s.CardTitle,{className:"flex items-center gap-2 text-base",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Share with All"," ",i==="allOrgUsers"?"Organization":i==="allTenantUsers"?"Tenant":i==="specificOrgUsers"?"Org":"Tenant"," ","Users",h&&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"}),(b||f)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:b||f?"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(C=>e.jsxs(s.Button,{variant:x===C.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>N(C.value),disabled:a||d||o,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[j(C.value),e.jsx("span",{className:"font-medium",children:C.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:C.description})]},C.value))})]})})]})})}function Zs({currentUser:t,currentShare:n,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:c,onRemoveAccess:d,allUsersToUpdate:o,allUsersToRemove:i}){const u=f=>f==="OWNER"?"CONTRIBUTOR":f,x=n?{role:u(n.role)}:{role:"NONE"},h=o?{currentRole:u(o.currentRole),newRole:u(o.newRole)}:null,p=(f,j)=>{c(f,j)},b=()=>{d()};return e.jsx(Ba,{currentUser:t,currentShare:x,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:p,onRemoveAccess:b,allUsersToUpdate:h,allUsersToRemove:i})}function Pe(t){const{debouncedSearchQuery:n,resourceId:a,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:c}=t,d=k.useMemo(()=>({search:n,active:!0,...l?{type:l}:{},...l==="tenant"&&c?{tenantId:c}:{}}),[n,l,c]),{users:o,isLoading:i,isError:u}=s.useUnifiedUsers(d),m=s.useResourceShares(r,a);return{allUsers:o,isLoadingUsers:i,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function Va({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:c=!1,isRemoving:d=!1}){var z,J;const o=s.useShareSelectedTab(),i=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:x}=s.useShareSearchWithDebounce(),h=s.useShareSelectedUsers(),p=s.useShareUsersToRemove(),b=s.useShareUsersToUpdate(),f=s.useShareCurrentMode(),j=s.useShareOrgWideRole(),N=s.useShareManagementActions(),[C,L]=k.useState("specific_users"),A=()=>{if(o==="org")return"organization";if(o==="tenant")return"tenant"},w=()=>{if(o==="tenant"&&i)return i},{allUsers:D,existingShares:g,isLoadingUsers:y}=Pe({debouncedSearchQuery:x,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:A(),tenantId:w()});k.useEffect(()=>{N.setCurrentContext("org-tab"),N.setCurrentMode(C==="all_users"?"allOrgUsers":"specificOrgUsers")},[N,C]);const v=W=>{var te,oe;const se=W;if(L(se),r==null||r(se),N.setCurrentContext("org-tab"),se==="specific_users")N.setCurrentMode("specificOrgUsers");else if(se==="all_users"){N.setCurrentMode("allOrgUsers");const Q=(oe=(te=g==null?void 0:g.shares)==null?void 0:te.orgUsersOnly)==null?void 0:oe[0];Q&&Q.role!==void 0&&N.setOrgWideRole(Q.role)}},R=D.filter(W=>W.name.toLowerCase().includes(u.toLowerCase())||W.email.toLowerCase().includes(u.toLowerCase())),S=D.filter(W=>h.some(se=>se.id===W.id)),F=W=>{var Q,_;const se=h.some(ae=>ae.id===W),te=p.includes(W),oe=(_=(Q=g==null?void 0:g.shares)==null?void 0:Q.specificOrgUsers)==null?void 0:_.some(ae=>ae.orgUserId===W);se?N.removeSelectedUser(W):te?N.removeUserFromRemove(W):oe||N.addSelectedUser({id:W,role:"VIEWER"})},I=(W,se)=>{N.updateSelectedUserRole(W,se)},T=W=>{N.addUserToRemove(W),N.removeSelectedUser(W)},M=W=>{N.removeUserFromRemove(W)},O=W=>{N.removeUserFromUpdate(W)},E=(W,se)=>{N.setOrgWideRole(se)},P=()=>{N.setOrgWideRole((B==null?void 0:B.role)||"NONE")},B=(J=(z=g==null?void 0:g.shares)==null?void 0:z.orgUsersOnly)==null?void 0:J[0];k.useEffect(()=>{C==="all_users"&&B&&B.role!==void 0&&N.setOrgWideRole(B.role)},[C,B,N]);const Y=y,q=!1;return a?e.jsxs(e.Fragment,{children:[e.jsx(ls,{shareType:C,onShareTypeChange:v,currentUser:a,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(a==null?void 0:a.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role??"")}]}),C==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(Qe,{value:u,onChange:m}),e.jsx(Ks,{selectedUsers:h,selectedUserObjects:S,onRemove:F,onRoleChange:I,getRoleOptions:ye}),e.jsx(Qs,{usersToRemove:p,allUsers:R,onRemove:M}),e.jsx(Hs,{usersToUpdate:b,allUsers:R,onRemove:O,getRoleOptions:ye}),e.jsx(Xs,{existingShares:g,isInitialLoading:Y,isSearching:q,resource:t,onShare:()=>{},getRoleOptions:ye,allUsers:R,currentUser:a,handleUserToggle:F,handleUserRoleChange:I,handleRemoveAccess:T,handleUpdateAccess:(W,se,te)=>{N.addUserToUpdate({id:W,currentRole:se,newRole:te})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Zs,{currentUser:a,currentShare:B,isSharing:l,isUpdating:c,isRemoving:d,onUpdateAccess:E,onRemoveAccess:P,allUsersToUpdate:f==="allOrgUsers"&&j!==((B==null?void 0:B.role)||"NONE")?{currentRole:(B==null?void 0:B.role)||"NONE",newRole:j}:null,allUsersToRemove:f==="allOrgUsers"&&(B==null?void 0:B.role)===void 0})})]}):null}function za(t){switch(t){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function Ua(t){switch(t){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function et({groups:t,existingGroupShares:n,isLoading:a,resource:r,getRoleOptions:l,currentUser:c,handleGroupToggle:d,handleGroupRoleChange:o,handleRemoveAccess:i,handleUpdateAccess:u}){const m=s.useShareSelectedGroups(),x=s.useShareGroupsToRemove(),h=s.useShareGroupsToUpdate(),p=s.useShareManagementActions(),b=l(c==null?void 0:c.type);return a?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):t.length===0?e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No groups available to share with"}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Available Groups"}),e.jsx("div",{className:"max-h-[300px] space-y-2 overflow-y-auto rounded-md border p-3",children:t.map(f=>{const j=n==null?void 0:n.find(g=>g.groupId===f.id),N=m.some(g=>g.id===f.id),C=x.includes(f.id),L=h.find(g=>g.id===f.id),A=!!j&&!C;let D=(j==null?void 0:j.role)||"VIEWER";if(N){const g=m.find(y=>y.id===f.id);D=(g==null?void 0:g.role)||"VIEWER"}else L&&(D=L.newRole);return e.jsxs("div",{className:s.cn("flex items-center justify-between rounded-lg p-2 transition-colors",A&&!C?"border border-green-200 bg-green-50":C?"border border-red-200 bg-red-50":N?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(s.Checkbox,{id:`group-${f.id}`,checked:A?!C:N,disabled:!1,onCheckedChange:()=>{A?C?p.removeGroupFromRemove(f.id):i==null||i(f.id):d==null||d(f.id)}}),e.jsxs("label",{htmlFor:`group-${f.id}`,className:"flex cursor-pointer flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:f.name}),f.type==="ORG_GROUP"?e.jsx(s.Building2,{className:"h-3 w-3 text-blue-600"}):e.jsx(s.Users,{className:"h-3 w-3 text-green-600"}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[f.memberCount," members"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:s.cn("text-xs",Ua(f.type)),children:za(f.type)}),f.type==="TENANT_GROUP"&&f.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",f.tenantName]})]}),f.description&&e.jsx("span",{className:"text-xs text-muted-foreground",children:f.description})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[A&&!C?e.jsx(Ae,{currentRole:D,onRoleChange:g=>{j&&g!==j.role&&(u==null||u(f.id,j.role,g))},roleOptions:b,disabled:!1,allowDropdown:!0,className:L?"border-orange-300 bg-orange-100":""}):N&&!A&&e.jsx(Ae,{currentRole:D,onRoleChange:g=>o==null?void 0:o(f.id,g),roleOptions:b,disabled:!1}),A&&!C&&!L&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>i==null?void 0:i(f.id),children:e.jsx(s.X,{className:"h-4 w-4"})}),C&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p.removeGroupFromRemove(f.id),children:"Undo"}),L&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p.removeGroupFromUpdate(f.id),children:"Cancel"})]})]},f.id)})})]})}function st({selectedGroups:t,groupObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){if(t.length===0)return null;const c=l();return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:["Selected Groups (",t.length,")"]}),e.jsx("div",{className:"space-y-1",children:t.map(d=>{const o=n.find(i=>i.id===d.id);return o?e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted/50 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[o.type==="ORG_GROUP"?e.jsx(s.Building2,{className:"h-4 w-4 text-blue-600"}):e.jsx(s.Users,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{className:"text-sm font-medium",children:o.name}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[o.memberCount," members"]}),o.type==="TENANT_GROUP"&&o.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",o.tenantName]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ae,{currentRole:d.role,onRoleChange:i=>r(d.id,i),roleOptions:c}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>a(d.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})]},d.id):null})})]})}function ws({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:c=!1,isRemoving:d=!1}){var G;const{searchQuery:o,debouncedSearchQuery:i,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),x=s.useShareUsersToRemove(),h=s.useShareUsersToUpdate(),p=s.useShareSelectedGroups(),b=s.useShareGroupsToRemove(),f=s.useShareGroupsToUpdate(),j=s.useShareCurrentMode(),N=s.useShareTenantWideRole(),C=s.useShareAllTenantsRole(),L=s.useShareSelectedTenant(),A=s.useShareManagementActions(),{data:w,isLoading:D}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"}),{groups:g,isLoading:y}=s.useShareableGroups("tenant",(a==null?void 0:a.tenantId)||L),[v,R]=k.useState((a==null?void 0:a.type)==="organization"?"all_tenants":"specific_tenant_users");k.useEffect(()=>{(a==null?void 0:a.type)==="tenant"?(A.setCurrentContext("tenant-dialog"),A.setCurrentMode("specificTenantUsers")):(A.setCurrentContext("tenant-tab"),A.setCurrentMode("allTenants"))},[A,a==null?void 0:a.type]);const S=V=>{var le,de,ne,me;R(V);let Z;if(V==="specific_tenant_users"?Z="specific_users":V==="all_tenant_users"||V==="all_tenants"?Z="all_users":V==="groups"?Z="groups":Z="specific_users",r==null||r(Z),V==="groups"?(A.setCurrentContext("group-share"),A.setCurrentMode("specificGroups")):(a==null?void 0:a.type)==="tenant"?(A.setCurrentContext("tenant-dialog"),V==="specific_tenant_users"?A.setCurrentMode("specificTenantUsers"):V==="all_tenant_users"&&(A.setCurrentMode("allTenantUsers"),a!=null&&a.tenantId&&A.setSelectedTenant(a.tenantId))):(A.setCurrentContext("tenant-tab"),V==="specific_tenant_users"?A.setCurrentMode("specificTenantUsers"):V==="all_tenant_users"?A.setCurrentMode("allTenantUsers"):V==="all_tenants"&&A.setCurrentMode("allTenants")),V==="all_tenant_users"){const je=(de=(le=T==null?void 0:T.shares)==null?void 0:le.tenantWide)==null?void 0:de[0];je&&je.role!==void 0&&A.setTenantWideRole(je.role)}else if(V==="all_tenants"){const je=(me=(ne=T==null?void 0:T.shares)==null?void 0:ne.allTenantsOnly)==null?void 0:me[0];je&&je.role!==void 0&&A.setAllTenantsRole(je.role)}},F=V=>{A.setSelectedTenant(V)},{allUsers:I,existingShares:T,isLoadingUsers:M,isErrorLoadingUsers:O,isLoadingShares:E,isErrorLoadingShares:P}=Pe({debouncedSearchQuery:i,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant",tenantId:(a==null?void 0:a.type)==="tenant"?a.tenantId:L}),B=V=>{var ne,me;const Z=m.some(je=>je.id===V),le=x.includes(V),de=(me=(ne=T==null?void 0:T.shares)==null?void 0:ne.specificTenantUsers)==null?void 0:me.some(je=>je.tenantUserId===V);Z?A.removeSelectedUser(V):le?A.removeUserFromRemove(V):de||A.addSelectedUser({id:V,role:"VIEWER"})},Y=(V,Z)=>{A.updateSelectedUserRole(V,Z)},q=V=>{A.addUserToRemove(V),A.removeSelectedUser(V)},z=V=>{A.removeUserFromRemove(V)},J=V=>{A.removeUserFromUpdate(V)},W=(V,Z,le)=>{A.addUserToUpdate({id:V,currentRole:Z,newRole:le})},se=(V,Z)=>{v==="all_tenant_users"?A.setTenantWideRole(Z):v==="all_tenants"&&A.setAllTenantsRole(Z)},te=()=>{v==="all_tenant_users"?A.setTenantWideRole("VIEWER"):v==="all_tenants"&&A.setAllTenantsRole("VIEWER")},Q=(()=>{var V,Z,le,de;return j==="allTenants"?(Z=(V=T==null?void 0:T.shares)==null?void 0:V.allTenantsOnly)==null?void 0:Z[0]:j==="allTenantUsers"?(de=(le=T==null?void 0:T.shares)==null?void 0:le.tenantWide)==null?void 0:de[0]:null})();k.useEffect(()=>{var V,Z,le,de;if(v==="all_tenant_users"){const ne=(Z=(V=T==null?void 0:T.shares)==null?void 0:V.tenantWide)==null?void 0:Z[0];ne&&ne.role!==void 0&&A.setTenantWideRole(ne.role)}else if(v==="all_tenants"){const ne=(de=(le=T==null?void 0:T.shares)==null?void 0:le.allTenantsOnly)==null?void 0:de[0];ne&&ne.role!==void 0&&A.setAllTenantsRole(ne.role)}},[v,T,A]);const _=I.filter(V=>m.some(Z=>Z.id===V.id)),ae=V=>{const Z=p.some(ne=>ne.id===V),le=b.includes(V),de=X==null?void 0:X.some(ne=>ne.groupId===V);Z?A.removeSelectedGroup(V):le?A.removeGroupFromRemove(V):de||A.addSelectedGroup({id:V,role:"VIEWER"})},H=(V,Z)=>{A.updateSelectedGroupRole(V,Z)},re=V=>{A.addGroupToRemove(V),A.removeSelectedGroup(V)},ie=(V,Z,le)=>{A.addGroupToUpdate({id:V,currentRole:Z,newRole:le})},ue=g.filter(V=>p.some(Z=>Z.id===V.id)),U=k.useMemo(()=>v!=="groups"?[]:g.filter(V=>V.type!=="TENANT_GROUP"?!1:V.name.toLowerCase().includes(o.toLowerCase())||V.description&&V.description.toLowerCase().includes(o.toLowerCase())),[g,v,o]),X=k.useMemo(()=>{var Z,le;const V=((Z=T==null?void 0:T.shares)==null?void 0:Z.specificGroups)||((le=T==null?void 0:T.shares)==null?void 0:le.groups)||[];return!V||V.length===0?[]:V.filter(de=>{const ne=g.find(me=>me.id===de.groupId);return(ne==null?void 0:ne.type)==="TENANT_GROUP"})},[T,g]),xe=M||E||v==="groups"&&y,ce=O||P,K=()=>(a==null?void 0:a.type)==="tenant"||v==="all_tenants"||v==="groups"?!0:L&&(v==="specific_tenant_users"||v==="all_tenant_users");return e.jsxs(e.Fragment,{children:[ce&&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"})]})}),!ce&&a&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(ls,{shareType:v,onShareTypeChange:S,currentUser:a,options:(a==null?void 0:a.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"specific_tenant_users",label:"Specific Users",description:"Share with specific tenant users",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"groups",label:"Groups",description:"Share with tenant groups",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-green-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:e.jsx(ys,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"all_tenant_users",label:"Specific Tenant",description:"Share with all users of a specific tenant",icon:e.jsx(s.House,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"specific_tenant_users",label:"Specific Tenant User",description:"Share with users of a specific tenant",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(a==null?void 0:a.type)==="organization"&&(v==="specific_tenant_users"||v==="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:L||"",onValueChange:F,disabled:D,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:D?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(G=w==null?void 0:w.tenants)==null?void 0:G.map(V=>e.jsx(s.SelectItem,{value:V.id,children:V.name},V.id))})]})]}),K()?e.jsx(e.Fragment,{children:v==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Qe,{value:o,onChange:u}),e.jsx(Ks,{selectedUsers:m,selectedUserObjects:_,onRemove:V=>B(V),onRoleChange:Y,getRoleOptions:ye}),e.jsx(Qs,{usersToRemove:x,allUsers:I,onRemove:z}),e.jsx(Hs,{usersToUpdate:h,allUsers:I,onRemove:J,getRoleOptions:ye}),e.jsx(Xs,{existingShares:T,isInitialLoading:!!xe,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:ye,allUsers:I,currentUser:a,handleUserToggle:B,handleUserRoleChange:Y,handleRemoveAccess:q,handleUpdateAccess:W})]}):v==="groups"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Qe,{value:o,onChange:u,placeholder:"Search groups..."}),e.jsx(st,{selectedGroups:p,groupObjects:ue,onRemove:ae,onRoleChange:H,getRoleOptions:ye}),b.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",b.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),f.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",f.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(et,{groups:U,existingGroupShares:X,isLoading:y,resource:t,getRoleOptions:ye,currentUser:a,handleGroupToggle:ae,handleGroupRoleChange:H,handleRemoveAccess:re,handleUpdateAccess:ie})]}):v==="all_tenant_users"||v==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Zs,{currentUser:a,currentShare:Q,isSharing:l,isUpdating:c,isRemoving:d,onUpdateAccess:se,onRemoveAccess:te,allUsersToUpdate:j==="allTenantUsers"&&((Q==null?void 0:Q.role)===void 0||N!==Q.role)||j==="allTenants"&&((Q==null?void 0:Q.role)===void 0||C!==Q.role)?{currentRole:(Q==null?void 0:Q.role)||"VIEWER",newRole:j==="allTenantUsers"?N:C}:null,allUsersToRemove:j==="allTenantUsers"&&(Q==null?void 0:Q.role)===void 0||j==="allTenants"&&(Q==null?void 0:Q.role)===void 0})}):null}):(a==null?void 0:a.type)==="organization"&&(v==="specific_tenant_users"||v==="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(ys,{className:"mx-auto mb-2 h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant to continue"})]})})]})]})}function _a({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:c=!1,isRemoving:d=!1}){var O,E;const{searchQuery:o,setSearchQuery:i}=s.useShareSearchWithDebounce(),u=s.useShareSelectedGroups(),m=s.useShareGroupsToRemove(),x=s.useShareGroupsToUpdate(),h=s.useShareManagementActions(),[p,b]=k.useState("org_groups"),[f,j]=k.useState(""),{data:N,isLoading:C}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"&&p==="tenant_groups"}),L=Array.isArray(N)?N:(N==null?void 0:N.tenants)||[],A=()=>{if((a==null?void 0:a.type)==="organization")return"organization";if((a==null?void 0:a.type)==="tenant")return"tenant"},{groups:w,isLoading:D}=s.useShareableGroups(A(),p==="tenant_groups"&&(a==null?void 0:a.type)==="organization"?f:a==null?void 0:a.tenantId),{existingShares:g}=Pe({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n}),y=w.filter(P=>p==="org_groups"&&P.type!=="ORG_GROUP"||p==="tenant_groups"&&P.type!=="TENANT_GROUP"||p==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&(!f||P.tenantId&&P.tenantId!==f)?!1:P.name.toLowerCase().includes(o.toLowerCase())||P.description&&P.description.toLowerCase().includes(o.toLowerCase())),v=((O=g==null?void 0:g.shares)==null?void 0:O.specificGroups)||((E=g==null?void 0:g.shares)==null?void 0:E.groups)||[];k.useEffect(()=>{h.setCurrentContext("group-share"),h.setCurrentMode("specificGroups")},[h]);const R=P=>{const B=P;b(B),B==="org_groups"&&j(""),r==null||r(B==="org_groups"?"specific_groups":"all_groups"),h.setCurrentContext("group-share"),h.setCurrentMode("specificGroups")},S=w.filter(P=>u.some(B=>B.id===P.id)),F=P=>{const B=u.some(z=>z.id===P),Y=m.includes(P),q=v==null?void 0:v.some(z=>z.groupId===P);B?h.removeSelectedGroup(P):Y?h.removeGroupFromRemove(P):q||h.addSelectedGroup({id:P,role:"VIEWER"})},I=(P,B)=>{h.updateSelectedGroupRole(P,B)},T=P=>{h.addGroupToRemove(P),h.removeSelectedGroup(P)},M=(P,B,Y)=>{h.addGroupToUpdate({id:P,currentRole:B,newRole:Y})};return a?e.jsxs(e.Fragment,{children:[e.jsx(ls,{shareType:p,onShareTypeChange:R,currentUser:a,options:[{value:"org_groups",label:"Organization Groups",description:"Share with organization-level groups",icon:e.jsx(s.Building2,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"tenant_groups",label:"Tenant Groups",description:"Share with tenant-level groups",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-green-500"})}]}),p==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(s.Label,{children:"Select Tenant"}),e.jsxs(s.Select,{value:f,onValueChange:j,disabled:C,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:C?"Loading tenants...":"Select a tenant to view its groups"})}),e.jsx(s.SelectContent,{className:"z-[51]",children:L.map(P=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:P.id,children:P.name},P.id))})]})]}),e.jsx("div",{className:"mt-3 space-y-2",children:p==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&!f?e.jsx("div",{className:"rounded-md border border-dashed p-6 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant above to view and share with its groups"})}):e.jsxs(e.Fragment,{children:[e.jsx(Qe,{value:o,onChange:i,placeholder:"Search groups..."}),e.jsx(st,{selectedGroups:u,groupObjects:S,onRemove:F,onRoleChange:I,getRoleOptions:ye}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",m.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),x.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",x.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(et,{groups:y,existingGroupShares:v,isLoading:D,resource:t,getRoleOptions:ye,currentUser:a,handleGroupToggle:F,handleGroupRoleChange:I,handleRemoveAccess:T,handleUpdateAccess:M})]})})]}):null}const tt=()=>{const t=s.useShareCurrentContext(),n=s.useShareCurrentMode(),a=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),c=s.useShareSelectedGroups(),d=s.useShareGroupsToRemove(),o=s.useShareGroupsToUpdate(),i=s.useShareSelectedTenant(),u=s.useShareOrgWideRole(),m=s.useShareAllTenantsRole(),x=s.useShareTenantWideRole(),h=s.useShareGroupWideRole(),p=k.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedGroups:c,groupsToRemove:d,groupsToUpdate:o,selectedTenant:i,orgWideRole:u,allTenantsRole:m,tenantWideRole:x}),[t,n,a,r,l,c,d,o,i,u,m,x,h]),b=k.useMemo(()=>j=>s.validateShareData(j),[]),f=k.useMemo(()=>{if(!t||!n)return!1;switch(t){case"org-tab":return n==="specificOrgUsers"?a.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(n==="allTenantUsers"){if(!i)return!1}else if(n==="specificTenantUsers")return i?a.length>0||r.length>0||l.length>0:!1;return!0;case"tenant-dialog":return n==="specificTenantUsers"?a.length>0||r.length>0||l.length>0:!0;case"group-share":return n==="specificGroups"?c.length>0||d.length>0||o.length>0:!0}return!1},[t,n,a,r,l,c,d,o,i]);return{buildShareData:p,validateShareData:b,isCurrentStateValid:f,currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedTenant:i,orgWideRole:u,allTenantsRole:m,tenantWideRole:x}};function Ds({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:c,onClose:d,shareTabType:o,currentAllUsersShare:i,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),x=s.useShareUsersToRemove(),h=s.useShareUsersToUpdate(),p=s.useShareSelectedTenant(),b=s.useShareOrgWideRole(),f=s.useShareAllTenantsRole(),j=s.useShareTenantWideRole(),{buildShareData:N,validateShareData:C,isCurrentStateValid:L}=tt(),A=a||r||l,w=()=>{var R,S,F,I;if(A)return"Updating...";if(o==="specific_users"){if(m.length===0&&x.length===0&&h.length===0)return"Select users to share with";const T=m.length+x.length+h.length;return T===0?"Select users to share with":m.length>0&&x.length>0?`Update access for ${T} user${T!==1?"s":""}`:x.length>0&&m.length===0&&h.length===0?`Remove access for ${x.length} user${x.length!==1?"s":""}`:m.length>0&&x.length===0&&h.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:h.length>0&&m.length===0&&x.length===0?`Update access for ${h.length} user${h.length!==1?"s":""}`:`Update access for ${T} user${T!==1?"s":""}`}else if(o==="all_users"){if(!i||i.role===void 0)return"Share with All Users";const T=i.role;return b===T?"Remove Access":"Update Access"}else if(o==="all_tenants"){const T=(S=(R=n==null?void 0:n.shares)==null?void 0:R.allTenantsOnly)==null?void 0:S[0];if(!T||T.role===void 0)return"Share with All Tenants";const M=T.role;return f===M?"Remove Access":"Update Access"}else if(o==="all_tenant_users"){const T=(I=(F=n==null?void 0:n.shares)==null?void 0:F.tenantWide)==null?void 0:I[0];if(!T||T.role===void 0)return"Share with All Tenant Users";const M=T.role;return j===M?"Remove Access":"Update Access"}else if(o==="specific_tenant_users"){if(m.length===0&&x.length===0&&h.length===0)return"Select users to share with";const T=m.length+x.length+h.length;return T===0?"Select users to share with":m.length>0&&x.length>0?`Update access for ${T} user${T!==1?"s":""}`:x.length>0&&m.length===0&&h.length===0?`Remove access for ${x.length} user${x.length!==1?"s":""}`:m.length>0&&x.length===0&&h.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:h.length>0&&m.length===0&&x.length===0?`Update access for ${h.length} user${h.length!==1?"s":""}`:`Update access for ${T} user${T!==1?"s":""}`}return"Share"},D=()=>A||!t||o==="all_tenant_users"&&!p||o==="specific_tenant_users"&&!p?!0:!L,g=()=>{const R=N();R&&C(R)&&c(R)},y=()=>{var R,S,F,I;if(o==="all_users")if(!i||i.role===void 0){const T=N();T&&C(T)&&c(T)}else{const T=i.role;if(b===T)u==null||u();else{const O=N();if(O&&C(O)){const E={...O,updateAccess:!0};c(E)}}}else if(o==="all_tenants"){const T=(S=(R=n==null?void 0:n.shares)==null?void 0:R.allTenantsOnly)==null?void 0:S[0];if(!T||T.role===void 0){const M=N();M&&C(M)&&c(M)}else{const M=T.role;if(f===M)u==null||u();else{const E=N();if(E&&C(E)){const P={...E,updateAccess:!0};c(P)}}}}else if(o==="all_tenant_users"){const T=(I=(F=n==null?void 0:n.shares)==null?void 0:F.tenantWide)==null?void 0:I[0];if(!T||T.role===void 0){const M=N();M&&C(M)&&c(M)}else{const M=T.role;if(j===M)u==null||u();else{const E=N();if(E&&C(E)){const P={...E,updateAccess:!0};c(P)}}}}},v=()=>{var R,S,F,I;if(o==="all_users"){if(!i||i.role===void 0)return"default";const T=i.role;return b===T?"destructive":"default"}else if(o==="all_tenants"){const T=(S=(R=n==null?void 0:n.shares)==null?void 0:R.allTenantsOnly)==null?void 0:S[0];if(!T||T.role===void 0)return"default";const M=T.role;return f===M?"destructive":"default"}else if(o==="all_tenant_users"){const T=(I=(F=n==null?void 0:n.shares)==null?void 0:F.tenantWide)==null?void 0:I[0];if(!T||T.role===void 0)return"default";const M=T.role;return j===M?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsxs(s.Button,{variant:"outline",onClick:d,disabled:A,children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),(o==="specific_users"||o==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||x.length>0||h.length>0)&&e.jsxs(s.Button,{onClick:g,disabled:!t||A,variant:"default",children:[A?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ie,{className:"mr-2 h-4 w-4"}),!A&&w()]})}),(o==="all_users"||o==="all_tenants"||o==="all_tenant_users")&&e.jsxs(s.Button,{onClick:y,disabled:D(),variant:v(),children:[A?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(s.Users,{className:"mr-2 h-4 w-4"}),!A&&w()]})]})}function Ga({resource:t,isSharing:n,isRemoving:a,isUpdating:r,onShare:l,onClose:c,shareTabType:d,currentAllUsersShare:o}){const i=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate(),x=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),p=s.useShareGroupsToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const b=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:f,validateShareData:j,isCurrentStateValid:N}=tt(),C=n||a||r,L=()=>{if(C)return"Updating...";if(d==="specific_users"){if(i.length===0&&u.length===0&&m.length===0)return"Select users to share with";const v=i.length+u.length+m.length;return v===0?"Select users to share with":i.length>0&&u.length>0?`Update access for ${v} user${v!==1?"s":""}`:u.length>0&&i.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:i.length>0&&u.length===0&&m.length===0?`Share with ${i.length} user${i.length!==1?"s":""}`:m.length>0&&i.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${v} user${v!==1?"s":""}`}else if(d==="groups"){if(x.length===0&&h.length===0&&p.length===0)return"Select groups to share with";const v=x.length+h.length+p.length;return v===0?"Select groups to share with":x.length>0&&h.length>0?`Update access for ${v} group${v!==1?"s":""}`:h.length>0&&x.length===0&&p.length===0?`Remove access for ${h.length} group${h.length!==1?"s":""}`:x.length>0&&h.length===0&&p.length===0?`Share with ${x.length} group${x.length!==1?"s":""}`:p.length>0&&x.length===0&&h.length===0?`Update access for ${p.length} group${p.length!==1?"s":""}`:`Update access for ${v} group${v!==1?"s":""}`}else if(d==="all_users"){if(!o||o.role==="NONE")return"Share with All Users";const v=o.role;return b===v?"Remove Access":"Update Access"}return"Share"},A=()=>C||!t?!0:!N,w=()=>{const v=f();v&&j(v)&&l(v)},D=()=>{const v=f();v&&j(v)&&l(v)},g=()=>{if(!o||o.role==="NONE"){const v=f();v&&j(v)&&l(v)}else{const v=o.role;if(b===v){const S=f();if(S&&j(S)){const F={...S,removeAccess:!0};l(F)}}else{const S=f();if(S&&j(S)){const F={...S,updateAccess:!0};l(F)}}}},y=()=>!o||o.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsxs(s.Button,{variant:"outline",onClick:c,disabled:C,children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),d==="specific_users"&&e.jsx(e.Fragment,{children:(i.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:w,disabled:!t||C,variant:"default",children:[C?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ie,{className:"mr-2 h-4 w-4"}),!C&&L()]})}),d==="groups"&&e.jsx(e.Fragment,{children:(x.length>0||h.length>0||p.length>0)&&e.jsxs(s.Button,{onClick:D,disabled:!t||C,variant:"default",children:[C?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ie,{className:"mr-2 h-4 w-4"}),!C&&L()]})}),d==="all_users"&&e.jsxs(s.Button,{onClick:g,disabled:A(),variant:y(),children:[C?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ie,{className:"mr-2 h-4 w-4"}),!C&&L()]})]})}function $a({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:c,onClose:d,shareTabType:o,currentAllGroupsShare:i,onRemoveAccess:u}){const m=s.useShareSelectedGroups(),x=s.useShareGroupsToRemove(),h=s.useShareGroupsToUpdate();s.useShareGroupWideRole(),s.useShareCurrentMode();const p=()=>{c({context:"group-share",mode:"specificGroups",selectedGroups:m,groupsToRemove:x,groupsToUpdate:h})},b=()=>m.length>0||x.length>0||h.length>0,f=()=>x.length>0&&m.length===0&&h.length===0?"Remove Access":h.length>0&&m.length===0&&x.length===0?"Update Access":"Share with Groups",j=a||r||l;return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[m.length>0&&e.jsxs("span",{children:[m.length," groups selected"]}),x.length>0&&e.jsxs("span",{className:"ml-2 text-destructive",children:["• ",x.length," to remove"]}),h.length>0&&e.jsxs("span",{className:"ml-2 text-orange-600",children:["• ",h.length," to update"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:d,disabled:j,children:"Cancel"}),e.jsxs(s.Button,{onClick:p,disabled:!b()||j,children:[j&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),f()]})]})]})}function ve(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Ce(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Ya(t,n,a){const{resourceType:r,resourceId:l,shareMutation:c,removeMutation:d,existingShares:o,resetUserSelections:i}=n;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const u=ve(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);c(u,{onSuccess:()=>{i()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:x}=t;if(u&&u.length>0){const h=ve(r,l,u.map(p=>({scope:"specific_org_user",orgUserId:p.id,role:p.role})));c(h,{onSuccess:()=>{i()}})}if(m&&m.length>0){const h=Ce(r,l,m.map(p=>{var f,j;const b=(j=(f=o==null?void 0:o.shares)==null?void 0:f.specificOrgUsers)==null?void 0:j.find(N=>N.orgUserId===p);return{scope:"specific_org_user",orgUserId:p,role:(b==null?void 0:b.role)||"VIEWER"}}));d(h,{onSuccess:()=>{i()}})}x&&x.length>0&&x.forEach(h=>{const p=ve(r,l,[{scope:"specific_org_user",orgUserId:h.id,role:h.newRole}]);c(p,{onSuccess:()=>{i()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const u=ve(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);c(u,{onSuccess:()=>{i()}})}else if(t.mode==="allTenantUsers"){const u=ve(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);c(u,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:x,tenantId:h}=t;if(m&&m.length>0){const p=Ce(r,l,m.map(b=>{var j,N;const f=(N=(j=o==null?void 0:o.shares)==null?void 0:j.specificTenantUsers)==null?void 0:N.find(C=>C.tenantUserId===b);return{scope:"specific_tenant_user",tenantUserId:b,tenantId:h,role:(f==null?void 0:f.role)||"VIEWER"}}));d(p,{onSuccess:()=>{i()}})}if(x&&x.length>0&&x.forEach(p=>{const b=ve(r,l,[{scope:"specific_tenant_user",tenantUserId:p.id,tenantId:h,role:p.newRole}]);c(b,{onSuccess:()=>{i()}})}),u&&u.length>0){const p=ve(r,l,u.map(b=>({scope:"specific_tenant_user",tenantUserId:b.id,tenantId:h,role:b.role})));c(p,{onSuccess:()=>{i()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const u=Ce(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);d(u,{onSuccess:()=>{i()}})}else if(t.updateAccess){const u=ve(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);c(u,{onSuccess:()=>{i()}})}else{const u=ve(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);c(u,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:x}=t;if(u&&u.length>0){const h=ve(r,l,u.map(p=>({scope:"specific_tenant_user",tenantUserId:p.id,role:p.role})));c(h,{onSuccess:()=>{i()}})}if(m&&m.length>0){const h=Ce(r,l,m.map(p=>{var f,j;const b=(j=(f=o==null?void 0:o.shares)==null?void 0:f.specificTenantUsers)==null?void 0:j.find(N=>N.tenantUserId===p);return{scope:"specific_tenant_user",tenantUserId:p,role:(b==null?void 0:b.role)||"VIEWER"}}));d(h,{onSuccess:()=>{i()}})}x&&x.length>0&&x.forEach(h=>{const p=ve(r,l,[{scope:"specific_tenant_user",tenantUserId:h.id,role:h.newRole}]);c(p,{onSuccess:()=>{i()}})})}break;case"group-share":if(t.mode==="specificGroups"){const{selectedGroups:u,groupsToRemove:m,groupsToUpdate:x}=t;if(u&&u.length>0){const h=ve(r,l,u.map(p=>({scope:"group",groupId:p.id,role:p.role})));c(h,{onSuccess:()=>{var p;i(),(p=n.resetGroupSelections)==null||p.call(n),s.ue.success(`Shared with ${u.length} group${u.length!==1?"s":""}`)}})}if(m&&m.length>0){const h=Ce(r,l,m.map(p=>({scope:"group",groupId:p,role:"VIEWER"})));d(h,{onSuccess:()=>{var p;i(),(p=n.resetGroupSelections)==null||p.call(n),s.ue.success(`Removed access from ${m.length} group${m.length!==1?"s":""}`)}})}x&&x.length>0&&x.forEach(h=>{const p=ve(r,l,[{scope:"group",groupId:h.id,role:h.newRole}]);c(p,{onSuccess:()=>{var b;i(),(b=n.resetGroupSelections)==null||b.call(n),s.ue.success("Updated access for group")}})})}break}}function qa(t,n,a,r){var u,m,x,h,p,b;const{resourceType:l,resourceId:c,removeMutation:d,existingShares:o,resetUserSelections:i}=r;if(c)if(t.length>0){const f=Ce(l,c,t.map(j=>{var C,L;const N=(L=(C=o==null?void 0:o.shares)==null?void 0:C.specificTenantUsers)==null?void 0:L.find(A=>A.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,role:(N==null?void 0:N.role)||"VIEWER"}}));d(f,{onSuccess:()=>{i()},onError:j=>{console.error("Remove access failed:",j)}})}else{const f=n==="tenant"&&a==="allTenants",j=n==="tenant"&&a==="allTenantUsers";if(f){const N=(m=(u=o==null?void 0:o.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(N){const C=Ce(l,c,[{scope:"all_tenants_only",role:N.role}]);d(C,{onSuccess:()=>{i()},onError:L=>{console.error("Remove all-tenants access failed:",L)}})}}else if(j){const N=(h=(x=o==null?void 0:o.shares)==null?void 0:x.tenantWide)==null?void 0:h[0];if(N){const C=Ce(l,c,[{scope:"all_tenant_users",role:N.role}]);d(C,{onSuccess:()=>{i()},onError:L=>{console.error("Remove all-tenant-users access failed:",L)}})}}else{const N=(b=(p=o==null?void 0:o.shares)==null?void 0:p.orgUsersOnly)==null?void 0:b[0];if(N){const C=Ce(l,c,[{scope:"org_users_only",role:N.role}]);d(C,{onSuccess:()=>{i()},onError:L=>{console.error("Remove org-wide access failed:",L)}})}}}}function Ka(t,n,a){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),c=s.useShareSelectedTab(),d=s.useShareCurrentMode(),{currentUser:o}=s.useCurrentUserInfo(),{existingShares:i}=Pe({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),u=k.useCallback(()=>{r.resetUserSelections()},[r]),m=k.useCallback(()=>{r.resetGroupSelections()},[r]),x=k.useCallback(p=>{if(!t)return;const b={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:n,removeMutation:a,existingShares:i,resetUserSelections:u,resetGroupSelections:m};Ya(p,b,o)},[t,n,a,i,u,m,o]),h=k.useCallback(()=>{if(!t)return;const p={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:a,existingShares:i,resetUserSelections:u};qa(l,c||"",d||"",p)},[t,n,a,i,u,m,l,c,d]);return{handleShareSubmit:x,handleRemoveAccess:h}}function We({resource:t,resourceType:n,onClose:a,onShareSuccess:r,onRemoveSuccess:l}){var I,T,M,O,E,P,B,Y;const{currentUser:c}=s.useCurrentUserInfo(),[d,o]=k.useState("specific_users"),[i,u]=k.useState("specific_users"),[m,x]=k.useState("specific_groups"),h=s.useShareManagementActions(),p=s.useShareSelectedTab(),b=s.useShareCurrentMode(),f=s.useShareResource(),j=s.useRemoveResourceShares(),{handleShareSubmit:N,handleRemoveAccess:C}=Ka(t.id,(q,z)=>{f.mutate(q,{...z,onSuccess:()=>{var J;(J=z==null?void 0:z.onSuccess)==null||J.call(z),r==null||r()}})},(q,z)=>{j.mutate(q,{...z,onSuccess:()=>{var J;(J=z==null?void 0:z.onSuccess)==null||J.call(z),l==null||l()}})}),L=f.isPending,A=j.isPending,w=f.isPending,{existingShares:D}=Pe({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant"}),{existingShares:g}=Pe({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"organization"}),y=(T=(I=D==null?void 0:D.shares)==null?void 0:I.tenantWide)==null?void 0:T[0],v=(O=(M=g==null?void 0:g.shares)==null?void 0:M.orgUsersOnly)==null?void 0:O[0],R=()=>{if(p==="org")return i;switch(b){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},S=k.useCallback(()=>{h.resetShareState(),a()},[h,a]),F=(c==null?void 0:c.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:S,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(Ie,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:F?"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."})]}),F?e.jsxs(s.Tabs,{value:p,onValueChange:q=>{const z=q;h.setSelectedTab(z),h.resetUserSelections(),h.resetGroupSelections()},className:"mb-4 min-h-0 flex-1",children:[e.jsxs(s.TabsList,{className:"mb-2 grid w-full grid-cols-3",children:[e.jsx(s.TabsTrigger,{value:"org",children:"Org Users"}),e.jsx(s.TabsTrigger,{value:"tenant",children:"Tenant Users"}),e.jsx(s.TabsTrigger,{value:"groups",children:"Groups"})]}),e.jsx(s.TabsContent,{value:"org",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(Va,{resource:t,resourceType:n,currentUser:c,onShareTabTypeChange:u,isSharing:L,isUpdating:w,isRemoving:A})})}),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(ws,{resource:t,resourceType:n,currentUser:c,onShareTabTypeChange:q=>o(q),isSharing:L,isUpdating:w,isRemoving:A})})}),e.jsx(s.TabsContent,{value:"groups",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(_a,{resource:t,resourceType:n,currentUser:c,onShareTabTypeChange:x,isSharing:L,isUpdating:w,isRemoving:A})})})]}):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(ws,{resource:t,resourceType:n,currentUser:c,onShareTabTypeChange:q=>o(q),isSharing:L,isUpdating:w,isRemoving:A})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:F?p==="org"?e.jsx(Ds,{resource:t,existingShares:g,isSharing:L,isRemoving:A,isUpdating:w,onShare:N,onClose:a,shareTabType:i,currentAllUsersShare:v,onRemoveAccess:C}):p==="tenant"?e.jsx(Ds,{resource:t,existingShares:D,isSharing:L,isRemoving:A,isUpdating:w,onShare:N,onClose:a,shareTabType:R(),currentAllUsersShare:y,onRemoveAccess:C}):e.jsx($a,{resource:t,existingShares:g,isSharing:L,isRemoving:A,isUpdating:w,onShare:N,onClose:a,shareTabType:m,currentAllGroupsShare:(c==null?void 0:c.type)==="organization"?(P=(E=g==null?void 0:g.shares)==null?void 0:E.allOrgGroups)==null?void 0:P[0]:(Y=(B=D==null?void 0:D.shares)==null?void 0:B.allTenantGroups)==null?void 0:Y[0],onRemoveAccess:C}):e.jsx(Ga,{resource:t,isSharing:L,isRemoving:A,isUpdating:w,onShare:N,onClose:a,shareTabType:d,currentAllUsersShare:y,onRemoveAccess:C})})]})})}function at({type:t,isLinked:n,className:a}){const r=s.useDashboardStore(u=>u.selectedFrameId),l=s.useManagementStore(u=>u.selectedVisual),c=s.useEditorStore(u=>u.frame);let d;if(t)d=t;else if(n!==void 0)d=n?"linked":"library";else if(!!!(c!=null&&c.visualId||l!=null&&l.id)&&r)d="local";else if(l&&!r)d="library";else if(c!=null&&c.visualId&&r)d="linked";else if(l!=null&&l.id&&r)d="library";else return null;const o={local:"bg-gray-100 text-gray-700",linked:"bg-purple-100 text-purple-700",library:"bg-blue-100 text-blue-700"},i={local:"Local Visual",linked:"Linked Visual",library:"Library Visual"};return e.jsx("span",{className:s.cn("rounded-full px-2.5 py-0.5 text-xs font-medium",o[d],a),children:i[d]})}const Qa=async(t,n,a)=>{const r=`${t}/management/v1/groups`;return await s.postRequestRegular(r,n,a)},Ha=async(t,n,a)=>{const r=`${t}/management/v1/groups/${a}`,l=await fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!l.ok){const c=await l.text();throw new Error(c||"Failed to delete group")}},Wa=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`;return await s.postRequestRegular(l,n,r)},Ja=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`,c=await fetch(l,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)});if(!c.ok){const d=await c.text();throw new Error(d||"Failed to remove group members")}};function Xa(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>Qa(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:()=>{a.invalidateQueries({queryKey:["groups"]}),s.ue.success("Group created successfully")},onError:r=>{console.error("Failed to create group:",r),s.ue.error("Failed to create group",{description:r.message})}})}function Za(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>Ha(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["groups"]}),a.removeQueries({queryKey:["group",l]}),s.ue.success("Group deleted successfully")},onError:r=>{console.error("Failed to delete group:",r),s.ue.error("Failed to delete group",{description:r.message})}})}function en(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>Wa(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["group",l.groupId]}),a.invalidateQueries({queryKey:["group-members",l.groupId]}),a.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members added successfully")},onError:r=>{console.error("Failed to add group members:",r),s.ue.error("Failed to add members",{description:r.message})}})}function sn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>Ja(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["group",l.groupId]}),a.invalidateQueries({queryKey:["group-members",l.groupId]}),a.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members removed successfully")},onError:r=>{console.error("Failed to remove group members:",r),s.ue.error("Failed to remove members",{description:r.message})}})}function tn({onSuccess:t,tenantId:n,isTenantUser:a}){const[r,l]=k.useState(""),[c,d]=k.useState(""),[o,i]=k.useState({}),u=Xa(),m=()=>{const h={};return r.trim()?r.length<3?h.name="Group name must be at least 3 characters":r.length>50&&(h.name="Group name must be less than 50 characters"):h.name="Group name is required",c&&c.length>200&&(h.description="Description must be less than 200 characters"),i(h),Object.keys(h).length===0},x=async h=>{if(h.preventDefault(),!m())return;const p={name:r.trim(),description:c.trim()||void 0,type:a?"TENANT_GROUP":"ORG_GROUP",...a&&n?{tenantId:n}:{}};try{await u.mutateAsync(p),l(""),d(""),i({}),t()}catch(b){console.error("Failed to create group:",b)}};return e.jsxs("form",{onSubmit:x,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"group-name",children:["Group Name ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(s.Input,{id:"group-name",placeholder:"e.g., Marketing Team, Engineering Squad",value:r,onChange:h=>{l(h.target.value),o.name&&i(p=>({...p,name:""}))},className:o.name?"border-destructive":"",disabled:u.isPending}),o.name&&e.jsx("p",{className:"text-sm text-destructive",children:o.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"group-description",children:["Description",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:"(optional)"})]}),e.jsx(s.Textarea,{id:"group-description",placeholder:"Describe the purpose of this group...",value:c,onChange:h=>{d(h.target.value),o.description&&i(p=>({...p,description:""}))},className:o.description?"border-destructive":"",disabled:u.isPending,rows:3}),o.description&&e.jsx("p",{className:"text-sm text-destructive",children:o.description}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[c.length,"/200 characters"]})]}),e.jsx("div",{className:"rounded-lg border bg-muted/50 p-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(s.CircleAlert,{className:"h-4 w-4 mt-0.5 text-muted-foreground"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This group will be accessible to users in your workspace. You can add members after creating the group."})]})})]}),e.jsxs("div",{className:"flex justify-end gap-3",children:[e.jsx(s.Button,{type:"button",variant:"outline",onClick:()=>{l(""),d(""),i({})},disabled:u.isPending,children:"Clear"}),e.jsx(s.Button,{type:"submit",disabled:u.isPending||!r.trim(),children:u.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Users,{className:"mr-2 h-4 w-4"}),"Create Group"]})})]})]})}function an({open:t,onOpenChange:n,group:a,onUpdate:r}){const[l,c]=k.useState("members"),[d,o]=k.useState(""),[i,u]=k.useState([]),[m,x]=k.useState([]),{data:h,isLoading:p,refetch:b}=s.useGroupMembers(a.id),f=a.type==="TENANT_GROUP"?"tenant":"organization",{users:j,isLoading:N}=s.useUnifiedUsers({type:f,tenantId:a.tenantId||void 0,active:!0,limit:100}),C=en(),L=sn(),A=(h==null?void 0:h.members)||[],w=k.useMemo(()=>new Set(A.map(I=>I.userId)),[A]),D=k.useMemo(()=>j.filter(I=>!w.has(I.id)),[j,w]),g=k.useMemo(()=>{if(!d)return D;const I=d.toLowerCase();return D.filter(T=>{var M,O;return((M=T.name)==null?void 0:M.toLowerCase().includes(I))||((O=T.email)==null?void 0:O.toLowerCase().includes(I))})},[D,d]),y=k.useMemo(()=>{if(!d)return A;const I=d.toLowerCase();return A.filter(T=>{var M,O,E,P;return((O=(M=T.user)==null?void 0:M.name)==null?void 0:O.toLowerCase().includes(I))||((P=(E=T.user)==null?void 0:E.email)==null?void 0:P.toLowerCase().includes(I))})},[A,d]),v=async()=>{if(i.length!==0)try{await C.mutateAsync({groupId:a.id,data:{userIds:i,userType:f==="tenant"?"tenant":"org"}}),u([]),c("members"),b(),r==null||r()}catch(I){console.error("Failed to add members:",I)}},R=async()=>{if(m.length!==0)try{await L.mutateAsync({groupId:a.id,data:{userIds:m}}),x([]),b(),r==null||r()}catch(I){console.error("Failed to remove members:",I)}},S=I=>{u(T=>T.includes(I)?T.filter(M=>M!==I):[...T,I])},F=I=>{x(T=>T.includes(I)?T.filter(M=>M!==I):[...T,I])};return e.jsx(e.Fragment,{children:e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-3xl max-h-[80vh]","aria-describedby":"group-members-description",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:a.name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[A.length," ",A.length===1?"member":"members"]})}),e.jsxs("p",{id:"group-members-description",className:"sr-only",children:["Add or remove members from the ",a.name," group"]})]}),e.jsxs(s.Tabs,{value:l,onValueChange:I=>{c(I),o(""),x([])},className:"mt-4",children:[e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"members",children:"Current Members"}),e.jsx(s.TabsTrigger,{value:"add",children:"Add Members"})]}),e.jsxs(s.TabsContent,{value:"members",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search members...",value:d,onChange:I=>o(I.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:m.length>0?"h-[300px]":"h-[350px]",children:p?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(I=>e.jsx(s.Skeleton,{className:"h-16 w-full"},I))}):y.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.Users,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:d?"No members found":"No members yet"}),e.jsx("p",{className:"text-xs mt-1",children:d?"Try a different search":'Switch to the "Add Members" tab to add people to this group'})]}):e.jsx("div",{className:"space-y-2",children:y.map(I=>e.jsx(nn,{member:I,selected:m.includes(I.userId),onToggle:()=>F(I.userId)},I.id))})}),m.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[m.length," member",m.length!==1?"s":""," selected"]}),e.jsx(s.Button,{variant:"destructive",size:"sm",onClick:R,disabled:L.isPending,children:L.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Removing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Trash2,{className:"mr-2 h-4 w-4"}),"Remove Selected"]})})]})]}),e.jsxs(s.TabsContent,{value:"add",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search users to add...",value:d,onChange:I=>o(I.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[300px]",children:N?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(I=>e.jsx(s.Skeleton,{className:"h-16 w-full"},I))}):g.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.UserPlus,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:"No available users"}),e.jsx("p",{className:"text-xs mt-1",children:d?"Try a different search":"All eligible users are already members"})]}):e.jsx("div",{className:"space-y-2",children:g.map(I=>e.jsx(rn,{user:I,selected:i.includes(I.id),onToggle:()=>S(I.id)},I.id))})}),i.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[i.length," user",i.length!==1?"s":""," selected"]}),e.jsx(s.Button,{onClick:v,disabled:C.isPending,children:C.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Adding..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.UserPlus,{className:"mr-2 h-4 w-4"}),"Add Members"]})})]})]})]})]})})})}function nn({member:t,selected:n,onToggle:a}){var l,c,d,o;const r=((c=(l=t.user)==null?void 0:l.name)==null?void 0:c.split(" ").map(i=>i[0]).join("").toUpperCase())||"?";return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-muted/50 cursor-pointer",onClick:a,children:[e.jsx(s.Checkbox,{checked:n}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:((d=t.user)==null?void 0:d.name)||"Unknown User"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(o=t.user)==null?void 0:o.email})]})]})}function rn({user:t,selected:n,onToggle:a}){var l;const r=((l=t.name)==null?void 0:l.split(" ").map(c=>c[0]).join("").toUpperCase())||"?";return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-muted/50 cursor-pointer",onClick:a,children:[e.jsx(s.Checkbox,{checked:n}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:t.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.email})]})]})}function ln({open:t,onOpenChange:n}){const[a,r]=k.useState("groups"),[l,c]=k.useState(""),[d,o]=k.useState(null),[i,u]=k.useState(!1),[m,x]=k.useState(null),{tokenProps:h}=s.useSemaphorContext(),{currentUser:p}=s.useCurrentUserInfo(),b=Za(),f=(p==null?void 0:p.type)==="tenant",j=h==null?void 0:h.tenantId,{groups:N,isLoading:C,refetch:L}=s.useGroups({type:f?"TENANT_GROUP":"all",tenantId:f?j:void 0,includeMembers:!1}),A=N.filter(y=>{var v;return y.name.toLowerCase().includes(l.toLowerCase())||((v=y.description)==null?void 0:v.toLowerCase().includes(l.toLowerCase()))}),w=async()=>{if(m)try{await b.mutateAsync(m.id),x(null),L()}catch(y){console.error("Failed to delete group:",y)}},D=y=>{o(y),u(!0)},g=()=>{r("groups"),L()};return e.jsxs(e.Fragment,{children:[e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-4xl max-h-[80vh]",children:[e.jsxs(s.DialogHeader,{children:[e.jsxs(s.DialogTitle,{className:"flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Group Management"]}),e.jsx(s.DialogDescription,{children:"Manage your groups, create new groups, and control group membership"})]}),e.jsxs(s.Tabs,{value:a,onValueChange:r,className:"mt-4",children:[e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsxs(s.TabsTrigger,{value:"groups",className:"flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4"}),"Groups"]}),e.jsxs(s.TabsTrigger,{value:"create",className:"flex items-center gap-2",children:[e.jsx(s.Plus,{className:"h-4 w-4"}),"Create Group"]})]}),e.jsx(s.TabsContent,{value:"groups",className:"mt-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search groups...",value:l,onChange:y=>c(y.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[400px]",children:C?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(y=>e.jsx(s.Skeleton,{className:"h-24 w-full"},y))}):A.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.Users,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:"No groups found"}),e.jsx("p",{className:"text-xs mt-1",children:l?"Try a different search":"Create your first group to get started"})]}):e.jsx("div",{className:"space-y-3",children:A.map(y=>e.jsx(on,{group:y,onManageMembers:()=>D(y),onDelete:()=>x(y),currentUserId:p==null?void 0:p.id},y.id))})})]})}),e.jsx(s.TabsContent,{value:"create",className:"mt-4",children:e.jsx(tn,{onSuccess:g,tenantId:j,isTenantUser:f})})]})]})}),d&&e.jsx(an,{open:i,onOpenChange:u,group:d,onUpdate:()=>L()}),e.jsx(s.AlertDialog,{open:!!m,onOpenChange:()=>x(null),children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Group"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',m==null?void 0:m.name,'"? This action cannot be undone and will remove all members from the group.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:w,disabled:b.isPending,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:b.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Deleting..."]}):"Delete Group"})]})]})})]})}function on({group:t,onManageMembers:n,onDelete:a,currentUserId:r}){const l=t.createdBy===r;return e.jsx("div",{className:"rounded-lg border bg-card p-4 transition-colors hover:bg-muted/50",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:t.name}),t.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:t.description})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(s.Users,{className:"h-3 w-3"}),t.memberCount," ",t.memberCount===1?"member":"members"]}),e.jsxs("span",{children:["Created ",s.format(new Date(t.createdAt),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:n,title:"Manage members",children:e.jsx(s.UserPlus,{className:"h-4 w-4"})}),l&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:a,title:"Delete group",className:"text-destructive hover:text-destructive",children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]})})}function os(t){const[n,a]=k.useState(null),[r,l]=k.useState(null);return k.useEffect(()=>{if(!t||t.trim()===""){a(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const o=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(o,{method:"HEAD"})).ok)throw new Error(`Module not found at ${o}`)}catch{}const i=await import(o);if(typeof i.useChartStore!="function")throw new Error("useChartStore is not a function");a(()=>i.useChartStore),l(null)}catch(d){const o=d instanceof Error?d.message:"Unknown error";console.error("Failed to load remote chart store:",o),l(o),a(null)}})()},[t]),n}function cn(t){const n=t.toUpperCase().indexOf("WHERE"),a=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let c=t.length;if(l!==-1&&(c=l),r!==-1&&r<c&&(c=r),n!==-1){const d=t.substring(0,n),o=t.substring(n);return`${d} {{ filters | where }} AND ${o.substring(6)}`}else if(a!==-1){const d=t.substring(0,a),o=t.substring(a);return`${d} {{ filters | where }} ${o}`}else{const d=t.substring(0,c),o=t.substring(c);return console.log("beforeClause",d),console.log("afterClause",o),o?`${d} {{ filters | where }} ${o}`:`${d.replace(/;$/,"")} {{ filters | where }}`}}function dn(t,n){if(t.length===0)return"";if(n){const a=t.find(r=>r.id===n);if(a){const r=a.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const c=r.split("__")[0],d=t.find(o=>o.tabTitle===c);return d?d.id:t[0].id}return n}}return t[0].id}async function Ts(t,n,a,r){if(!n||!a)throw new Error("Missing auth token or visual ID");const l=["resource-by-id","visual",a],c=r.getQueryData(l);if(c)return console.log("Using cached visual data for:",a),{data:c,fromCache:!0};console.log("Fetching visual data from network for:",a);const d=s.ue.loading("Loading visual...",{position:"top-center"});try{const o=await fetch(`${t}/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${n}`}});if(!o.ok)throw new Error("Failed to load visual");const i=await o.json();return r.setQueryData(l,i),s.ue.dismiss(d),{data:i,fromCache:!1}}catch(o){throw s.ue.dismiss(d),o}}function nt(t){if(typeof t=="string")return JSON.parse(t);if(typeof t=="object")return t;throw new Error("Invalid frame object format")}function un(t,n){var c,d;const a=(t==null?void 0:t.frameObject)??((c=t==null?void 0:t.visual)==null?void 0:c.frameObject);if(!a)return!1;const r=nt(a);if(!(r!=null&&r.cards)||r.cards.length===0)return!1;const l=(d=r.cards)==null?void 0:d.find(o=>o.id===r.activeCardId);return l?(s.setupEditorWithCard({...n,frame:r,card:l,visualId:(t==null?void 0:t.id)||r.visualId}),!0):!1}function mn(){var h;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(p=>p.frame),a=s.useEditorStore(p=>p.card),r=os(((h=a.customCardPreferences)==null?void 0:h.url)||""),l=s.useEditorStore(p=>p.selectedSchemaName),c=s.useEditorStore(p=>p.selectedDatamodelId),d=s.useEditorStore(p=>p.selectedDatabaseName),o=s.useEditorStore(p=>p.selectedTableName),i=s.useEditorStore(p=>p.selectedConnectionId),u=s.useEditorStore(p=>p.isShowingVisual),m=a.sql;return{getUpdatedFrame:k.useCallback(()=>{var N;let p=m;m&&!m.includes("{{")&&(p=cn(m),t(p));const b=(N=r==null?void 0:r.getState())==null?void 0:N.settings,f={...a,dataSource:a.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:c,lastSelectedDatabase:d,lastSelectedTable:o,connectionId:i,sql:p,customCfg:u?a.customCfg:null,preferences:a.preferences,...b&&{customCardPreferences:{...a.customCardPreferences,settings:b}}},j=n.cards.map(C=>C.id===a.id?f:C);return{...n,cards:j,activeCardId:dn(j,n.activeCardId)}},[a,n,u,l,c,d,o,i,t,r,m])}}function Me(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient(),r=s.useSelectedVisual(),{selectVisual:l}=s.useManagementActions(),{setFrame:c,setCard:d,setIsDevMode:o,setActiveTabCardId:i,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:x,setSelectedDatabaseName:h,setSelectedSchemaName:p,setSelectedTableName:b,setSelectedDatamodelId:f,setFilterValues:j,setApplyFilters:N}=s.useEditorActions(),{setIsDashboardEditing:C,setIsVisualEditing:L,setSelectedFrameId:A,clearSelectedFrameId:w,addFrame:D,setIsDashboardPanelOpen:g}=s.useDashboardActions(),y=s.useDashboardStore(M=>M.selectedSheetId),v=s.useDashboardStore(M=>M.selectedFrameId),R=s.useDashboardStore(M=>M.dashboard),S=s.useDashboardStore(M=>M.filterValues),F=s.useVisualById((r==null?void 0:r.id)||"",{enabled:!!(r!=null&&r.id)&&!!(t!=null&&t.accessToken)}),I=k.useCallback(async M=>{try{l(M),w();const{data:O,fromCache:E}=await Ts(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",M.id,a);if(!un(O,{setFrame:c,setCard:d,setIsDevMode:o,setActiveTabCardId:i,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:x,setSelectedDatabaseName:h,setSelectedSchemaName:p,setSelectedTableName:b,setSelectedDatamodelId:f,setFilterValues:j,setApplyFilters:N,setIsDashboardEditing:C,setIsVisualEditing:L,dashboard:R,selectedSheetId:y,selectedFrameId:v,filterValues:S}))throw new Error("Failed to setup editor with visual data");return{success:!0,fromCache:E}}catch(O){return console.error("Error editing visual:",O),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,c,d,C,L,o,i,u,m,x,h,p,b,f,j,N,w,R,y,v,S]),T=k.useCallback(async M=>{var O;try{if(l(M),!y)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:E,fromCache:P}=await Ts(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",M.id,a),B=(E==null?void 0:E.frameObject)??((O=E==null?void 0:E.visual)==null?void 0:O.frameObject);if(!B)return{success:!1,error:"Visual has no frame data"};const Y=nt(B);if(!(Y!=null&&Y.cards)||Y.cards.length===0)return{success:!1,error:"Visual frame is malformed"};const q={...Y,id:s.v4(),visualId:M.id};return D(y,q,"end"),C(!0),A(q.id),g(!1),{success:!0,fromCache:P}}catch(E){return console.error("Error adding visual:",E),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,y,D,C,A,g]);return{visual:F.data,isLoading:F.isLoading,isError:F.isError,error:F.error,handleEditLibraryVisual:I,handleAddLibraryVisual:T,getUpdatedFrame:mn().getUpdatedFrame,refetch:F.refetch}}function hn({open:t,onOpenChange:n,isLibraryVisual:a,currentVisualName:r,isSaving:l=!1,onConfirm:c}){const[d,o]=k.useState(a&&r?`Copy of ${r}`:r||""),[i,u]=k.useState(""),[m,x]=k.useState(!a),[h,p]=k.useState(!0);k.useEffect(()=>{t&&(o(a&&r?`Copy of ${r}`:r||""),u(""),x(!a),p(!0))},[t,a,r]);const b=()=>{d.trim()&&(!m&&!h||c({name:d.trim(),description:i.trim()||void 0,saveToLibrary:m,saveToCurrentDashboard:h}))},f=d.trim()&&(m||h);return e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Save Visual As"}),e.jsx(s.DialogDescription,{children:a?"Create a copy of this visual with a new name":"Save this visual to make it reusable"})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"name",children:"Name"}),e.jsx(s.Input$1,{id:"name",value:d,onChange:j=>o(j.target.value),placeholder:"Enter visual name",disabled:l})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"description",children:"Description (optional)"}),e.jsx(s.Textarea,{id:"description",value:i,onChange:j=>u(j.target.value),placeholder:"Enter visual description",rows:3,disabled:l})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Label,{children:"Save to:"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"save-to-dashboard",checked:h,onCheckedChange:j=>p(!!j),disabled:l}),e.jsxs("label",{htmlFor:"save-to-dashboard",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Current Dashboard",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:a?"(add copy to this dashboard)":"(keep as local visual)"})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"save-to-library",checked:m,onCheckedChange:j=>x(!!j),disabled:l}),e.jsxs("label",{htmlFor:"save-to-library",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Visual Library",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:a?"(save as new reusable visual)":"(make available to all dashboards)"})]})]})]}),!m&&!h&&e.jsx("p",{className:"text-sm text-destructive",children:"Please select at least one destination"})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),disabled:l,children:"Cancel"}),e.jsxs(s.Button,{onClick:b,disabled:!f||l,children:[l&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Saving...":"Save"]})]})]})})}function xn({className:t,variant:n="outline"}){var o;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(i=>i.frame);const r=s.useEditorStore(i=>i.card);os(((o=r.customCardPreferences)==null?void 0:o.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),r.sql;const l=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:c}=Me();function d(){const i=c();l==null||l(i)}return e.jsxs(s.Button,{onClick:d,className:s.cn("h-8",t),size:"sm",variant:n,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function pn({className:t,variant:n="default"}){const a=s.useQueryClient(),[r,l]=k.useState(!1),c=s.useDashboardStore(h=>h.actions.setIsDashboardPanelOpen),{setIsVisualEditing:d}=s.useDashboardActions(),{getUpdatedFrame:o}=Me(),i=s.useSelectedVisual(),u=s.useEditorStore(h=>h.frame),m=s.useUpdateVisualMutation(),x=()=>{const h=o(),p=(u==null?void 0:u.visualId)||(i==null?void 0:i.id);if(!p){s.ue.error("No visual to save");return}l(!0),m.mutate({visualId:p,data:{frameObject:h}},{onSuccess:()=>{l(!1),c(!0),s.ue.success("Visual updated successfully"),a.invalidateQueries({queryKey:["resource-by-id","visual",p],exact:!0})},onError:()=>{l(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:x,className:s.cn("h-8",t),size:"sm",variant:n,children:[r&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!r&&e.jsxs(e.Fragment,{children:[e.jsx(Oe,{className:"mr-2 size-4 font-bold"}),"Save to Library"]})]})}function fn({className:t}){const n=s.useQueryClient(),[a,r]=k.useState(!1),l=s.useSelectedVisual(),c=s.useEditorStore(h=>h.frame),d=s.useDashboardStore(h=>h.selectedSheetId),{updateFrame:o,setIsVisualEditing:i}=s.useDashboardActions(),{getUpdatedFrame:u}=Me(),m=s.useUpdateVisualMutation(),x=async()=>{if(!d){s.ue.error("No sheet selected");return}const h=(c==null?void 0:c.visualId)||(l==null?void 0:l.id);if(!h){s.ue.error("No visual to update");return}r(!0);try{const p=u();await m.mutateAsync({visualId:h,data:{frameObject:p}});const b={...p,visualId:h};o(d,b),n.invalidateQueries({queryKey:["visuals"]}),n.invalidateQueries({queryKey:["visual",h]}),s.ue.success("Saved to library and applied locally"),setTimeout(()=>{i(!1)},300)}catch(p){console.error("Failed to save and apply:",p),s.ue.error("Failed to save and apply changes")}finally{r(!1)}};return e.jsx(s.Button,{onClick:x,className:s.cn("h-8",t),size:"sm",variant:"default",disabled:a,children:a?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Oe,{className:"mr-2 size-4 font-bold"}),"Save & Apply"]})})}function gn({className:t}){const{getUpdatedFrame:n}=Me();s.useEditorStore(i=>i.frame);const a=s.useDashboardStore(i=>i.selectedSheetId),{updateFrame:r,setIsVisualEditing:l}=s.useDashboardActions(),[c,d]=k.useState(!1),o=()=>{if(!a){s.ue.error("No sheet selected");return}d(!0);const u={...n(),visualId:void 0};r(a,u),setTimeout(()=>{d(!1),s.ue.success("Changes applied. Visual is now local to this dashboard"),l(!1)},300)};return e.jsxs(s.Button,{onClick:o,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[c&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Applying"]}),!c&&e.jsxs(e.Fragment,{children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Apply Locally"]})]})}function jn({className:t}){const{setTempQueryData:n,setSqlGen:a}=s.useEditorActions(),r=s.useQueryClient(),l=s.useEditorStore(u=>u.tempQueryData),c=s.useEditorStore(u=>u.onClose),d=s.useEditorStore(u=>u.card),{queryKey:o}=s.useDashboardCardQuery(d);function i(){if(l){const{queryKey:u,queryData:m}=l;u&&m&&r.setQueryData(u,m)}a({}),c==null||c()}return e.jsxs(s.Button,{onClick:i,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function is(){const{setTempQueryData:t}=s.useEditorActions(),n=s.useQueryClient();s.useEditorStore(f=>f.isDevMode);const a=s.useEditorStore(f=>f.tempQueryData),r=s.useEditorStore(f=>f.card),{queryKey:l}=s.useDashboardCardQuery(r),{setCardSql:c,setSqlGen:d,setCardPython:o,setCardCustomCfg:i,setCardPreferences:u,updateDataSource:m,clearQueryConfig:x,setCardConfig:h,setCardType:p}=s.useEditorActions();function b(){const f=n.getQueryData(l);a!=null&&a.queryData||t({queryKey:l,queryData:f}),n.setQueryData(l,null),n.removeQueries({queryKey:l,exact:!0}),c(""),d({}),x(),h(void 0),o(""),i(""),u({}),p("bar")}return e.jsxs(s.Button,{onClick:b,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(Qt,{className:"mr-2 size-4"}),"Clear"]})}function bn(){const[t,n]=k.useState(!1),[a,r]=k.useState(!1),[l,c]=k.useState(null),d=s.useEditorStore(A=>A.frame),o=s.useEditorStore(A=>A.card),i=s.useSelectedVisual(),u=s.useDashboardStore(A=>A.selectedSheetId),m=s.useDashboardStore(A=>A.actions.setIsDashboardPanelOpen),{getUpdatedFrame:x}=Me(),{selectVisual:h}=s.useManagementActions(),{addFrame:p,setSelectedFrameId:b,setIsVisualEditing:f}=s.useDashboardActions(),j=!!(d!=null&&d.visualId),N=(i==null?void 0:i.title)||(o==null?void 0:o.title)||"Untitled Visual",C=s.useCreateVisualWithFrame(A=>{if(A!=null&&A.id){if(h(A),a&&l&&u){const w={...l,id:s.v4(),visualId:A.id};p(u,w,"end"),b(w.id),r(!1),c(null),f(!1)}m(!0),n(!1)}});return{saveAsDialogOpen:t,setSaveAsDialogOpen:n,handleSaveAs:async A=>{if(!u){s.ue.error("No sheet selected");return}const w=x();if(A.saveToLibrary){r(A.saveToCurrentDashboard),c(w);const D={title:A.name,description:A.description,frameObject:w,isPrivate:!1};C.mutate(D)}else if(A.saveToCurrentDashboard){const D={...w,id:s.v4(),visualId:void 0,cards:w.cards.map(g=>({...g,title:g.id===o.id?A.name:g.title}))};p(u,D,"end"),b(D.id),s.ue.success("Visual saved to dashboard"),n(!1),f(!1)}},isLibraryVisual:j,currentVisualName:N,isSaving:C.isPending}}function rt({className:t}){const n=s.useEditorStore(C=>C.frame),a=s.useEditorStore(C=>C.card),r=s.useManagementStore(C=>C.selectedVisual),l=s.useDashboardStore(C=>C.selectedFrameId),c=s.useDashboardStore(C=>C.selectedSheetId),{setIsVisualEditing:d}=s.useDashboardActions(),o=!!(n!=null&&n.visualId||r!=null&&r.id),i=!!(n!=null&&n.visualId&&l),u=o&&!i,{saveAsDialogOpen:m,setSaveAsDialogOpen:x,handleSaveAs:h,isLibraryVisual:p,currentVisualName:b,isSaving:f}=bn(),{handleAddLibraryVisual:j}=Me(),N=async()=>{if(!c){s.ue.error("No dashboard sheet selected");return}if(!r){s.ue.error("No visual selected");return}const C=await j(r);C.success?(s.ue.success("Visual added to dashboard"),d(!1)):s.ue.error(C.error||"Failed to add visual to dashboard")};return e.jsxs(e.Fragment,{children:[!o&&e.jsx(xn,{className:t,variant:"default"}),o&&e.jsxs(e.Fragment,{children:[i&&e.jsx(gn,{className:t}),u&&c&&a&&(a.sql||s.hasValidCardConfig(a.config))&&e.jsxs(s.Button,{onClick:N,className:s.cn(t),size:"sm",variant:"outline",children:[e.jsx(Gt,{className:"mr-2 size-4 font-bold"}),"Add to Dashboard"]}),u&&e.jsx(pn,{className:t,variant:"default"}),i&&e.jsx(fn,{className:t}),e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:s.cn(t,"w-8 p-0"),children:e.jsx(s.EllipsisVertical,{className:"h-4 w-4"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.stopPropagation(),x(!0)},children:[e.jsx(Oe,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]})]}),!o&&e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:s.cn(t,"w-8 p-0"),children:e.jsx(s.EllipsisVertical,{className:"h-4 w-4"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:()=>x(!0),children:[e.jsx(Oe,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]}),e.jsx(jn,{className:t}),e.jsx(hn,{open:m,onOpenChange:C=>{f||x(C)},isLibraryVisual:p,currentVisualName:b,isSaving:f,onConfirm:h})]})}function lt({className:t,labelClassName:n,switchClassName:a}){const r=s.useEditorStore(i=>i.isDevMode),l=s.useDashboardStore(i=>i.isVisualEditing),{setIsDevMode:c}=s.useEditorActions(),{config:d}=k.useContext(s.SemaphorContext).tokenProps,o=(d==null?void 0:d.showAdvancedMode)!==!1;return!l||!o?null:e.jsxs("div",{className:s.cn("flex items-center space-x-2",t),children:[e.jsx(s.Switch,{className:s.cn("",a),checked:r,onCheckedChange:()=>c(!r),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:s.cn("text-sm font-medium",n),children:"Advanced Mode"})]})}function vn(){var xe,ce,K;const{authToken:t,tokenProps:n,id:a}=s.useSemaphorContext(),{isLocalDev:r,isConsoleMode:l}=s.useDashboardPreferences(),{permissions:c}=s.useRoleAwareDisplayPreferences(),d=s.useHasDashboardId();s.useDashboardStore(G=>G.theme);const o=s.useDashboardStore(G=>G.lenses),i=s.useDashboardStore(G=>G.selectedLensId),u=o==null?void 0:o.find(G=>G.id===i),m=s.useDashboardStore(G=>G.dashboard);s.useDashboardStore(G=>G.selectedSheetId);const x=s.useDashboardStore(G=>G.isDashboardEditing),[h,p]=k.useState(!1),[b,f]=k.useState(!1),[j,N]=k.useState(!1),C=s.useDashboardStore(G=>G.isDashboardPanelOpen),L=s.useDashboardStore(G=>G.actions.setIsDashboardPanelOpen),A=s.useDashboardStore(G=>G.filterValues),w=s.useDashboardStore(G=>G.isVisualEditing),D=s.useEditorStore(G=>G.card),g=s.useManagementStore(G=>G.selectedDashboard),y=s.useManagementStore(G=>G.initialDashboard),v=s.useManagementStore(G=>G.selectedVisual);s.useDashboardStore(G=>G.selectedFrameId),s.useEditorStore(G=>G.frame);const R=g?(ce=g==null?void 0:g.permissions)==null?void 0:ce.canEdit:(xe=y==null?void 0:y.permissions)==null?void 0:xe.canEdit,S=s.useDashboardStore(G=>G.showFilters),F=s.useDashboardStore(G=>G.showDashboardJSON),I=s.useDashboardStore(G=>G.onSaveFunction),T=s.useDashboardStore(G=>G.actions.setShowFilters),{setIsDashboardEditing:M,setShowDashboardJSON:O}=s.useDashboardStore(G=>G.actions),{setInitialDashboard:E,clearSelectedDashboard:P}=s.useManagementStore(G=>G.actions),{resources:B}=s.useResourceManagement(s.ResourceType.DASHBOARD),{currentUser:Y}=s.useCurrentUserInfo(),q=s.canUserManageGroups(Y),z=g||y,J=z?{id:z.id,title:(m==null?void 0:m.title)||z.title||"Dashboard"}:null,{handleAddNewFrame:W}=s.useAddNewFrame(),[se,te]=k.useState(!1),oe=s.useUpdateResource(s.ResourceType.DASHBOARD);k.useEffect(()=>{if(B&&B.length>0){const G=m==null?void 0:m.id;if(G){const V=B.find(Z=>Z.id===G);V&&E(V)}}},[B,m==null?void 0:m.id,E]);const Q=n.orgUserId||n.tenantId,_=x&&!w&&Q&&R,ae=()=>{M(!0)};async function H(){const G=Ke(m);te(!0);const V={template:G};oe.mutate({resourceId:G.id,data:V},{onSuccess:()=>{te(!1),s.ue.success("Dashboard saved!")},onError:()=>{te(!1),s.ue.error("Failed to save dashboard")}})}async function re(){if(p(!0),!i||!u)return;const G=Ke(m),V=JSON.stringify(G),Z={...u,template:V,filterValues:A};await ts(n.apiServiceUrl,Z,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),I==null||I(G),p(!1)}const ie=(u==null?void 0:u.name)||m.title,U=B&&B.length>0&&(n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail),X=g&&!(n!=null&&n.dashboard_id)&&!a;return e.jsxs("div",{className:"flex h-11 items-center justify-between gap-2 border-b px-4 py-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[U&&e.jsxs(e.Fragment,{children:[e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>{L(!C)},className:"h-7 p-2",children:e.jsx(ia,{className:"h-4 w-4"})}),X&&!w&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Dashboard Hub",onClick:()=>P(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})})]}),!w&&d&&e.jsx(s.Label,{children:ie}),w&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm font-medium",children:(v==null?void 0:v.title)||(D==null?void 0:D.title)||"Untitled Visual"}),e.jsx(at,{})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[w&&e.jsxs(e.Fragment,{children:[e.jsx(lt,{className:"mr-2"}),e.jsx(rt,{className:"h-7"})]}),r&&!w&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:()=>s.invalidateToken(n.apiServiceUrl),className:"h-7 p-2",children:e.jsx(xa,{className:"h-4 w-4"})}),!w&&d&&e.jsx(ka,{}),!w&&d&&e.jsx(qs,{}),!w&&d&&q&&e.jsx(s.IconButton,{tooltip:"Manage Groups",onClick:()=>N(!0),className:"h-7 p-2",children:e.jsx(s.Users,{className:"h-4 w-4"})}),!w&&d&&((K=z==null?void 0:z.permissions)==null?void 0:K.canShare)&&e.jsx(s.IconButton,{tooltip:"Share Dashboard",onClick:()=>f(!0),className:"h-7 p-2",children:e.jsx(Ie,{className:"h-4 w-4"})}),!S&&!w&&x&&c.canUseFilters&&d&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>T(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),x&&!w&&Q&&r&&d&&e.jsx(Da,{}),!w&&Q&&r&&d&&e.jsx(Ta,{}),x&&!w&&Q&&u&&r&&d&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:h,onClick:re,size:"sm",children:[e.jsx(Oe,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),x&&!w&&d&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!x,onClick:()=>W(),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Visual"]}),!w&&!x&&c.canEdit&&d&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:ae,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),_&&d&&e.jsxs(s.Button,{className:"h-7 p-2",disabled:se,onClick:H,size:"sm",children:[se?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Oe,{className:"mr-2 h-4 w-4"}),se?"Saving...":"Save"]}),!w&&x&&r&&d&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>O(!F),size:"sm",variant:"ghost",children:e.jsx(Us,{className:"h-4 w-4"})})}),!w&&r&&e.jsx(Na,{}),x&&!w&&d&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{M(!1),O(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),b&&J&&e.jsx(We,{resource:J,resourceType:s.ResourceType.DASHBOARD,onClose:()=>f(!1)}),e.jsx(ln,{open:j,onOpenChange:N})]})]})}function cs(t){const{tokenProps:n,authToken:a}=s.useSemaphorContext(),r=n==null?void 0:n.apiServiceUrl;return s.useQuery({queryKey:["joinability-map",t],queryFn:async()=>{if(!t||!(a!=null&&a.accessToken))return null;const l=`${r}/v1/domains/${t}/joinability`;return s.getRequest(l,a.accessToken)},enabled:!!t&&!!(a!=null&&a.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:l=>Math.min(1e3*2**l,3e4)})}function Ve(t,n,a){if(n==="source")return{isValid:!0};const r=s.getDataType(t.dataType);if(a==="kpi"){if(n==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(n==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function as(t,n,a,r,l){if(t!=="kpi"||l.length<3)return;const c=(n==null?void 0:n.groupByColumns)&&n.groupByColumns.length>0,d=(n==null?void 0:n.comparisonType)==="none";!c&&d||a(r,{groupByColumns:[],comparisonType:"none"})}const ds=t=>{var I;const n=(I=t==null?void 0:t.dataSource)==null?void 0:I.semanticDomainId,{data:a}=cs(n),{updateCardConfig:r,updateGroupByColumn:l,updateMetricColumn:c,updatePivotByColumn:d,updateSortByColumn:o,removeGroupByColumn:i,removeMetricColumn:u,removePivotByColumn:m,removeSortByColumn:x}=s.useEditorActions(),h=s.useEditorStore(T=>T.card.type),p=t==null?void 0:t.id,b=k.useCallback(T=>{if(!(t!=null&&t.config))return[];switch(T){case"groupBy":return(t.config.groupByColumns||[]).map(M=>({id:M.id,name:M.name,dataType:M.dataType,label:M.label!==void 0?M.label:M.name,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType,dateFormat:M.dateFormat,customFormat:M.customFormat,granularity:M.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(M=>({id:M.id,name:M.name,dataType:M.dataType,label:M.label!==void 0?M.label:M.name,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(M=>({id:M.id,name:M.name,dataType:M.dataType,label:M.label!==void 0?M.label:M.name,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType,direction:M.direction}));case"source":return[];default:return[]}},[t]),f=k.useCallback((T,M)=>{if(p)switch(T){case"groupBy":{r(p,{groupByColumns:M});break}case"metrics":{r(p,{metricColumns:M});break}case"pivotBy":{r(p,{pivotByColumns:M});break}case"sortBy":{r(p,{sortByColumns:M});break}}},[p,r]),j=k.useCallback((T,M,O)=>{if(!p)return;const P=b(T)[M];if(P)switch(T){case"groupBy":l(p,P.id,{label:O});break;case"metrics":c(p,P.id,{label:O});break;case"pivotBy":d(p,P.id,{label:O});break;case"sortBy":o(p,P.id,{label:O});break}},[p,b,l,c,d,o]),N=k.useCallback((T,M)=>{if(!p)return;const E=b("metrics")[T];E&&c(p,E.id,{aggregate:M,label:s.getAggregationLabel(E.name,M)})},[p,b,c]),C=k.useCallback((T,M,O)=>{if(!p)return;const P=b("groupBy")[T];if(!P)return;const B={dateFormat:M};M==="custom"&&O?B.customFormat=O:B.customFormat=void 0,l(p,P.id,B)},[p,b,l]),L=k.useCallback((T,M)=>{if(!p)return;const E=b("groupBy")[T];E&&l(p,E.id,{granularity:M})},[p,b,l]),A=k.useCallback((T,M)=>{if(!p)return;const E=b("metrics")[T];E&&c(p,E.id,{aliasTemplate:M})},[p,b,c]),w=k.useCallback((T,M)=>{if(console.log("handleValueAliasesChange",T,M),!p)return;console.log("handleValueAliasesChange",T,M);const E=b("metrics")[T];E&&(console.log("handleValueAliasesChange",M),c(p,E.id,{valueAliases:M}))},[p,b,c]),D=k.useCallback(T=>{if(!p)return;if(b("metrics").length===0){s.ue.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(p,{comparisonType:T})},[p,r,b]),g=k.useCallback(T=>{p&&r(p,{showTrendline:T})},[p,r]),y=k.useCallback(T=>{p&&r(p,{trendlineWindow:T})},[p,r]),v=k.useCallback(T=>{p&&r(p,{trendlineGranularity:T})},[p,r]),R=k.useCallback(T=>{p&&r(p,{targetValue:T})},[p,r]),S=k.useCallback(T=>{var q;if(!p)return;const M=[...b("groupBy"),...b("pivotBy"),...b("metrics"),...b("sortBy")],O=s.validateEntityConsistency(T,M,{joinPlan:(q=t==null?void 0:t.config)==null?void 0:q.joinPlan,joinabilityMap:a==null?void 0:a.joinabilityMap,semanticDomainId:n});if(!O.isValid){O.showError&&s.showJoinRequiredNotification();return}const E=s.getSmartContainerForField(T,M,h);if(!E){s.ue.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const P=Ve(T,E,h);if(!P.isValid){s.ue.error("Invalid Field Type",{description:P.reason,position:"top-center",duration:3e3});return}const B=b(E);if(s.fieldAlreadyExists(T,B))return;const Y=s.getNewField(T,E,B);if(Y){const z=[...B,Y];f(E,z),E==="metrics"&&as(h,t==null?void 0:t.config,r,p,z)}},[p,t==null?void 0:t.config,b,f,n,a,h,r]),F=k.useCallback((T,M)=>{if(!p)return;const E=b(T)[M];if(E){if(T!=="sortBy"){const P=b("sortBy"),B=P.filter(Y=>!(Y.name===E.name&&Y.qualifiedEntityName===E.qualifiedEntityName));B.length!==P.length&&r(p,{sortByColumns:B})}switch(T){case"groupBy":i(p,E.id);break;case"metrics":u(p,E.id);break;case"pivotBy":m(p,E.id);break;case"sortBy":x(p,E.id);break}}},[p,b,i,u,m,x,r]);return{getFieldsForContainer:b,setFieldsForContainer:f,updateLabel:j,handleAggregationChange:N,handleDateFormatChange:C,handleGranularityChange:L,handleAliasTemplateChange:A,handleValueAliasesChange:w,removeField:F,handleFieldClick:S,handleKpiComparisonTypeChange:D,handleKpiShowTrendlineChange:g,handleKpiTrendlineWindowChange:y,handleKpiTrendlineGranularityChange:v,handleKpiTargetValueChange:R,cardType:h}};function _e(t){return`${t}-${s.v4()}`}function ks(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"SUM":return`Sum of ${a}`;case"COUNT":return`Count of ${a}`;case"DISTINCT":return`Unique ${a}`;case"AVG":return`Average of ${a}`;case"MIN":return`Min of ${a}`;case"MAX":return`Max of ${a}`;default:return a}}function yn(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"day":return`Date of ${a}`;case"week":return`Week of ${a}`;case"month":return`Month of ${a}`;case"year":return`Year of ${a}`;default:return a}}function us(t){if(!t||!t.selectedEntities||t.selectedEntities.length===0)return{tableName:void 0,schemaName:void 0,databaseName:void 0,connectionId:t==null?void 0:t.connectionId,connectionType:t==null?void 0:t.connectionType};const n=t.selectedEntities[0];return{tableName:n==null?void 0:n.name,schemaName:n==null?void 0:n.schema,databaseName:n==null?void 0:n.database,connectionId:t.connectionId,connectionType:t.connectionType}}function ot(t){if(!t||!t.selectedEntities||t.selectedEntities.length===0)return!1;const n=t.selectedEntities[0];return!!(n!=null&&n.name)}function it(){const t=s.useEditorStore(D=>D.sqlGen),n=s.useEditorStore(D=>D.isDevMode),a=s.useEditorStore(D=>D.card.dataSource),r=s.useEditorStore(D=>{var g,y;return(y=(g=D.card)==null?void 0:g.queryConfig)==null?void 0:y.metricColumns}),{tableName:l,schemaName:c,databaseName:d}=us(a),o=ot(a),i=s.useEditorStore(D=>D.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:m,setCardSql:x,setRunSql:h,setSqlGen:p,setIsShowingVisual:b}=s.useEditorActions(),{connectionType:f,modelItems:j,selectedDatamodelName:N}=s.useEditorAside(),C=D=>({column_name:D.name,data_type:D.dataType,label:D.label,description:D.description});return{handleDevModeFieldClick:D=>{var y;if(!n)return;const g=C(D);if(n&&o&&l){const v=s.createSqlGenConfig(g,t);p(v);const R=(y=j==null?void 0:j.find(F=>F.id===i))==null?void 0:y.name,S=s.getSql(v,s.fmt(c||""),s.fmt(l),R||"",f,d||"");S&&(x(S),h(!0))}else if(!n){if(s.isTextDataType(g.data_type))if(r&&r.length>0){const v={...g,role:"groupby",id:_e(g.column_name),name:g.column_name,type:g.data_type};m(v)}else{const v={...g,role:"metric",id:_e(g.column_name),name:g.column_name,label:ks(g.column_name,"COUNT"),type:g.data_type,aggregate:"COUNT"};u(v)}if(s.isDateDataType(g.data_type)){const v={...g,role:"groupby",id:_e(g.column_name),name:g.column_name,type:g.data_type,label:yn(g.column_name,"month"),granularity:"month"};m(v)}if(s.isNumberDataType(g.data_type)){const v={...g,role:"metric",id:_e(g.column_name),name:g.column_name,label:ks(g.column_name,"SUM"),type:g.data_type,aggregate:"SUM"};u(v)}}},handleShowSample:()=>{if(!o||!l){console.warn("Cannot generate SQL: missing table metadata");return}const D=s.getFormattedTableNameForQuery({schemaName:c||"",tableName:l,modelName:N,connectionType:f,databaseName:d||""});b(!1);const g=f==="MSSQL"?`SELECT top 10 * FROM ${D}`:`SELECT * FROM ${D} LIMIT 10`;x(g),h(!0)},handleShowCount:()=>{if(!o||!l){console.warn("Cannot generate SQL: missing table metadata");return}const D=s.getFormattedTableNameForQuery({schemaName:c||"",tableName:l,modelName:N,connectionType:f,databaseName:d||""});x(`SELECT COUNT(*) as count FROM ${D}`),h(!0)},isNumberField:D=>s.isNumberDataType(D.dataType)}}function ct(){const t=s.useEditorStore(p=>p.selectedConnectionId),n=s.useEditorStore(p=>p.selectedDatamodelId),a=s.useEditorStore(p=>p.selectedDatabaseName),r=s.useEditorStore(p=>p.selectedSchemaName),l=s.useEditorStore(p=>p.selectedTableName),c=s.useDashboardStore(p=>p.dashboard.filters)||[],d=s.useDashboardStore(p=>p.actions.addFilter),o=s.useDashboardStore(p=>p.actions.removeFilter),{removeFilterValues:i}=s.useDashboardActions(),{modelItems:u,tableName:m,connectionType:x}=s.useEditorAside();function h(p,b="dashboard",f){var y;const j=s.fmt(p.column_name),N=s.fmt(a||""),C=s.fmt(r||""),L=s.fmt(m);let A=s.getQualifiedTableName({schemaName:C,tableName:L,connectionType:x,databaseName:N}),w=`${A}.${j}`;const D=(y=u==null?void 0:u.find(v=>v.id===n))==null?void 0:y.name;n&&n!=="none"&&(w=`${s.DATAMODEL_NAMESPCACE}.${D}.${j}`,A=`${s.DATAMODEL_NAMESPCACE}.${D}`),f!=null&&f.qualifiedFieldName&&(w=f.qualifiedFieldName),f!=null&&f.entityName&&(A=f.entityName);const g=c==null?void 0:c.find(v=>v.column===w&&v.table===L&&(v.database===N||v.database===a));if(g)i(g.id),o(g.id);else{const v=s.v4();return m==="api"&&t?(d({location:b,id:v,column:w,title:p.column_name,dataType:p.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(p.data_type,A,j)}),v):(d({id:v,location:b,column:w,title:p.column_name,dataType:p.data_type,table:l||"",database:a||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(p.data_type,A,j)}),v)}}return{assignFilter:h}}function Nn({column:t}){const[n,a]=k.useState(!1),r=s.useEditorStore(N=>N.card.dataSource),{tableName:l,schemaName:c,databaseName:d}=us(r),o=s.useEditorStore(N=>N.selectedDatamodelId),i=s.useEditorStore(N=>N.sqlGen),{modelItems:u,connectionType:m}=s.useEditorAside(),x=s.useEditorStore(N=>N.actions.setSqlGen),h=s.useEditorStore(N=>N.actions.setCardSql),p=s.useEditorStore(N=>N.actions.setRunSql),b=ot(r);function f(N,C){var D;if(!b||!l){console.warn("Cannot generate SQL: missing table metadata");return}const L=s.createSqlGenConfig(N,i,C),A=(D=u==null?void 0:u.find(g=>g.id===o))==null?void 0:D.name;x(L);const w=s.getSql(L,s.fmt(c||""),s.fmt(l),A||"",m,d||"");w&&(h(w),p(!0)),a(!1)}function j(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>f(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>f(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>f(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>f(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>f(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return b?e.jsxs(s.HoverCard,{openDelay:0,open:n,onOpenChange:a,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:j()})]}):null}function Cn({field:t,fieldState:n}){return e.jsxs("div",{className:"w-64 bg-background p-0",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground",children:t.label||t.name}),e.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:t.dataType})]}),t.description&&e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:t.description}),n&&n.tooltip&&e.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:n.tooltip})}),e.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.name})})]})}function Sn({field:t,context:n="editor",fieldState:a}){const r=s.useEditorStore(S=>S.isDevMode),l=n==="filter",c=r||l||(a==null?void 0:a.state)==="unreachable"&&!l,d=s.useDashboardStore(S=>S.dashboard.filters),{assignFilter:o}=ct(),i=l&&(d==null?void 0:d.some(S=>{var F;return S.title===t.name||((F=S.column)==null?void 0:F.includes(t.name))})),{attributes:u,listeners:m,setNodeRef:x,transform:h,transition:p,isDragging:b}=s.useSortable({id:t.id,disabled:c}),[f,j]=k.useState(!1),N=s.useEditorStore(S=>S.card),{handleFieldClick:C}=ds(N),{handleDevModeFieldClick:L,isNumberField:A}=it(),w=()=>{if(l){const S={column_name:t.name,data_type:t.dataType,label:t.label,description:t.description};o(S,"dashboard",t)}else r?L(t):C(t)},D={column_name:t.name,data_type:t.dataType,label:t.label,description:t.description},g={transform:s.CSS.Transform.toString(h),transition:p},v=(()=>{if(!a||l)return{};const F={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[a.state]||{};return a.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",...F},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...F},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...F}}[a.state]||F})(),R=S=>{const F=(S||"").toLowerCase(),I=s.getDataType(F);return I==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(qe,{className:"h-3 w-3"})}):I==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(rs,{className:"h-3 w-3"})}):I==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):I==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx($s,{className:"h-3 w-3"})}):I==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Us,{className:"h-3 w-3"})}):I==="geo"?e.jsx("div",{className:"bg-orange -100 flex size-6 shrink-0 items-center justify-center rounded-sm text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(oa,{className:"h-3 w-3"})}):I==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(zs,{className:"h-3 w-3"})}):null};return e.jsxs("div",{ref:x,style:g,...c?{}:u,...c?{}:m,className:s.cn("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",b&&"scale-95 opacity-50",!b&&"border",v.borderColor||"border-transparent",v.bgColor||"",v.hoverBorderColor,v.hoverBgColor||"hover:bg-muted",v.opacity,v.cursor,i&&"bg-accent border-accent-foreground/20",{"cursor-pointer":r||l,"cursor-grab active:cursor-grabbing":!c&&!r&&!l}),title:a==null?void 0:a.tooltip,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:w,children:[R(t.dataType),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${f?"whitespace-normal break-words":"truncate"}`,children:t.label||t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:e.jsx(Cn,{field:t,fieldState:a})})]})}),r&&!l&&A(t)&&e.jsx("div",{onClick:S=>S.stopPropagation(),children:e.jsx(Nn,{column:D})})]}),f&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(s.Card,{className:"",children:e.jsxs(s.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gs,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.label||t.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ba,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.name})]}),e.jsx(s.Badge,{variant:"outline",className:"mt-2 text-xs",children:t.dataType})]})})})]})}function wn({context:t="editor"}={}){var I,T,M,O;const[n,a]=k.useState(""),[r,l]=k.useState("all"),c=s.useEditorStore(E=>E.isDevMode),d=s.useEditorStore(E=>E.card.dataSource),o=s.useEditorStore(E=>E.card.config),i=s.useEditorStore(E=>E.card),{autoJoinMetadata:u}=s.useDashboardCardQuery(i),{columns:m=[],columnGroups:x=[],isLoading:h,error:p}=s.useColumns(),b=(d==null?void 0:d.mode)==="semanticDomain"?d.semanticDomainId:void 0,{data:f}=cs(b),j=[...(o==null?void 0:o.groupByColumns)||[],...(o==null?void 0:o.metricColumns)||[]];(T=(I=o==null?void 0:o.joinPlan)==null?void 0:I.baseEntity)==null||T.name,(O=(M=u==null?void 0:u.resolvedJoinPlan)==null?void 0:M.baseEntity)==null||O.name;const{handleShowSample:N,handleShowCount:C}=it(),L=m.filter(E=>E.name.toLowerCase().includes(n.toLowerCase())||E.dataType.toLowerCase().includes(n.toLowerCase())||E.label&&E.label.toLowerCase().includes(n.toLowerCase())||E.qualifiedEntityName&&E.qualifiedEntityName.toLowerCase().includes(n.toLowerCase())),A=E=>{if(E.dataType==="number"||E.dataType==="integer"||E.dataType==="float"||E.dataType==="decimal"||E.dataType==="currency")return"metrics";const P=s.getDataType(E.dataType);return["date","string","boolean"].includes(P)?"dimensions":P==="number"?"metrics":"dimensions"},D=(r==="all"?L:L.filter(E=>A(E)===r)).reduce((E,P)=>{const B=P.qualifiedEntityName||"Other Fields";return E[B]||(E[B]={label:s.toLabel(P.entityName),fields:[]}),E[B].fields.push(P),E},{}),y=Object.keys(D),v=L.filter(E=>A(E)==="dimensions").length,R=L.filter(E=>A(E)==="metrics").length,S=L.filter(E=>A(E)==="calculated").length,F=L.length>0;return h?e.jsx("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):p?e.jsxs("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:p.message||"Failed to load column data"})]}):!d||!d.selectedEntities||d.selectedEntities.length===0?e.jsx(s.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:t==="filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-full w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[c&&t!=="filter"&&m.length>0&&e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:h,onClick:N,size:"sm",variant:"secondary",className:"grow",children:[h?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(la,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:h,onClick:C,size:"sm",variant:"secondary",className:"grow",children:[h?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(pa,{className:"mr-2 size-4"}),"Count"]})]}),m.length>0&&e.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:n,onChange:E=>a(E.target.value)}),n&&e.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>a(""),type:"button",children:e.jsx(s.X,{className:"size-3.5"})})]}),F&&e.jsx(s.Tabs,{defaultValue:"all",value:r,onValueChange:E=>l(E),className:"mb-4",children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:L.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:v})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:R})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(zs,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:S})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:y,className:"space-y-2",children:Object.entries(D).map(([E,P])=>{const B=x.find(Y=>Y.entityName===E)||{entityName:E,label:P.label};return e.jsxs(s.AccordionItem,{value:E,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{title:B.label||B.entityName,className:"flex items-center gap-2",children:[e.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:B.label||B.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:P.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:P.fields.map(Y=>{const q=s.calculateFieldState(Y,{joinabilityMap:(f==null?void 0:f.joinabilityMap)||null,selectedFields:j,cardConfig:o,autoJoinMetadata:u});return e.jsx(Sn,{field:Y,context:t,fieldState:q},Y.id)})})})]},E)})}),Object.keys(D).length===0&&m.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:t==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),Object.keys(D).length===0&&m.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),e.jsx(s.ScrollBar,{orientation:"horizontal"}),e.jsx(s.ScrollBar,{orientation:"vertical"})]})]})}function dt({context:t="editor"}={}){return e.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",e.jsx(wn,{context:t})," "]})}function Dn({initialJoinPlan:t,availableDataSources:n}){const[a,r]=k.useState(t),[l,c]=k.useState(new Set),d=()=>{const D=a.joins.length>0?Math.max(...a.joins.map(y=>y.sequence))+1:1,g={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:D,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,g]}),c(new Set([...l,g.id]))},o=D=>{r({...a,joins:a.joins.filter(g=>g.id!==D)}),c(new Set([...l].filter(g=>g!==D)))},i=(D,g)=>{var S,F;const y=a.joins.find(I=>I.id===D);if(!y)return;const v={...y,...g},R=a.joins.map(I=>I.id===D?v:I);if((S=v.source)!=null&&S.name&&((F=v.target)!=null&&F.name)&&v.joinKeyGroups[0].keys.length===0){const I=n.find(E=>{var P;return E.name===((P=v.source)==null?void 0:P.name)}),T=n.find(E=>{var P;return E.name===((P=v.target)==null?void 0:P.name)}),M={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(T==null?void 0:T.name)||"",entityName:(T==null?void 0:T.name)||"",entityType:(T==null?void 0:T.type)||"table"},operator:"="},O=[...v.joinKeyGroups];O[0]={...O[0],keys:[M]},v.joinKeyGroups=O,R[R.findIndex(E=>E.id===D)]=v}r({...a,joins:R})};return{joinPlan:a,expandedJoins:l,setJoinPlan:r,addJoin:d,removeJoin:o,updateJoin:i,moveJoinUp:D=>{const g=a.joins.findIndex(y=>y.id===D);if(g>0){const y=[...a.joins],v={...y[g]},R={...y[g-1]};y[g]=R,y[g-1]=v,y.forEach((F,I)=>{F.sequence=I+1});const S={...a,joins:y};r(S)}},moveJoinDown:D=>{const g=a.joins.findIndex(y=>y.id===D);if(g<a.joins.length-1){const y=[...a.joins],v={...y[g]},R={...y[g+1]};y[g]=R,y[g+1]=v,y.forEach((F,I)=>{F.sequence=I+1});const S={...a,joins:y};r(S)}},toggleJoinExpansion:D=>{const g=new Set(l);g.has(D)?g.delete(D):g.add(D),c(g)},getAvailableSourceEntities:D=>{if(a.joins.length===0)return n;const g=a.joins.findIndex(v=>v.id===D);if(g===0)return n;const y=new Set;return a.baseEntity.name&&y.add(a.baseEntity.name),a.joins.slice(0,g).forEach(v=>{y.add(v.source.name),y.add(v.target.name)}),n.filter(v=>y.has(v.name))},getAvailableTargetEntities:D=>n.filter(g=>g.name!==D),addJoinKeyGroup:D=>{const g=a.joins.find(v=>v.id===D);if(!g)return;const y=[...g.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];i(D,{joinKeyGroups:y})},updateGroupOperator:(D,g,y)=>{const v=a.joins.find(S=>S.id===D);if(!v)return;const R=[...v.joinKeyGroups];R[g]={...R[g],operator:y},i(D,{joinKeyGroups:R})},removeJoinKeyGroup:(D,g)=>{const y=a.joins.find(R=>R.id===D);if(!y)return;const v=[...y.joinKeyGroups];v.splice(g,1),i(D,{joinKeyGroups:v})},addJoinKey:(D,g)=>{const y=a.joins.find(I=>I.id===D);if(!y)return;const v=n.find(I=>I.name===y.source.name),R=n.find(I=>I.name===y.target.name),S=[...y.joinKeyGroups],F={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(v==null?void 0:v.name)||"",entityName:(v==null?void 0:v.name)||"",entityType:(v==null?void 0:v.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(R==null?void 0:R.name)||"",entityName:(R==null?void 0:R.name)||"",entityType:(R==null?void 0:R.type)||"table"},operator:"="};S[g]={...S[g],keys:[...S[g].keys,F]},i(D,{joinKeyGroups:S})},updateJoinKey:(D,g,y,v,R)=>{const S=a.joins.find(O=>O.id===D);if(!S)return;const F=n.find(O=>O.name===S.source.name),I=n.find(O=>O.name===S.target.name),T=[...S.joinKeyGroups],M=T[g].keys[y];v==="sourceColumnName"&&F?T[g].keys[y]={...M,source:{...M.source,name:R}}:v==="targetColumnName"&&I?T[g].keys[y]={...M,target:{...M.target,name:R}}:v==="operator"&&(T[g].keys[y]={...M,operator:R}),i(D,{joinKeyGroups:T})},removeJoinKey:(D,g,y)=>{const v=a.joins.find(S=>S.id===D);if(!v)return;const R=[...v.joinKeyGroups];R[g].keys.splice(y,1),i(D,{joinKeyGroups:R})},generateSQLPreview:()=>{const D=[...a.joins].sort((v,R)=>v.sequence-R.sequence),g=a.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let y=`SELECT *
|
|
256
|
+
*/const ya=s.createLucideIcon("Wand",[["path",{d:"M15 4V2",key:"z1p9b7"}],["path",{d:"M15 16v-2",key:"px0unx"}],["path",{d:"M8 9h2",key:"1g203m"}],["path",{d:"M20 9h2",key:"19tzq7"}],["path",{d:"M17.8 11.8 19 13",key:"yihg8r"}],["path",{d:"M15 9h.01",key:"x1ddxp"}],["path",{d:"M17.8 6.2 19 5",key:"fd4us0"}],["path",{d:"m3 21 9-9",key:"1jfql5"}],["path",{d:"M12.2 6.2 11 5",key:"i3da3b"}]]);function Na(){const{setTheme:t}=s.useTheme(),n=s.useDashboardStore(a=>a.actions.setDashboardTheme);return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"h-7 p-2",variant:"ghost",size:"sm",children:[e.jsx(ga,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(ca,{strokeWidth:1.5,className:"absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),e.jsx("span",{className:"sr-only",children:"Toggle theme"})]})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuItem,{onClick:()=>{t("light"),n("light")},children:"Light"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("dark"),n("dark")},children:"Dark"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("system"),n("system")},children:"System"})]})]})}function Ke(t){var n;return{...t,sheets:(n=t==null?void 0:t.sheets)==null?void 0:n.map(a=>{var r;return{...a,frames:(r=a.frames)==null?void 0:r.map(l=>{var c;return{...l,cards:(c=l.cards)==null?void 0:c.map(d=>Ys(d))}})}})}}function Ys(t){return{...t,customCfg:Ca(t.customCfg),data:[]}}function Ca(t){var n,a;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(a=(n=t==null?void 0:t.data)==null?void 0:n.datasets)==null?void 0:a.map(r=>({...r,data:[]}))}}:null}async function Sa(t,n,a,r,l){if(!l)return null;const c=JSON.stringify(a),d=`${t}/v1/lens`;return await s.postRequest(d,l,{name:n,template:c,filterValues:r,operation:"create"})}async function ts(t,n,a){if(!a)return null;const{id:r,template:l,filterValues:c,isDefault:d,shared:o}=n,i=`${t}/v1/lens`;return await s.postRequest(i,a,{lensId:r,template:l,filterValues:c,isDefault:d,shared:o,operation:"update"})}async function wa(t,n,a){if(!a)return null;const r=`${t}/v1/lens`;return await s.postRequest(r,a,{operation:"delete",lensId:n})}function Da(){const[t,n]=k.useState(""),[a,r]=k.useState(!1),l=s.useDashboardStore(j=>j.lenses),{setLenses:c,setSelectedLensId:d}=s.useDashboardActions(),[o,i]=k.useState(!1),[u,m]=k.useState(!1),x=s.useDashboardStore(j=>j.dashboard),h=s.useDashboardStore(j=>j.filterValues),{authToken:p,tokenProps:b}=s.useSemaphorContext();async function f(){i(!0);const j=Ke(x),N=await Sa(b.apiServiceUrl,t,j,h,p==null?void 0:p.accessToken);N&&(c([...l||[],N]),d(N.id),m(!1)),i(!1)}return e.jsxs(s.Dialog,{open:u,onOpenChange:m,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange:j=>{n(j.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),a&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:f,disabled:o,children:o?"Creating...":"Add"})})]})]})}function Ta(){const[t,n]=k.useState(!1),a=s.useDashboardStore(x=>x.lenses),r=s.useDashboardStore(x=>x.selectedLensId),{setLenses:l,setSelectedLensId:c}=s.useDashboardActions(),{authToken:d,tokenProps:o}=s.useSemaphorContext();async function i(x){c(x)}async function u(x){if(await wa(o.apiServiceUrl,x,d==null?void 0:d.accessToken)){const p=a==null?void 0:a.filter(b=>b.id!==x);l(p||[]),c("original")}}async function m(x){const h=a==null?void 0:a.map(f=>f.id===x.id?{...f,isDefault:!x.isDefault}:{...f,isDefault:!1});l(h||[]);const p={...x,isDefault:!x.isDefault};await ts(o.apiServiceUrl,p,d==null?void 0:d.accessToken);const b=a==null?void 0:a.find(f=>f.isDefault);if(b&&b.id!==x.id){const f={...b,isDefault:!1};await ts(o.apiServiceUrl,f,d==null?void 0:d.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:n,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(ea,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:i,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),a==null?void 0:a.map(x=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:x.id,children:[e.jsx("p",{children:x.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:h=>{h.preventDefault(),m(x)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!x.isDefault,"text-green-500":x.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:h=>{h.preventDefault(),u(x.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},x.id))]})]})]})}function ka({iconClassName:t}){const[n,a]=k.useState(!1),[r,l]=k.useState(""),[c,d]=k.useState(!1),o=s.useDashboardStore(x=>x.isDownloadingPdf),{tokenProps:i}=s.useSemaphorContext();async function u(){const x=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(i.apiServiceUrl),s.ue.dismiss(x),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(h){s.ue.dismiss(x),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",h)}}async function m(){if(!r)return;a(!1),l(""),d(!1);const x=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(i.apiServiceUrl,r),s.ue.dismiss(x),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(h){s.ue.dismiss(x),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",h)}}return e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:o,children:e.jsx(s.Download,{className:s.cn("size-4",t)})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsxs(s.DropdownMenuItem,{onClick:u,children:[e.jsx(s.File,{className:"mr-2 h-4 w-4"}),"Download PDF"]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>a(!0),children:[e.jsx(s.Lock,{className:"mr-2 h-4 w-4"}),"Download Protected PDF"]})]})]}),e.jsx(s.Dialog,{open:n,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Download Protected PDF"}),e.jsx(s.DialogDescription,{children:"Enter a password to protect your PDF. The PDF will be encrypted and require this password to open."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Input,{id:"password",type:c?"text":"password",value:r,onChange:x=>l(x.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:x=>{x.key==="Enter"&&r&&m()}}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>d(!c),children:c?e.jsx(s.EyeOff,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(s.Eye,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:m,disabled:!r,children:"Download"})]})]})})]})}function qs({triggerButtonClassName:t}){const[n,a]=k.useState(!1),r=s.useDashboardStore(o=>{var i;return(i=o.dashboard)==null?void 0:i.id}),l=s.useDashboardStore(o=>{var i;return(i=o.dashboard)==null?void 0:i.title}),c=s.useDashboardStore(o=>{var i;return(i=o.dashboard)==null?void 0:i.sheets}),d=s.useDashboardStore(o=>o.selectedSheetId);return c==null||c.find(o=>o.id===d),r?e.jsxs(e.Fragment,{children:[e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),onClick:()=>a(!0),children:e.jsx(s.Clock,{className:"size-4"})}),e.jsx(s.EmailScheduleDialog,{open:n,onOpenChange:a,dashboardId:r,dashboardName:l})]}):null}function Qe({value:t,onChange:n,placeholder:a="Search users by name, email, or department..."}){return e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:a,value:t,onChange:r=>n(r.target.value),className:"pl-9"})]})}function Ae({currentRole:t,onRoleChange:n,roleOptions:a,disabled:r=!1,className:l="",allowDropdown:c=!0}){var i;const d=((i=a.find(u=>u.value===t))==null?void 0:i.label)||t,o=a.filter(u=>u.value!==t);return c?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${l}`,children:d})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:o.map(u=>e.jsx(s.DropdownMenuItem,{onClick:()=>n(u.value),disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})},u.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${l}`,children:d})}function Ks({selectedUsers:t,selectedUserObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(c=>a(c.id)),className:"h-7 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.map(c=>{const d=t.find(i=>i.id===c.id),o=l(c.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[c.name,e.jsx(Ae,{currentRole:(d==null?void 0:d.role)||"VIEWER",onRoleChange:i=>r(c.id,i),roleOptions:o}),e.jsx("button",{onClick:()=>a(c.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},c.id)})}),e.jsx(s.Separator,{})]})}function Qs({usersToRemove:t,allUsers:n,onRemove:a}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium text-destructive",children:["Users to Remove Access (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(r=>a(r)),className:"h-auto p-1 text-xs text-destructive hover:text-destructive",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>a(r.id),className:"ml-1 rounded-full p-0.5 hover:bg-destructive-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},r.id))}),e.jsx(s.Separator,{})]})}function Hs({usersToUpdate:t,allUsers:n,onRemove:a,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),c=o=>{const i=n.find(u=>u.id===o);return(i==null?void 0:i.name)||"Unknown User"},d=o=>{const i=l.find(u=>u.value===o);return(i==null?void 0:i.label)||o};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(o=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:c(o.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:d(o.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:d(o.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>a(o.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},o.id))})]})}function Ws(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,l=k.useRef(null);return k.useEffect(()=>{const c=d=>{const o=d.target;l.current&&l.current.contains(o)||o instanceof Element&&(o.closest("[data-radix-popper-content-wrapper]")||o.closest("[data-radix-select-content]")||o.closest("[data-radix-popover-content]")||o.closest("[data-radix-dropdown-menu-content]")||o.closest("[data-radix-tooltip-content]")||o.closest('[role="listbox"]')||o.closest('[role="option"]')||o.closest('[role="combobox"]'))||o instanceof Element&&o.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,c),()=>{document.removeEventListener(r,c)}},[t,a,r]),l}function Ne(t,n){var a;return((a=n.find(r=>r.value===t))==null?void 0:a.label)||t}function Ea(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function Js(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function Ia(t,n,a){const r=Js(t),l=(a==null?void 0:a.type)||"organization";if(!(!n||!n.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in n.shares)return(n.shares.specificOrgUsers||[]).find(o=>o.orgUserId===t.id)}else return(n.shares.specificTenantUsers||[]).find(o=>o.tenantUserId===t.id);else return(n.shares.specificTenantUsers||[]).find(o=>o.tenantUserId===t.id)}function Aa({user:t}){return Js(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 Ma({user:t,userShare:n,usersToUpdate:a,currentUser:r,getRoleOptions:l,handleUpdateAccess:c}){if(!(n!=null&&n.role))return null;const d=Ea((r==null?void 0:r.type)||""),o=a.some(x=>x.id===t.id),i=a.find(x=>x.id===t.id),u=i?i.newRole:n==null?void 0:n.role,m=l(t.type);return n?e.jsx("div",{className:"flex items-center gap-2",children:d?e.jsx(Ae,{currentRole:u,onRoleChange:x=>{c(t.id,n.role,x)},roleOptions:m,disabled:!d,allowDropdown:d,className:o?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:Ne(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function Ra({hasAccess:t,isUserRemoving:n,isSelected:a,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!n&&e.jsxs(s.Badge,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Has Access"]}),n&&e.jsxs(s.Badge,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[e.jsx(s.X,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),a&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(Ie,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function La({isUserRemoving:t,isRemoving:n}){return e.jsx(e.Fragment,{children:t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:n?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"})})}function Fa({existingShares:t,allUsers:n,getRoleOptions:a,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const d=t.shares,o=d.specificOrgUsers||[],i=d.specificTenantUsers||[],u=d.orgWide||[],m=d.orgUsersOnly||[],x=d.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",o.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[o.slice(0,3).map((h,p)=>{var N,C;const b=((N=n.find(L=>L.id===h.orgUserId))==null?void 0:N.name)||"Unknown User",f=((C=n.find(L=>L.id===h.orgUserId))==null?void 0:C.type)||"",j=Ne(h.role,a(f));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:b}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},p)}),o.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),i.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 (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((h,p)=>{var N,C;const b=((N=n.find(L=>L.id===h.tenantUserId))==null?void 0:N.name)||"Unknown User",f=((C=n.find(L=>L.id===h.tenantUserId))==null?void 0:C.type)||"",j=Ne(h.role,a(f));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:b}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:j})]},p)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.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((h,p)=>{const b=Ne(h.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},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((h,p)=>{const b=Ne(h.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},p)})})]}),x.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:x.map((h,p)=>{const b=Ne(h.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},p)})})]}),!o.length&&!i.length&&!u.length&&!m.length&&!x.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const d=t.shares.specificTenantUsers||[],o=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[d.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",d.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[d.slice(0,3).map((i,u)=>{var p,b;const m=((p=n.find(f=>f.id===i.tenantUserId))==null?void 0:p.name)||"Unknown User",x=((b=n.find(f=>f.id===i.tenantUserId))==null?void 0:b.type)||"",h=Ne(i.role,a(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},u)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:o.map((i,u)=>{const m=Ne(i.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},u)})})]}),!d.length&&!o.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],d=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((o,i)=>{var h,p;const u=((h=n.find(b=>b.id===o.tenantUserId))==null?void 0:h.name)||"Unknown User",m=((p=n.find(b=>b.id===o.tenantUserId))==null?void 0:p.type)||"",x=Ne(o.role,a(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:x})]},i)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),d.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:d.map((o,i)=>{const u=Ne(o.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},i)})})]}),!c.length&&!d.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function Oa({isInitialLoading:t,searchQuery:n,availableUsers:a}){return t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):a.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:n?"No users found matching your search.":"No users available to share with."}):null}function Pa({user:t,userShare:n,isUserRemoving:a,hasAccess:r,hasAccessFromAPI:l,isSelected:c,selectedUser:d,roleOptions:o,currentUser:i,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:x,handleUpdateAccess:h,handleUserRoleChange:p}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!a?"border border-green-200 bg-green-50":a?"border border-red-200 bg-red-50":c?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:l?!a:c,onCheckedChange:()=>{l?a?m(t.id):x(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(Aa,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!a?e.jsx(Ae,{currentRole:n==null?void 0:n.role,onRoleChange:b=>h(t.id,n.role,b),roleOptions:o,disabled:!1,allowDropdown:!0}):e.jsx(Ma,{user:t,userShare:n,usersToUpdate:u,currentUser:i,getRoleOptions:()=>o,handleUpdateAccess:h}),c&&!l&&e.jsx("div",{onClick:b=>b.stopPropagation(),children:e.jsx(Ae,{currentRole:(d==null?void 0:d.role)||"VIEWER",onRoleChange:b=>p(t.id,b),roleOptions:o,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(Ra,{hasAccess:r,isUserRemoving:a,isSelected:c,hasAccessFromAPI:l}),e.jsx(La,{isUserRemoving:a,isSelected:c,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function Xs({existingShares:t,isInitialLoading:n,isSearching:a,getRoleOptions:r,allUsers:l=[],currentUser:c,handleUserToggle:d,handleUserRoleChange:o,handleRemoveAccess:i,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),x=s.useShareUsersToRemove(),h=s.useShareUsersToUpdate(),p=s.useShareSearchQuery(),b=s.useShareManagementActions(),f=d||(w=>{const D=m.some(y=>y.id===w),g=x.includes(w);D?b.removeSelectedUser(w):g?b.removeUserFromRemove(w):b.addSelectedUser({id:w,role:"VIEWER"})}),j=o||b.updateSelectedUserRole,N=i||b.addUserToRemove,C=u||((w,D,g)=>{b.addUserToUpdate({id:w,currentRole:D,newRole:g})}),L=l.filter(w=>w.id!==(c==null?void 0:c.id)),A=x;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 (",(L??[]).length,")"]}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:e.jsx(s.Info,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{className:"w-48 max-w-sm",children:e.jsx(Fa,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:c})})]})})]}),(L==null?void 0:L.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===L.length?b.setSelectedUsers([]):b.setSelectedUsers(L.map(w=>({id:w.id,role:"VIEWER"})))},className:"h-7 text-xs",children:m.length===L.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(Oa,{isInitialLoading:n,isSearching:a,searchQuery:p,availableUsers:L||[]}),!n&&!a&&(L==null?void 0:L.length)>0&&L.map(w=>{const D=t?Ia(w,t,c):void 0,g=A.includes(w.id),y=!!D,v=y&&!g,R=m.some(I=>I.id===w.id),S=m.find(I=>I.id===w.id),F=r(w.type);return e.jsx(Pa,{user:w,userShare:D,isUserRemoving:g,hasAccess:v,hasAccessFromAPI:y,isSelected:R,selectedUser:S,roleOptions:F,currentUser:c,usersToUpdate:h,handleUserToggle:f,handleRemoveAccess:N,handleUpdateAccess:C,handleUserRoleChange:j},w.id)})]})]})}function ls({shareType:t,onShareTypeChange:n,currentUser:a,options:r}){const l=(a==null?void 0:a.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:n,className:`grid grid-cols-${r.length} gap-4`,children:r.map(c=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:c.value,id:c.value,className:"peer sr-only",disabled:c.disabled}),e.jsxs(s.Label,{htmlFor:c.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 ${c.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[c.icon||e.jsx(s.User,{className:"mb-3 h-6 w-6"}),e.jsxs("div",{className:"space-y-1 text-center",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:c.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:c.description})]})]})]},c.value))}),!l&&r.some(c=>c.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 ye=()=>[{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 Ba({currentUser:t,currentShare:n,isSharing:a,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:c=!1,isUpdating:d=!1,isRemoving:o=!1}){const i=s.useShareCurrentMode(),u=ye().filter(C=>C.value==="VIEWER"||C.value==="EDITOR"||C.value==="CONTRIBUTOR"),m=n.role!=="NONE"?n.role:"NONE",x=l?l.newRole:m,h=n.role!=="NONE"&&!c&&(!l||l.newRole===m),p=l!==null&&l.newRole!==m,b=c,f=m==="NONE"||!m,j=C=>{switch(C){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(ha,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},N=C=>{r(m,C)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",p&&!b&&!f?"border-orange-300 bg-orange-50":h?"border-green-300 bg-green-50":b||f?"border-destructive bg-destructive/10":""),children:[e.jsxs(s.CardHeader,{children:[e.jsxs(s.CardTitle,{className:"flex items-center gap-2 text-base",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Share with All"," ",i==="allOrgUsers"?"Organization":i==="allTenantUsers"?"Tenant":i==="specificOrgUsers"?"Org":"Tenant"," ","Users",h&&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"}),(b||f)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:b||f?"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(C=>e.jsxs(s.Button,{variant:x===C.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>N(C.value),disabled:a||d||o,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[j(C.value),e.jsx("span",{className:"font-medium",children:C.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:C.description})]},C.value))})]})})]})})}function Zs({currentUser:t,currentShare:n,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:c,onRemoveAccess:d,allUsersToUpdate:o,allUsersToRemove:i}){const u=f=>f==="OWNER"?"CONTRIBUTOR":f,x=n?{role:u(n.role)}:{role:"NONE"},h=o?{currentRole:u(o.currentRole),newRole:u(o.newRole)}:null,p=(f,j)=>{c(f,j)},b=()=>{d()};return e.jsx(Ba,{currentUser:t,currentShare:x,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:p,onRemoveAccess:b,allUsersToUpdate:h,allUsersToRemove:i})}function Pe(t){const{debouncedSearchQuery:n,resourceId:a,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:c}=t,d=k.useMemo(()=>({search:n,active:!0,...l?{type:l}:{},...l==="tenant"&&c?{tenantId:c}:{}}),[n,l,c]),{users:o,isLoading:i,isError:u}=s.useUnifiedUsers(d),m=s.useResourceShares(r,a);return{allUsers:o,isLoadingUsers:i,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function Va({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:c=!1,isRemoving:d=!1}){var z,J;const o=s.useShareSelectedTab(),i=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:x}=s.useShareSearchWithDebounce(),h=s.useShareSelectedUsers(),p=s.useShareUsersToRemove(),b=s.useShareUsersToUpdate(),f=s.useShareCurrentMode(),j=s.useShareOrgWideRole(),N=s.useShareManagementActions(),[C,L]=k.useState("specific_users"),A=()=>{if(o==="org")return"organization";if(o==="tenant")return"tenant"},w=()=>{if(o==="tenant"&&i)return i},{allUsers:D,existingShares:g,isLoadingUsers:y}=Pe({debouncedSearchQuery:x,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:A(),tenantId:w()});k.useEffect(()=>{N.setCurrentContext("org-tab"),N.setCurrentMode(C==="all_users"?"allOrgUsers":"specificOrgUsers")},[N,C]);const v=W=>{var te,oe;const se=W;if(L(se),r==null||r(se),N.setCurrentContext("org-tab"),se==="specific_users")N.setCurrentMode("specificOrgUsers");else if(se==="all_users"){N.setCurrentMode("allOrgUsers");const Q=(oe=(te=g==null?void 0:g.shares)==null?void 0:te.orgUsersOnly)==null?void 0:oe[0];Q&&Q.role!==void 0&&N.setOrgWideRole(Q.role)}},R=D.filter(W=>W.name.toLowerCase().includes(u.toLowerCase())||W.email.toLowerCase().includes(u.toLowerCase())),S=D.filter(W=>h.some(se=>se.id===W.id)),F=W=>{var Q,_;const se=h.some(ae=>ae.id===W),te=p.includes(W),oe=(_=(Q=g==null?void 0:g.shares)==null?void 0:Q.specificOrgUsers)==null?void 0:_.some(ae=>ae.orgUserId===W);se?N.removeSelectedUser(W):te?N.removeUserFromRemove(W):oe||N.addSelectedUser({id:W,role:"VIEWER"})},I=(W,se)=>{N.updateSelectedUserRole(W,se)},T=W=>{N.addUserToRemove(W),N.removeSelectedUser(W)},M=W=>{N.removeUserFromRemove(W)},O=W=>{N.removeUserFromUpdate(W)},E=(W,se)=>{N.setOrgWideRole(se)},P=()=>{N.setOrgWideRole((B==null?void 0:B.role)||"NONE")},B=(J=(z=g==null?void 0:g.shares)==null?void 0:z.orgUsersOnly)==null?void 0:J[0];k.useEffect(()=>{C==="all_users"&&B&&B.role!==void 0&&N.setOrgWideRole(B.role)},[C,B,N]);const Y=y,q=!1;return a?e.jsxs(e.Fragment,{children:[e.jsx(ls,{shareType:C,onShareTypeChange:v,currentUser:a,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(a==null?void 0:a.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role??"")}]}),C==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(Qe,{value:u,onChange:m}),e.jsx(Ks,{selectedUsers:h,selectedUserObjects:S,onRemove:F,onRoleChange:I,getRoleOptions:ye}),e.jsx(Qs,{usersToRemove:p,allUsers:R,onRemove:M}),e.jsx(Hs,{usersToUpdate:b,allUsers:R,onRemove:O,getRoleOptions:ye}),e.jsx(Xs,{existingShares:g,isInitialLoading:Y,isSearching:q,resource:t,onShare:()=>{},getRoleOptions:ye,allUsers:R,currentUser:a,handleUserToggle:F,handleUserRoleChange:I,handleRemoveAccess:T,handleUpdateAccess:(W,se,te)=>{N.addUserToUpdate({id:W,currentRole:se,newRole:te})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(Zs,{currentUser:a,currentShare:B,isSharing:l,isUpdating:c,isRemoving:d,onUpdateAccess:E,onRemoveAccess:P,allUsersToUpdate:f==="allOrgUsers"&&j!==((B==null?void 0:B.role)||"NONE")?{currentRole:(B==null?void 0:B.role)||"NONE",newRole:j}:null,allUsersToRemove:f==="allOrgUsers"&&(B==null?void 0:B.role)===void 0})})]}):null}function za(t){switch(t){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function Ua(t){switch(t){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function et({groups:t,existingGroupShares:n,isLoading:a,resource:r,getRoleOptions:l,currentUser:c,handleGroupToggle:d,handleGroupRoleChange:o,handleRemoveAccess:i,handleUpdateAccess:u}){const m=s.useShareSelectedGroups(),x=s.useShareGroupsToRemove(),h=s.useShareGroupsToUpdate(),p=s.useShareManagementActions(),b=l(c==null?void 0:c.type);return a?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):t.length===0?e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No groups available to share with"}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Available Groups"}),e.jsx("div",{className:"max-h-[300px] space-y-2 overflow-y-auto rounded-md border p-3",children:t.map(f=>{const j=n==null?void 0:n.find(g=>g.groupId===f.id),N=m.some(g=>g.id===f.id),C=x.includes(f.id),L=h.find(g=>g.id===f.id),A=!!j&&!C;let D=(j==null?void 0:j.role)||"VIEWER";if(N){const g=m.find(y=>y.id===f.id);D=(g==null?void 0:g.role)||"VIEWER"}else L&&(D=L.newRole);return e.jsxs("div",{className:s.cn("flex items-center justify-between rounded-lg p-2 transition-colors",A&&!C?"border border-green-200 bg-green-50":C?"border border-red-200 bg-red-50":N?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(s.Checkbox,{id:`group-${f.id}`,checked:A?!C:N,disabled:!1,onCheckedChange:()=>{A?C?p.removeGroupFromRemove(f.id):i==null||i(f.id):d==null||d(f.id)}}),e.jsxs("label",{htmlFor:`group-${f.id}`,className:"flex cursor-pointer flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:f.name}),f.type==="ORG_GROUP"?e.jsx(s.Building2,{className:"h-3 w-3 text-blue-600"}):e.jsx(s.Users,{className:"h-3 w-3 text-green-600"}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[f.memberCount," members"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:s.cn("text-xs",Ua(f.type)),children:za(f.type)}),f.type==="TENANT_GROUP"&&f.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",f.tenantName]})]}),f.description&&e.jsx("span",{className:"text-xs text-muted-foreground",children:f.description})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[A&&!C?e.jsx(Ae,{currentRole:D,onRoleChange:g=>{j&&g!==j.role&&(u==null||u(f.id,j.role,g))},roleOptions:b,disabled:!1,allowDropdown:!0,className:L?"border-orange-300 bg-orange-100":""}):N&&!A&&e.jsx(Ae,{currentRole:D,onRoleChange:g=>o==null?void 0:o(f.id,g),roleOptions:b,disabled:!1}),A&&!C&&!L&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>i==null?void 0:i(f.id),children:e.jsx(s.X,{className:"h-4 w-4"})}),C&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p.removeGroupFromRemove(f.id),children:"Undo"}),L&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p.removeGroupFromUpdate(f.id),children:"Cancel"})]})]},f.id)})})]})}function st({selectedGroups:t,groupObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){if(t.length===0)return null;const c=l();return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:["Selected Groups (",t.length,")"]}),e.jsx("div",{className:"space-y-1",children:t.map(d=>{const o=n.find(i=>i.id===d.id);return o?e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted/50 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[o.type==="ORG_GROUP"?e.jsx(s.Building2,{className:"h-4 w-4 text-blue-600"}):e.jsx(s.Users,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{className:"text-sm font-medium",children:o.name}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[o.memberCount," members"]}),o.type==="TENANT_GROUP"&&o.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",o.tenantName]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ae,{currentRole:d.role,onRoleChange:i=>r(d.id,i),roleOptions:c}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>a(d.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})]},d.id):null})})]})}function ws({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:c=!1,isRemoving:d=!1}){var G;const{searchQuery:o,debouncedSearchQuery:i,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),x=s.useShareUsersToRemove(),h=s.useShareUsersToUpdate(),p=s.useShareSelectedGroups(),b=s.useShareGroupsToRemove(),f=s.useShareGroupsToUpdate(),j=s.useShareCurrentMode(),N=s.useShareTenantWideRole(),C=s.useShareAllTenantsRole(),L=s.useShareSelectedTenant(),A=s.useShareManagementActions(),{data:w,isLoading:D}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"}),{groups:g,isLoading:y}=s.useShareableGroups("tenant",(a==null?void 0:a.tenantId)||L),[v,R]=k.useState((a==null?void 0:a.type)==="organization"?"all_tenants":"specific_tenant_users");k.useEffect(()=>{(a==null?void 0:a.type)==="tenant"?(A.setCurrentContext("tenant-dialog"),A.setCurrentMode("specificTenantUsers")):(A.setCurrentContext("tenant-tab"),A.setCurrentMode("allTenants"))},[A,a==null?void 0:a.type]);const S=V=>{var le,de,ne,me;R(V);let Z;if(V==="specific_tenant_users"?Z="specific_users":V==="all_tenant_users"||V==="all_tenants"?Z="all_users":V==="groups"?Z="groups":Z="specific_users",r==null||r(Z),V==="groups"?(A.setCurrentContext("group-share"),A.setCurrentMode("specificGroups")):(a==null?void 0:a.type)==="tenant"?(A.setCurrentContext("tenant-dialog"),V==="specific_tenant_users"?A.setCurrentMode("specificTenantUsers"):V==="all_tenant_users"&&(A.setCurrentMode("allTenantUsers"),a!=null&&a.tenantId&&A.setSelectedTenant(a.tenantId))):(A.setCurrentContext("tenant-tab"),V==="specific_tenant_users"?A.setCurrentMode("specificTenantUsers"):V==="all_tenant_users"?A.setCurrentMode("allTenantUsers"):V==="all_tenants"&&A.setCurrentMode("allTenants")),V==="all_tenant_users"){const je=(de=(le=T==null?void 0:T.shares)==null?void 0:le.tenantWide)==null?void 0:de[0];je&&je.role!==void 0&&A.setTenantWideRole(je.role)}else if(V==="all_tenants"){const je=(me=(ne=T==null?void 0:T.shares)==null?void 0:ne.allTenantsOnly)==null?void 0:me[0];je&&je.role!==void 0&&A.setAllTenantsRole(je.role)}},F=V=>{A.setSelectedTenant(V)},{allUsers:I,existingShares:T,isLoadingUsers:M,isErrorLoadingUsers:O,isLoadingShares:E,isErrorLoadingShares:P}=Pe({debouncedSearchQuery:i,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant",tenantId:(a==null?void 0:a.type)==="tenant"?a.tenantId:L}),B=V=>{var ne,me;const Z=m.some(je=>je.id===V),le=x.includes(V),de=(me=(ne=T==null?void 0:T.shares)==null?void 0:ne.specificTenantUsers)==null?void 0:me.some(je=>je.tenantUserId===V);Z?A.removeSelectedUser(V):le?A.removeUserFromRemove(V):de||A.addSelectedUser({id:V,role:"VIEWER"})},Y=(V,Z)=>{A.updateSelectedUserRole(V,Z)},q=V=>{A.addUserToRemove(V),A.removeSelectedUser(V)},z=V=>{A.removeUserFromRemove(V)},J=V=>{A.removeUserFromUpdate(V)},W=(V,Z,le)=>{A.addUserToUpdate({id:V,currentRole:Z,newRole:le})},se=(V,Z)=>{v==="all_tenant_users"?A.setTenantWideRole(Z):v==="all_tenants"&&A.setAllTenantsRole(Z)},te=()=>{v==="all_tenant_users"?A.setTenantWideRole("VIEWER"):v==="all_tenants"&&A.setAllTenantsRole("VIEWER")},Q=(()=>{var V,Z,le,de;return j==="allTenants"?(Z=(V=T==null?void 0:T.shares)==null?void 0:V.allTenantsOnly)==null?void 0:Z[0]:j==="allTenantUsers"?(de=(le=T==null?void 0:T.shares)==null?void 0:le.tenantWide)==null?void 0:de[0]:null})();k.useEffect(()=>{var V,Z,le,de;if(v==="all_tenant_users"){const ne=(Z=(V=T==null?void 0:T.shares)==null?void 0:V.tenantWide)==null?void 0:Z[0];ne&&ne.role!==void 0&&A.setTenantWideRole(ne.role)}else if(v==="all_tenants"){const ne=(de=(le=T==null?void 0:T.shares)==null?void 0:le.allTenantsOnly)==null?void 0:de[0];ne&&ne.role!==void 0&&A.setAllTenantsRole(ne.role)}},[v,T,A]);const _=I.filter(V=>m.some(Z=>Z.id===V.id)),ae=V=>{const Z=p.some(ne=>ne.id===V),le=b.includes(V),de=X==null?void 0:X.some(ne=>ne.groupId===V);Z?A.removeSelectedGroup(V):le?A.removeGroupFromRemove(V):de||A.addSelectedGroup({id:V,role:"VIEWER"})},H=(V,Z)=>{A.updateSelectedGroupRole(V,Z)},re=V=>{A.addGroupToRemove(V),A.removeSelectedGroup(V)},ie=(V,Z,le)=>{A.addGroupToUpdate({id:V,currentRole:Z,newRole:le})},ue=g.filter(V=>p.some(Z=>Z.id===V.id)),U=k.useMemo(()=>v!=="groups"?[]:g.filter(V=>V.type!=="TENANT_GROUP"?!1:V.name.toLowerCase().includes(o.toLowerCase())||V.description&&V.description.toLowerCase().includes(o.toLowerCase())),[g,v,o]),X=k.useMemo(()=>{var Z,le;const V=((Z=T==null?void 0:T.shares)==null?void 0:Z.specificGroups)||((le=T==null?void 0:T.shares)==null?void 0:le.groups)||[];return!V||V.length===0?[]:V.filter(de=>{const ne=g.find(me=>me.id===de.groupId);return(ne==null?void 0:ne.type)==="TENANT_GROUP"})},[T,g]),xe=M||E||v==="groups"&&y,ce=O||P,K=()=>(a==null?void 0:a.type)==="tenant"||v==="all_tenants"||v==="groups"?!0:L&&(v==="specific_tenant_users"||v==="all_tenant_users");return e.jsxs(e.Fragment,{children:[ce&&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"})]})}),!ce&&a&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(ls,{shareType:v,onShareTypeChange:S,currentUser:a,options:(a==null?void 0:a.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"specific_tenant_users",label:"Specific Users",description:"Share with specific tenant users",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"groups",label:"Groups",description:"Share with tenant groups",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-green-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:e.jsx(ys,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"all_tenant_users",label:"Specific Tenant",description:"Share with all users of a specific tenant",icon:e.jsx(s.House,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"specific_tenant_users",label:"Specific Tenant User",description:"Share with users of a specific tenant",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(a==null?void 0:a.type)==="organization"&&(v==="specific_tenant_users"||v==="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:L||"",onValueChange:F,disabled:D,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:D?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(G=w==null?void 0:w.tenants)==null?void 0:G.map(V=>e.jsx(s.SelectItem,{value:V.id,children:V.name},V.id))})]})]}),K()?e.jsx(e.Fragment,{children:v==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Qe,{value:o,onChange:u}),e.jsx(Ks,{selectedUsers:m,selectedUserObjects:_,onRemove:V=>B(V),onRoleChange:Y,getRoleOptions:ye}),e.jsx(Qs,{usersToRemove:x,allUsers:I,onRemove:z}),e.jsx(Hs,{usersToUpdate:h,allUsers:I,onRemove:J,getRoleOptions:ye}),e.jsx(Xs,{existingShares:T,isInitialLoading:!!xe,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:ye,allUsers:I,currentUser:a,handleUserToggle:B,handleUserRoleChange:Y,handleRemoveAccess:q,handleUpdateAccess:W})]}):v==="groups"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Qe,{value:o,onChange:u,placeholder:"Search groups..."}),e.jsx(st,{selectedGroups:p,groupObjects:ue,onRemove:ae,onRoleChange:H,getRoleOptions:ye}),b.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",b.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),f.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",f.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(et,{groups:U,existingGroupShares:X,isLoading:y,resource:t,getRoleOptions:ye,currentUser:a,handleGroupToggle:ae,handleGroupRoleChange:H,handleRemoveAccess:re,handleUpdateAccess:ie})]}):v==="all_tenant_users"||v==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(Zs,{currentUser:a,currentShare:Q,isSharing:l,isUpdating:c,isRemoving:d,onUpdateAccess:se,onRemoveAccess:te,allUsersToUpdate:j==="allTenantUsers"&&((Q==null?void 0:Q.role)===void 0||N!==Q.role)||j==="allTenants"&&((Q==null?void 0:Q.role)===void 0||C!==Q.role)?{currentRole:(Q==null?void 0:Q.role)||"VIEWER",newRole:j==="allTenantUsers"?N:C}:null,allUsersToRemove:j==="allTenantUsers"&&(Q==null?void 0:Q.role)===void 0||j==="allTenants"&&(Q==null?void 0:Q.role)===void 0})}):null}):(a==null?void 0:a.type)==="organization"&&(v==="specific_tenant_users"||v==="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(ys,{className:"mx-auto mb-2 h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant to continue"})]})})]})]})}function _a({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:c=!1,isRemoving:d=!1}){var O,E;const{searchQuery:o,setSearchQuery:i}=s.useShareSearchWithDebounce(),u=s.useShareSelectedGroups(),m=s.useShareGroupsToRemove(),x=s.useShareGroupsToUpdate(),h=s.useShareManagementActions(),[p,b]=k.useState("org_groups"),[f,j]=k.useState(""),{data:N,isLoading:C}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"&&p==="tenant_groups"}),L=Array.isArray(N)?N:(N==null?void 0:N.tenants)||[],A=()=>{if((a==null?void 0:a.type)==="organization")return"organization";if((a==null?void 0:a.type)==="tenant")return"tenant"},{groups:w,isLoading:D}=s.useShareableGroups(A(),p==="tenant_groups"&&(a==null?void 0:a.type)==="organization"?f:a==null?void 0:a.tenantId),{existingShares:g}=Pe({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n}),y=w.filter(P=>p==="org_groups"&&P.type!=="ORG_GROUP"||p==="tenant_groups"&&P.type!=="TENANT_GROUP"||p==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&(!f||P.tenantId&&P.tenantId!==f)?!1:P.name.toLowerCase().includes(o.toLowerCase())||P.description&&P.description.toLowerCase().includes(o.toLowerCase())),v=((O=g==null?void 0:g.shares)==null?void 0:O.specificGroups)||((E=g==null?void 0:g.shares)==null?void 0:E.groups)||[];k.useEffect(()=>{h.setCurrentContext("group-share"),h.setCurrentMode("specificGroups")},[h]);const R=P=>{const B=P;b(B),B==="org_groups"&&j(""),r==null||r(B==="org_groups"?"specific_groups":"all_groups"),h.setCurrentContext("group-share"),h.setCurrentMode("specificGroups")},S=w.filter(P=>u.some(B=>B.id===P.id)),F=P=>{const B=u.some(z=>z.id===P),Y=m.includes(P),q=v==null?void 0:v.some(z=>z.groupId===P);B?h.removeSelectedGroup(P):Y?h.removeGroupFromRemove(P):q||h.addSelectedGroup({id:P,role:"VIEWER"})},I=(P,B)=>{h.updateSelectedGroupRole(P,B)},T=P=>{h.addGroupToRemove(P),h.removeSelectedGroup(P)},M=(P,B,Y)=>{h.addGroupToUpdate({id:P,currentRole:B,newRole:Y})};return a?e.jsxs(e.Fragment,{children:[e.jsx(ls,{shareType:p,onShareTypeChange:R,currentUser:a,options:[{value:"org_groups",label:"Organization Groups",description:"Share with organization-level groups",icon:e.jsx(s.Building2,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"tenant_groups",label:"Tenant Groups",description:"Share with tenant-level groups",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-green-500"})}]}),p==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(s.Label,{children:"Select Tenant"}),e.jsxs(s.Select,{value:f,onValueChange:j,disabled:C,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:C?"Loading tenants...":"Select a tenant to view its groups"})}),e.jsx(s.SelectContent,{className:"z-[51]",children:L.map(P=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:P.id,children:P.name},P.id))})]})]}),e.jsx("div",{className:"mt-3 space-y-2",children:p==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&!f?e.jsx("div",{className:"rounded-md border border-dashed p-6 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant above to view and share with its groups"})}):e.jsxs(e.Fragment,{children:[e.jsx(Qe,{value:o,onChange:i,placeholder:"Search groups..."}),e.jsx(st,{selectedGroups:u,groupObjects:S,onRemove:F,onRoleChange:I,getRoleOptions:ye}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",m.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),x.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",x.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(et,{groups:y,existingGroupShares:v,isLoading:D,resource:t,getRoleOptions:ye,currentUser:a,handleGroupToggle:F,handleGroupRoleChange:I,handleRemoveAccess:T,handleUpdateAccess:M})]})})]}):null}const tt=()=>{const t=s.useShareCurrentContext(),n=s.useShareCurrentMode(),a=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),c=s.useShareSelectedGroups(),d=s.useShareGroupsToRemove(),o=s.useShareGroupsToUpdate(),i=s.useShareSelectedTenant(),u=s.useShareOrgWideRole(),m=s.useShareAllTenantsRole(),x=s.useShareTenantWideRole(),h=s.useShareGroupWideRole(),p=k.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedGroups:c,groupsToRemove:d,groupsToUpdate:o,selectedTenant:i,orgWideRole:u,allTenantsRole:m,tenantWideRole:x}),[t,n,a,r,l,c,d,o,i,u,m,x,h]),b=k.useMemo(()=>j=>s.validateShareData(j),[]),f=k.useMemo(()=>{if(!t||!n)return!1;switch(t){case"org-tab":return n==="specificOrgUsers"?a.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(n==="allTenantUsers"){if(!i)return!1}else if(n==="specificTenantUsers")return i?a.length>0||r.length>0||l.length>0:!1;return!0;case"tenant-dialog":return n==="specificTenantUsers"?a.length>0||r.length>0||l.length>0:!0;case"group-share":return n==="specificGroups"?c.length>0||d.length>0||o.length>0:!0}return!1},[t,n,a,r,l,c,d,o,i]);return{buildShareData:p,validateShareData:b,isCurrentStateValid:f,currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedTenant:i,orgWideRole:u,allTenantsRole:m,tenantWideRole:x}};function Ds({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:c,onClose:d,shareTabType:o,currentAllUsersShare:i,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),x=s.useShareUsersToRemove(),h=s.useShareUsersToUpdate(),p=s.useShareSelectedTenant(),b=s.useShareOrgWideRole(),f=s.useShareAllTenantsRole(),j=s.useShareTenantWideRole(),{buildShareData:N,validateShareData:C,isCurrentStateValid:L}=tt(),A=a||r||l,w=()=>{var R,S,F,I;if(A)return"Updating...";if(o==="specific_users"){if(m.length===0&&x.length===0&&h.length===0)return"Select users to share with";const T=m.length+x.length+h.length;return T===0?"Select users to share with":m.length>0&&x.length>0?`Update access for ${T} user${T!==1?"s":""}`:x.length>0&&m.length===0&&h.length===0?`Remove access for ${x.length} user${x.length!==1?"s":""}`:m.length>0&&x.length===0&&h.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:h.length>0&&m.length===0&&x.length===0?`Update access for ${h.length} user${h.length!==1?"s":""}`:`Update access for ${T} user${T!==1?"s":""}`}else if(o==="all_users"){if(!i||i.role===void 0)return"Share with All Users";const T=i.role;return b===T?"Remove Access":"Update Access"}else if(o==="all_tenants"){const T=(S=(R=n==null?void 0:n.shares)==null?void 0:R.allTenantsOnly)==null?void 0:S[0];if(!T||T.role===void 0)return"Share with All Tenants";const M=T.role;return f===M?"Remove Access":"Update Access"}else if(o==="all_tenant_users"){const T=(I=(F=n==null?void 0:n.shares)==null?void 0:F.tenantWide)==null?void 0:I[0];if(!T||T.role===void 0)return"Share with All Tenant Users";const M=T.role;return j===M?"Remove Access":"Update Access"}else if(o==="specific_tenant_users"){if(m.length===0&&x.length===0&&h.length===0)return"Select users to share with";const T=m.length+x.length+h.length;return T===0?"Select users to share with":m.length>0&&x.length>0?`Update access for ${T} user${T!==1?"s":""}`:x.length>0&&m.length===0&&h.length===0?`Remove access for ${x.length} user${x.length!==1?"s":""}`:m.length>0&&x.length===0&&h.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:h.length>0&&m.length===0&&x.length===0?`Update access for ${h.length} user${h.length!==1?"s":""}`:`Update access for ${T} user${T!==1?"s":""}`}return"Share"},D=()=>A||!t||o==="all_tenant_users"&&!p||o==="specific_tenant_users"&&!p?!0:!L,g=()=>{const R=N();R&&C(R)&&c(R)},y=()=>{var R,S,F,I;if(o==="all_users")if(!i||i.role===void 0){const T=N();T&&C(T)&&c(T)}else{const T=i.role;if(b===T)u==null||u();else{const O=N();if(O&&C(O)){const E={...O,updateAccess:!0};c(E)}}}else if(o==="all_tenants"){const T=(S=(R=n==null?void 0:n.shares)==null?void 0:R.allTenantsOnly)==null?void 0:S[0];if(!T||T.role===void 0){const M=N();M&&C(M)&&c(M)}else{const M=T.role;if(f===M)u==null||u();else{const E=N();if(E&&C(E)){const P={...E,updateAccess:!0};c(P)}}}}else if(o==="all_tenant_users"){const T=(I=(F=n==null?void 0:n.shares)==null?void 0:F.tenantWide)==null?void 0:I[0];if(!T||T.role===void 0){const M=N();M&&C(M)&&c(M)}else{const M=T.role;if(j===M)u==null||u();else{const E=N();if(E&&C(E)){const P={...E,updateAccess:!0};c(P)}}}}},v=()=>{var R,S,F,I;if(o==="all_users"){if(!i||i.role===void 0)return"default";const T=i.role;return b===T?"destructive":"default"}else if(o==="all_tenants"){const T=(S=(R=n==null?void 0:n.shares)==null?void 0:R.allTenantsOnly)==null?void 0:S[0];if(!T||T.role===void 0)return"default";const M=T.role;return f===M?"destructive":"default"}else if(o==="all_tenant_users"){const T=(I=(F=n==null?void 0:n.shares)==null?void 0:F.tenantWide)==null?void 0:I[0];if(!T||T.role===void 0)return"default";const M=T.role;return j===M?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsxs(s.Button,{variant:"outline",onClick:d,disabled:A,children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),(o==="specific_users"||o==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||x.length>0||h.length>0)&&e.jsxs(s.Button,{onClick:g,disabled:!t||A,variant:"default",children:[A?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ie,{className:"mr-2 h-4 w-4"}),!A&&w()]})}),(o==="all_users"||o==="all_tenants"||o==="all_tenant_users")&&e.jsxs(s.Button,{onClick:y,disabled:D(),variant:v(),children:[A?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(s.Users,{className:"mr-2 h-4 w-4"}),!A&&w()]})]})}function Ga({resource:t,isSharing:n,isRemoving:a,isUpdating:r,onShare:l,onClose:c,shareTabType:d,currentAllUsersShare:o}){const i=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate(),x=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),p=s.useShareGroupsToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const b=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:f,validateShareData:j,isCurrentStateValid:N}=tt(),C=n||a||r,L=()=>{if(C)return"Updating...";if(d==="specific_users"){if(i.length===0&&u.length===0&&m.length===0)return"Select users to share with";const v=i.length+u.length+m.length;return v===0?"Select users to share with":i.length>0&&u.length>0?`Update access for ${v} user${v!==1?"s":""}`:u.length>0&&i.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:i.length>0&&u.length===0&&m.length===0?`Share with ${i.length} user${i.length!==1?"s":""}`:m.length>0&&i.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${v} user${v!==1?"s":""}`}else if(d==="groups"){if(x.length===0&&h.length===0&&p.length===0)return"Select groups to share with";const v=x.length+h.length+p.length;return v===0?"Select groups to share with":x.length>0&&h.length>0?`Update access for ${v} group${v!==1?"s":""}`:h.length>0&&x.length===0&&p.length===0?`Remove access for ${h.length} group${h.length!==1?"s":""}`:x.length>0&&h.length===0&&p.length===0?`Share with ${x.length} group${x.length!==1?"s":""}`:p.length>0&&x.length===0&&h.length===0?`Update access for ${p.length} group${p.length!==1?"s":""}`:`Update access for ${v} group${v!==1?"s":""}`}else if(d==="all_users"){if(!o||o.role==="NONE")return"Share with All Users";const v=o.role;return b===v?"Remove Access":"Update Access"}return"Share"},A=()=>C||!t?!0:!N,w=()=>{const v=f();v&&j(v)&&l(v)},D=()=>{const v=f();v&&j(v)&&l(v)},g=()=>{if(!o||o.role==="NONE"){const v=f();v&&j(v)&&l(v)}else{const v=o.role;if(b===v){const S=f();if(S&&j(S)){const F={...S,removeAccess:!0};l(F)}}else{const S=f();if(S&&j(S)){const F={...S,updateAccess:!0};l(F)}}}},y=()=>!o||o.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsxs(s.Button,{variant:"outline",onClick:c,disabled:C,children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),d==="specific_users"&&e.jsx(e.Fragment,{children:(i.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:w,disabled:!t||C,variant:"default",children:[C?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ie,{className:"mr-2 h-4 w-4"}),!C&&L()]})}),d==="groups"&&e.jsx(e.Fragment,{children:(x.length>0||h.length>0||p.length>0)&&e.jsxs(s.Button,{onClick:D,disabled:!t||C,variant:"default",children:[C?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ie,{className:"mr-2 h-4 w-4"}),!C&&L()]})}),d==="all_users"&&e.jsxs(s.Button,{onClick:g,disabled:A(),variant:y(),children:[C?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ie,{className:"mr-2 h-4 w-4"}),!C&&L()]})]})}function $a({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:c,onClose:d,shareTabType:o,currentAllGroupsShare:i,onRemoveAccess:u}){const m=s.useShareSelectedGroups(),x=s.useShareGroupsToRemove(),h=s.useShareGroupsToUpdate();s.useShareGroupWideRole(),s.useShareCurrentMode();const p=()=>{c({context:"group-share",mode:"specificGroups",selectedGroups:m,groupsToRemove:x,groupsToUpdate:h})},b=()=>m.length>0||x.length>0||h.length>0,f=()=>x.length>0&&m.length===0&&h.length===0?"Remove Access":h.length>0&&m.length===0&&x.length===0?"Update Access":"Share with Groups",j=a||r||l;return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[m.length>0&&e.jsxs("span",{children:[m.length," groups selected"]}),x.length>0&&e.jsxs("span",{className:"ml-2 text-destructive",children:["• ",x.length," to remove"]}),h.length>0&&e.jsxs("span",{className:"ml-2 text-orange-600",children:["• ",h.length," to update"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:d,disabled:j,children:"Cancel"}),e.jsxs(s.Button,{onClick:p,disabled:!b()||j,children:[j&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),f()]})]})]})}function ve(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Ce(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Ya(t,n,a){const{resourceType:r,resourceId:l,shareMutation:c,removeMutation:d,existingShares:o,resetUserSelections:i}=n;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const u=ve(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);c(u,{onSuccess:()=>{i()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:x}=t;if(u&&u.length>0){const h=ve(r,l,u.map(p=>({scope:"specific_org_user",orgUserId:p.id,role:p.role})));c(h,{onSuccess:()=>{i()}})}if(m&&m.length>0){const h=Ce(r,l,m.map(p=>{var f,j;const b=(j=(f=o==null?void 0:o.shares)==null?void 0:f.specificOrgUsers)==null?void 0:j.find(N=>N.orgUserId===p);return{scope:"specific_org_user",orgUserId:p,role:(b==null?void 0:b.role)||"VIEWER"}}));d(h,{onSuccess:()=>{i()}})}x&&x.length>0&&x.forEach(h=>{const p=ve(r,l,[{scope:"specific_org_user",orgUserId:h.id,role:h.newRole}]);c(p,{onSuccess:()=>{i()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const u=ve(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);c(u,{onSuccess:()=>{i()}})}else if(t.mode==="allTenantUsers"){const u=ve(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);c(u,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:x,tenantId:h}=t;if(m&&m.length>0){const p=Ce(r,l,m.map(b=>{var j,N;const f=(N=(j=o==null?void 0:o.shares)==null?void 0:j.specificTenantUsers)==null?void 0:N.find(C=>C.tenantUserId===b);return{scope:"specific_tenant_user",tenantUserId:b,tenantId:h,role:(f==null?void 0:f.role)||"VIEWER"}}));d(p,{onSuccess:()=>{i()}})}if(x&&x.length>0&&x.forEach(p=>{const b=ve(r,l,[{scope:"specific_tenant_user",tenantUserId:p.id,tenantId:h,role:p.newRole}]);c(b,{onSuccess:()=>{i()}})}),u&&u.length>0){const p=ve(r,l,u.map(b=>({scope:"specific_tenant_user",tenantUserId:b.id,tenantId:h,role:b.role})));c(p,{onSuccess:()=>{i()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const u=Ce(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);d(u,{onSuccess:()=>{i()}})}else if(t.updateAccess){const u=ve(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);c(u,{onSuccess:()=>{i()}})}else{const u=ve(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);c(u,{onSuccess:()=>{i()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:x}=t;if(u&&u.length>0){const h=ve(r,l,u.map(p=>({scope:"specific_tenant_user",tenantUserId:p.id,role:p.role})));c(h,{onSuccess:()=>{i()}})}if(m&&m.length>0){const h=Ce(r,l,m.map(p=>{var f,j;const b=(j=(f=o==null?void 0:o.shares)==null?void 0:f.specificTenantUsers)==null?void 0:j.find(N=>N.tenantUserId===p);return{scope:"specific_tenant_user",tenantUserId:p,role:(b==null?void 0:b.role)||"VIEWER"}}));d(h,{onSuccess:()=>{i()}})}x&&x.length>0&&x.forEach(h=>{const p=ve(r,l,[{scope:"specific_tenant_user",tenantUserId:h.id,role:h.newRole}]);c(p,{onSuccess:()=>{i()}})})}break;case"group-share":if(t.mode==="specificGroups"){const{selectedGroups:u,groupsToRemove:m,groupsToUpdate:x}=t;if(u&&u.length>0){const h=ve(r,l,u.map(p=>({scope:"group",groupId:p.id,role:p.role})));c(h,{onSuccess:()=>{var p;i(),(p=n.resetGroupSelections)==null||p.call(n),s.ue.success(`Shared with ${u.length} group${u.length!==1?"s":""}`)}})}if(m&&m.length>0){const h=Ce(r,l,m.map(p=>({scope:"group",groupId:p,role:"VIEWER"})));d(h,{onSuccess:()=>{var p;i(),(p=n.resetGroupSelections)==null||p.call(n),s.ue.success(`Removed access from ${m.length} group${m.length!==1?"s":""}`)}})}x&&x.length>0&&x.forEach(h=>{const p=ve(r,l,[{scope:"group",groupId:h.id,role:h.newRole}]);c(p,{onSuccess:()=>{var b;i(),(b=n.resetGroupSelections)==null||b.call(n),s.ue.success("Updated access for group")}})})}break}}function qa(t,n,a,r){var u,m,x,h,p,b;const{resourceType:l,resourceId:c,removeMutation:d,existingShares:o,resetUserSelections:i}=r;if(c)if(t.length>0){const f=Ce(l,c,t.map(j=>{var C,L;const N=(L=(C=o==null?void 0:o.shares)==null?void 0:C.specificTenantUsers)==null?void 0:L.find(A=>A.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,role:(N==null?void 0:N.role)||"VIEWER"}}));d(f,{onSuccess:()=>{i()},onError:j=>{console.error("Remove access failed:",j)}})}else{const f=n==="tenant"&&a==="allTenants",j=n==="tenant"&&a==="allTenantUsers";if(f){const N=(m=(u=o==null?void 0:o.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(N){const C=Ce(l,c,[{scope:"all_tenants_only",role:N.role}]);d(C,{onSuccess:()=>{i()},onError:L=>{console.error("Remove all-tenants access failed:",L)}})}}else if(j){const N=(h=(x=o==null?void 0:o.shares)==null?void 0:x.tenantWide)==null?void 0:h[0];if(N){const C=Ce(l,c,[{scope:"all_tenant_users",role:N.role}]);d(C,{onSuccess:()=>{i()},onError:L=>{console.error("Remove all-tenant-users access failed:",L)}})}}else{const N=(b=(p=o==null?void 0:o.shares)==null?void 0:p.orgUsersOnly)==null?void 0:b[0];if(N){const C=Ce(l,c,[{scope:"org_users_only",role:N.role}]);d(C,{onSuccess:()=>{i()},onError:L=>{console.error("Remove org-wide access failed:",L)}})}}}}function Ka(t,n,a){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),c=s.useShareSelectedTab(),d=s.useShareCurrentMode(),{currentUser:o}=s.useCurrentUserInfo(),{existingShares:i}=Pe({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),u=k.useCallback(()=>{r.resetUserSelections()},[r]),m=k.useCallback(()=>{r.resetGroupSelections()},[r]),x=k.useCallback(p=>{if(!t)return;const b={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:n,removeMutation:a,existingShares:i,resetUserSelections:u,resetGroupSelections:m};Ya(p,b,o)},[t,n,a,i,u,m,o]),h=k.useCallback(()=>{if(!t)return;const p={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:a,existingShares:i,resetUserSelections:u};qa(l,c||"",d||"",p)},[t,n,a,i,u,m,l,c,d]);return{handleShareSubmit:x,handleRemoveAccess:h}}function We({resource:t,resourceType:n,onClose:a,onShareSuccess:r,onRemoveSuccess:l}){var I,T,M,O,E,P,B,Y;const{currentUser:c}=s.useCurrentUserInfo(),[d,o]=k.useState("specific_users"),[i,u]=k.useState("specific_users"),[m,x]=k.useState("specific_groups"),h=s.useShareManagementActions(),p=s.useShareSelectedTab(),b=s.useShareCurrentMode(),f=s.useShareResource(),j=s.useRemoveResourceShares(),{handleShareSubmit:N,handleRemoveAccess:C}=Ka(t.id,(q,z)=>{f.mutate(q,{...z,onSuccess:()=>{var J;(J=z==null?void 0:z.onSuccess)==null||J.call(z),r==null||r()}})},(q,z)=>{j.mutate(q,{...z,onSuccess:()=>{var J;(J=z==null?void 0:z.onSuccess)==null||J.call(z),l==null||l()}})}),L=f.isPending,A=j.isPending,w=f.isPending,{existingShares:D}=Pe({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant"}),{existingShares:g}=Pe({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"organization"}),y=(T=(I=D==null?void 0:D.shares)==null?void 0:I.tenantWide)==null?void 0:T[0],v=(O=(M=g==null?void 0:g.shares)==null?void 0:M.orgUsersOnly)==null?void 0:O[0],R=()=>{if(p==="org")return i;switch(b){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},S=k.useCallback(()=>{h.resetShareState(),a()},[h,a]),F=(c==null?void 0:c.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:S,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(Ie,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:F?"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."})]}),F?e.jsxs(s.Tabs,{value:p,onValueChange:q=>{const z=q;h.setSelectedTab(z),h.resetUserSelections(),h.resetGroupSelections()},className:"mb-4 min-h-0 flex-1",children:[e.jsxs(s.TabsList,{className:"mb-2 grid w-full grid-cols-3",children:[e.jsx(s.TabsTrigger,{value:"org",children:"Org Users"}),e.jsx(s.TabsTrigger,{value:"tenant",children:"Tenant Users"}),e.jsx(s.TabsTrigger,{value:"groups",children:"Groups"})]}),e.jsx(s.TabsContent,{value:"org",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(Va,{resource:t,resourceType:n,currentUser:c,onShareTabTypeChange:u,isSharing:L,isUpdating:w,isRemoving:A})})}),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(ws,{resource:t,resourceType:n,currentUser:c,onShareTabTypeChange:q=>o(q),isSharing:L,isUpdating:w,isRemoving:A})})}),e.jsx(s.TabsContent,{value:"groups",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(_a,{resource:t,resourceType:n,currentUser:c,onShareTabTypeChange:x,isSharing:L,isUpdating:w,isRemoving:A})})})]}):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(ws,{resource:t,resourceType:n,currentUser:c,onShareTabTypeChange:q=>o(q),isSharing:L,isUpdating:w,isRemoving:A})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:F?p==="org"?e.jsx(Ds,{resource:t,existingShares:g,isSharing:L,isRemoving:A,isUpdating:w,onShare:N,onClose:a,shareTabType:i,currentAllUsersShare:v,onRemoveAccess:C}):p==="tenant"?e.jsx(Ds,{resource:t,existingShares:D,isSharing:L,isRemoving:A,isUpdating:w,onShare:N,onClose:a,shareTabType:R(),currentAllUsersShare:y,onRemoveAccess:C}):e.jsx($a,{resource:t,existingShares:g,isSharing:L,isRemoving:A,isUpdating:w,onShare:N,onClose:a,shareTabType:m,currentAllGroupsShare:(c==null?void 0:c.type)==="organization"?(P=(E=g==null?void 0:g.shares)==null?void 0:E.allOrgGroups)==null?void 0:P[0]:(Y=(B=D==null?void 0:D.shares)==null?void 0:B.allTenantGroups)==null?void 0:Y[0],onRemoveAccess:C}):e.jsx(Ga,{resource:t,isSharing:L,isRemoving:A,isUpdating:w,onShare:N,onClose:a,shareTabType:d,currentAllUsersShare:y,onRemoveAccess:C})})]})})}function at({type:t,isLinked:n,className:a}){const r=s.useDashboardStore(u=>u.selectedFrameId),l=s.useManagementStore(u=>u.selectedVisual),c=s.useEditorStore(u=>u.frame);let d;if(t)d=t;else if(n!==void 0)d=n?"linked":"library";else if(!!!(c!=null&&c.visualId||l!=null&&l.id)&&r)d="local";else if(l&&!r)d="library";else if(c!=null&&c.visualId&&r)d="linked";else if(l!=null&&l.id&&r)d="library";else return null;const o={local:"bg-gray-100 text-gray-700",linked:"bg-purple-100 text-purple-700",library:"bg-blue-100 text-blue-700"},i={local:"Local Visual",linked:"Linked Visual",library:"Library Visual"};return e.jsx("span",{className:s.cn("rounded-full px-2.5 py-0.5 text-xs font-medium",o[d],a),children:i[d]})}const Qa=async(t,n,a)=>{const r=`${t}/management/v1/groups`;return await s.postRequestRegular(r,n,a)},Ha=async(t,n,a)=>{const r=`${t}/management/v1/groups/${a}`,l=await fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!l.ok){const c=await l.text();throw new Error(c||"Failed to delete group")}},Wa=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`;return await s.postRequestRegular(l,n,r)},Ja=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`,c=await fetch(l,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)});if(!c.ok){const d=await c.text();throw new Error(d||"Failed to remove group members")}};function Xa(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>Qa(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:()=>{a.invalidateQueries({queryKey:["groups"]}),s.ue.success("Group created successfully")},onError:r=>{console.error("Failed to create group:",r),s.ue.error("Failed to create group",{description:r.message})}})}function Za(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>Ha(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["groups"]}),a.removeQueries({queryKey:["group",l]}),s.ue.success("Group deleted successfully")},onError:r=>{console.error("Failed to delete group:",r),s.ue.error("Failed to delete group",{description:r.message})}})}function en(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>Wa(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["group",l.groupId]}),a.invalidateQueries({queryKey:["group-members",l.groupId]}),a.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members added successfully")},onError:r=>{console.error("Failed to add group members:",r),s.ue.error("Failed to add members",{description:r.message})}})}function sn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>Ja(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r,l),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["group",l.groupId]}),a.invalidateQueries({queryKey:["group-members",l.groupId]}),a.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members removed successfully")},onError:r=>{console.error("Failed to remove group members:",r),s.ue.error("Failed to remove members",{description:r.message})}})}function tn({onSuccess:t,tenantId:n,isTenantUser:a}){const[r,l]=k.useState(""),[c,d]=k.useState(""),[o,i]=k.useState({}),u=Xa(),m=()=>{const h={};return r.trim()?r.length<3?h.name="Group name must be at least 3 characters":r.length>50&&(h.name="Group name must be less than 50 characters"):h.name="Group name is required",c&&c.length>200&&(h.description="Description must be less than 200 characters"),i(h),Object.keys(h).length===0},x=async h=>{if(h.preventDefault(),!m())return;const p={name:r.trim(),description:c.trim()||void 0,type:a?"TENANT_GROUP":"ORG_GROUP",...a&&n?{tenantId:n}:{}};try{await u.mutateAsync(p),l(""),d(""),i({}),t()}catch(b){console.error("Failed to create group:",b)}};return e.jsxs("form",{onSubmit:x,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"group-name",children:["Group Name ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(s.Input,{id:"group-name",placeholder:"e.g., Marketing Team, Engineering Squad",value:r,onChange:h=>{l(h.target.value),o.name&&i(p=>({...p,name:""}))},className:o.name?"border-destructive":"",disabled:u.isPending}),o.name&&e.jsx("p",{className:"text-sm text-destructive",children:o.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"group-description",children:["Description",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:"(optional)"})]}),e.jsx(s.Textarea,{id:"group-description",placeholder:"Describe the purpose of this group...",value:c,onChange:h=>{d(h.target.value),o.description&&i(p=>({...p,description:""}))},className:o.description?"border-destructive":"",disabled:u.isPending,rows:3}),o.description&&e.jsx("p",{className:"text-sm text-destructive",children:o.description}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[c.length,"/200 characters"]})]}),e.jsx("div",{className:"rounded-lg border bg-muted/50 p-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(s.CircleAlert,{className:"h-4 w-4 mt-0.5 text-muted-foreground"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This group will be accessible to users in your workspace. You can add members after creating the group."})]})})]}),e.jsxs("div",{className:"flex justify-end gap-3",children:[e.jsx(s.Button,{type:"button",variant:"outline",onClick:()=>{l(""),d(""),i({})},disabled:u.isPending,children:"Clear"}),e.jsx(s.Button,{type:"submit",disabled:u.isPending||!r.trim(),children:u.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Users,{className:"mr-2 h-4 w-4"}),"Create Group"]})})]})]})}function an({open:t,onOpenChange:n,group:a,onUpdate:r}){const[l,c]=k.useState("members"),[d,o]=k.useState(""),[i,u]=k.useState([]),[m,x]=k.useState([]),{data:h,isLoading:p,refetch:b}=s.useGroupMembers(a.id),f=a.type==="TENANT_GROUP"?"tenant":"organization",{users:j,isLoading:N}=s.useUnifiedUsers({type:f,tenantId:a.tenantId||void 0,active:!0,limit:100}),C=en(),L=sn(),A=(h==null?void 0:h.members)||[],w=k.useMemo(()=>new Set(A.map(I=>I.userId)),[A]),D=k.useMemo(()=>j.filter(I=>!w.has(I.id)),[j,w]),g=k.useMemo(()=>{if(!d)return D;const I=d.toLowerCase();return D.filter(T=>{var M,O;return((M=T.name)==null?void 0:M.toLowerCase().includes(I))||((O=T.email)==null?void 0:O.toLowerCase().includes(I))})},[D,d]),y=k.useMemo(()=>{if(!d)return A;const I=d.toLowerCase();return A.filter(T=>{var M,O,E,P;return((O=(M=T.user)==null?void 0:M.name)==null?void 0:O.toLowerCase().includes(I))||((P=(E=T.user)==null?void 0:E.email)==null?void 0:P.toLowerCase().includes(I))})},[A,d]),v=async()=>{if(i.length!==0)try{await C.mutateAsync({groupId:a.id,data:{userIds:i,userType:f==="tenant"?"tenant":"org"}}),u([]),c("members"),b(),r==null||r()}catch(I){console.error("Failed to add members:",I)}},R=async()=>{if(m.length!==0)try{await L.mutateAsync({groupId:a.id,data:{userIds:m}}),x([]),b(),r==null||r()}catch(I){console.error("Failed to remove members:",I)}},S=I=>{u(T=>T.includes(I)?T.filter(M=>M!==I):[...T,I])},F=I=>{x(T=>T.includes(I)?T.filter(M=>M!==I):[...T,I])};return e.jsx(e.Fragment,{children:e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-3xl max-h-[80vh]","aria-describedby":"group-members-description",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:a.name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[A.length," ",A.length===1?"member":"members"]})}),e.jsxs("p",{id:"group-members-description",className:"sr-only",children:["Add or remove members from the ",a.name," group"]})]}),e.jsxs(s.Tabs,{value:l,onValueChange:I=>{c(I),o(""),x([])},className:"mt-4",children:[e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"members",children:"Current Members"}),e.jsx(s.TabsTrigger,{value:"add",children:"Add Members"})]}),e.jsxs(s.TabsContent,{value:"members",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search members...",value:d,onChange:I=>o(I.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:m.length>0?"h-[300px]":"h-[350px]",children:p?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(I=>e.jsx(s.Skeleton,{className:"h-16 w-full"},I))}):y.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.Users,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:d?"No members found":"No members yet"}),e.jsx("p",{className:"text-xs mt-1",children:d?"Try a different search":'Switch to the "Add Members" tab to add people to this group'})]}):e.jsx("div",{className:"space-y-2",children:y.map(I=>e.jsx(nn,{member:I,selected:m.includes(I.userId),onToggle:()=>F(I.userId)},I.id))})}),m.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[m.length," member",m.length!==1?"s":""," selected"]}),e.jsx(s.Button,{variant:"destructive",size:"sm",onClick:R,disabled:L.isPending,children:L.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Removing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Trash2,{className:"mr-2 h-4 w-4"}),"Remove Selected"]})})]})]}),e.jsxs(s.TabsContent,{value:"add",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search users to add...",value:d,onChange:I=>o(I.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[300px]",children:N?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(I=>e.jsx(s.Skeleton,{className:"h-16 w-full"},I))}):g.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.UserPlus,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:"No available users"}),e.jsx("p",{className:"text-xs mt-1",children:d?"Try a different search":"All eligible users are already members"})]}):e.jsx("div",{className:"space-y-2",children:g.map(I=>e.jsx(rn,{user:I,selected:i.includes(I.id),onToggle:()=>S(I.id)},I.id))})}),i.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[i.length," user",i.length!==1?"s":""," selected"]}),e.jsx(s.Button,{onClick:v,disabled:C.isPending,children:C.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Adding..."]}):e.jsxs(e.Fragment,{children:[e.jsx(s.UserPlus,{className:"mr-2 h-4 w-4"}),"Add Members"]})})]})]})]})]})})})}function nn({member:t,selected:n,onToggle:a}){var l,c,d,o;const r=((c=(l=t.user)==null?void 0:l.name)==null?void 0:c.split(" ").map(i=>i[0]).join("").toUpperCase())||"?";return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-muted/50 cursor-pointer",onClick:a,children:[e.jsx(s.Checkbox,{checked:n}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:((d=t.user)==null?void 0:d.name)||"Unknown User"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(o=t.user)==null?void 0:o.email})]})]})}function rn({user:t,selected:n,onToggle:a}){var l;const r=((l=t.name)==null?void 0:l.split(" ").map(c=>c[0]).join("").toUpperCase())||"?";return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-muted/50 cursor-pointer",onClick:a,children:[e.jsx(s.Checkbox,{checked:n}),e.jsx(s.Avatar,{className:"h-8 w-8",children:e.jsx(s.AvatarFallback,{className:"text-xs",children:r})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:t.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.email})]})]})}function ln({open:t,onOpenChange:n}){const[a,r]=k.useState("groups"),[l,c]=k.useState(""),[d,o]=k.useState(null),[i,u]=k.useState(!1),[m,x]=k.useState(null),{tokenProps:h}=s.useSemaphorContext(),{currentUser:p}=s.useCurrentUserInfo(),b=Za(),f=(p==null?void 0:p.type)==="tenant",j=h==null?void 0:h.tenantId,{groups:N,isLoading:C,refetch:L}=s.useGroups({type:f?"TENANT_GROUP":"all",tenantId:f?j:void 0,includeMembers:!1}),A=N.filter(y=>{var v;return y.name.toLowerCase().includes(l.toLowerCase())||((v=y.description)==null?void 0:v.toLowerCase().includes(l.toLowerCase()))}),w=async()=>{if(m)try{await b.mutateAsync(m.id),x(null),L()}catch(y){console.error("Failed to delete group:",y)}},D=y=>{o(y),u(!0)},g=()=>{r("groups"),L()};return e.jsxs(e.Fragment,{children:[e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-4xl max-h-[80vh]",children:[e.jsxs(s.DialogHeader,{children:[e.jsxs(s.DialogTitle,{className:"flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Group Management"]}),e.jsx(s.DialogDescription,{children:"Manage your groups, create new groups, and control group membership"})]}),e.jsxs(s.Tabs,{value:a,onValueChange:r,className:"mt-4",children:[e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsxs(s.TabsTrigger,{value:"groups",className:"flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4"}),"Groups"]}),e.jsxs(s.TabsTrigger,{value:"create",className:"flex items-center gap-2",children:[e.jsx(s.Plus,{className:"h-4 w-4"}),"Create Group"]})]}),e.jsx(s.TabsContent,{value:"groups",className:"mt-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search groups...",value:l,onChange:y=>c(y.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[400px]",children:C?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(y=>e.jsx(s.Skeleton,{className:"h-24 w-full"},y))}):A.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.Users,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:"No groups found"}),e.jsx("p",{className:"text-xs mt-1",children:l?"Try a different search":"Create your first group to get started"})]}):e.jsx("div",{className:"space-y-3",children:A.map(y=>e.jsx(on,{group:y,onManageMembers:()=>D(y),onDelete:()=>x(y),currentUserId:p==null?void 0:p.id},y.id))})})]})}),e.jsx(s.TabsContent,{value:"create",className:"mt-4",children:e.jsx(tn,{onSuccess:g,tenantId:j,isTenantUser:f})})]})]})}),d&&e.jsx(an,{open:i,onOpenChange:u,group:d,onUpdate:()=>L()}),e.jsx(s.AlertDialog,{open:!!m,onOpenChange:()=>x(null),children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Group"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',m==null?void 0:m.name,'"? This action cannot be undone and will remove all members from the group.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:w,disabled:b.isPending,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:b.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Deleting..."]}):"Delete Group"})]})]})})]})}function on({group:t,onManageMembers:n,onDelete:a,currentUserId:r}){const l=t.createdBy===r;return e.jsx("div",{className:"rounded-lg border bg-card p-4 transition-colors hover:bg-muted/50",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:t.name}),t.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:t.description})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(s.Users,{className:"h-3 w-3"}),t.memberCount," ",t.memberCount===1?"member":"members"]}),e.jsxs("span",{children:["Created ",s.format(new Date(t.createdAt),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:n,title:"Manage members",children:e.jsx(s.UserPlus,{className:"h-4 w-4"})}),l&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:a,title:"Delete group",className:"text-destructive hover:text-destructive",children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]})})}function os(t){const[n,a]=k.useState(null),[r,l]=k.useState(null);return k.useEffect(()=>{if(!t||t.trim()===""){a(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const o=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(o,{method:"HEAD"})).ok)throw new Error(`Module not found at ${o}`)}catch{}const i=await import(o);if(typeof i.useChartStore!="function")throw new Error("useChartStore is not a function");a(()=>i.useChartStore),l(null)}catch(d){const o=d instanceof Error?d.message:"Unknown error";console.error("Failed to load remote chart store:",o),l(o),a(null)}})()},[t]),n}function cn(t){const n=t.toUpperCase().indexOf("WHERE"),a=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let c=t.length;if(l!==-1&&(c=l),r!==-1&&r<c&&(c=r),n!==-1){const d=t.substring(0,n),o=t.substring(n);return`${d} {{ filters | where }} AND ${o.substring(6)}`}else if(a!==-1){const d=t.substring(0,a),o=t.substring(a);return`${d} {{ filters | where }} ${o}`}else{const d=t.substring(0,c),o=t.substring(c);return console.log("beforeClause",d),console.log("afterClause",o),o?`${d} {{ filters | where }} ${o}`:`${d.replace(/;$/,"")} {{ filters | where }}`}}function dn(t,n){if(t.length===0)return"";if(n){const a=t.find(r=>r.id===n);if(a){const r=a.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const c=r.split("__")[0],d=t.find(o=>o.tabTitle===c);return d?d.id:t[0].id}return n}}return t[0].id}async function Ts(t,n,a,r){if(!n||!a)throw new Error("Missing auth token or visual ID");const l=["resource-by-id","visual",a],c=r.getQueryData(l);if(c)return console.log("Using cached visual data for:",a),{data:c,fromCache:!0};console.log("Fetching visual data from network for:",a);const d=s.ue.loading("Loading visual...",{position:"top-center"});try{const o=await fetch(`${t}/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${n}`}});if(!o.ok)throw new Error("Failed to load visual");const i=await o.json();return r.setQueryData(l,i),s.ue.dismiss(d),{data:i,fromCache:!1}}catch(o){throw s.ue.dismiss(d),o}}function nt(t){if(typeof t=="string")return JSON.parse(t);if(typeof t=="object")return t;throw new Error("Invalid frame object format")}function un(t,n){var c,d;const a=(t==null?void 0:t.frameObject)??((c=t==null?void 0:t.visual)==null?void 0:c.frameObject);if(!a)return!1;const r=nt(a);if(!(r!=null&&r.cards)||r.cards.length===0)return!1;const l=(d=r.cards)==null?void 0:d.find(o=>o.id===r.activeCardId);return l?(s.setupEditorWithCard({...n,frame:r,card:l,visualId:(t==null?void 0:t.id)||r.visualId}),!0):!1}function mn(){var h;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(p=>p.frame),a=s.useEditorStore(p=>p.card),r=os(((h=a.customCardPreferences)==null?void 0:h.url)||""),l=s.useEditorStore(p=>p.selectedSchemaName),c=s.useEditorStore(p=>p.selectedDatamodelId),d=s.useEditorStore(p=>p.selectedDatabaseName),o=s.useEditorStore(p=>p.selectedTableName),i=s.useEditorStore(p=>p.selectedConnectionId),u=s.useEditorStore(p=>p.isShowingVisual),m=a.sql;return{getUpdatedFrame:k.useCallback(()=>{var N;let p=m;m&&!m.includes("{{")&&(p=cn(m),t(p));const b=(N=r==null?void 0:r.getState())==null?void 0:N.settings,f={...a,dataSource:a.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:c,lastSelectedDatabase:d,lastSelectedTable:o,connectionId:i,sql:p,customCfg:u?a.customCfg:null,preferences:a.preferences,...b&&{customCardPreferences:{...a.customCardPreferences,settings:b}}},j=n.cards.map(C=>C.id===a.id?f:C);return{...n,cards:j,activeCardId:dn(j,n.activeCardId)}},[a,n,u,l,c,d,o,i,t,r,m])}}function Me(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient(),r=s.useSelectedVisual(),{selectVisual:l}=s.useManagementActions(),{setFrame:c,setCard:d,setIsDevMode:o,setActiveTabCardId:i,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:x,setSelectedDatabaseName:h,setSelectedSchemaName:p,setSelectedTableName:b,setSelectedDatamodelId:f,setFilterValues:j,setApplyFilters:N}=s.useEditorActions(),{setIsDashboardEditing:C,setIsVisualEditing:L,setSelectedFrameId:A,clearSelectedFrameId:w,addFrame:D,setIsDashboardPanelOpen:g}=s.useDashboardActions(),y=s.useDashboardStore(M=>M.selectedSheetId),v=s.useDashboardStore(M=>M.selectedFrameId),R=s.useDashboardStore(M=>M.dashboard),S=s.useDashboardStore(M=>M.filterValues),F=s.useVisualById((r==null?void 0:r.id)||"",{enabled:!!(r!=null&&r.id)&&!!(t!=null&&t.accessToken)}),I=k.useCallback(async M=>{try{l(M),w();const{data:O,fromCache:E}=await Ts(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",M.id,a);if(!un(O,{setFrame:c,setCard:d,setIsDevMode:o,setActiveTabCardId:i,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:x,setSelectedDatabaseName:h,setSelectedSchemaName:p,setSelectedTableName:b,setSelectedDatamodelId:f,setFilterValues:j,setApplyFilters:N,setIsDashboardEditing:C,setIsVisualEditing:L,dashboard:R,selectedSheetId:y,selectedFrameId:v,filterValues:S}))throw new Error("Failed to setup editor with visual data");return{success:!0,fromCache:E}}catch(O){return console.error("Error editing visual:",O),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,c,d,C,L,o,i,u,m,x,h,p,b,f,j,N,w,R,y,v,S]),T=k.useCallback(async M=>{var O;try{if(l(M),!y)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:E,fromCache:P}=await Ts(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",M.id,a),B=(E==null?void 0:E.frameObject)??((O=E==null?void 0:E.visual)==null?void 0:O.frameObject);if(!B)return{success:!1,error:"Visual has no frame data"};const Y=nt(B);if(!(Y!=null&&Y.cards)||Y.cards.length===0)return{success:!1,error:"Visual frame is malformed"};const q={...Y,id:s.v4(),visualId:M.id};return D(y,q,"end"),C(!0),A(q.id),g(!1),{success:!0,fromCache:P}}catch(E){return console.error("Error adding visual:",E),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,y,D,C,A,g]);return{visual:F.data,isLoading:F.isLoading,isError:F.isError,error:F.error,handleEditLibraryVisual:I,handleAddLibraryVisual:T,getUpdatedFrame:mn().getUpdatedFrame,refetch:F.refetch}}function hn({open:t,onOpenChange:n,isLibraryVisual:a,currentVisualName:r,isSaving:l=!1,onConfirm:c}){const[d,o]=k.useState(a&&r?`Copy of ${r}`:r||""),[i,u]=k.useState(""),[m,x]=k.useState(!a),[h,p]=k.useState(!0);k.useEffect(()=>{t&&(o(a&&r?`Copy of ${r}`:r||""),u(""),x(!a),p(!0))},[t,a,r]);const b=()=>{d.trim()&&(!m&&!h||c({name:d.trim(),description:i.trim()||void 0,saveToLibrary:m,saveToCurrentDashboard:h}))},f=d.trim()&&(m||h);return e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Save Visual As"}),e.jsx(s.DialogDescription,{children:a?"Create a copy of this visual with a new name":"Save this visual to make it reusable"})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"name",children:"Name"}),e.jsx(s.Input$1,{id:"name",value:d,onChange:j=>o(j.target.value),placeholder:"Enter visual name",disabled:l})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"description",children:"Description (optional)"}),e.jsx(s.Textarea,{id:"description",value:i,onChange:j=>u(j.target.value),placeholder:"Enter visual description",rows:3,disabled:l})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Label,{children:"Save to:"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"save-to-dashboard",checked:h,onCheckedChange:j=>p(!!j),disabled:l}),e.jsxs("label",{htmlFor:"save-to-dashboard",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Current Dashboard",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:a?"(add copy to this dashboard)":"(keep as local visual)"})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"save-to-library",checked:m,onCheckedChange:j=>x(!!j),disabled:l}),e.jsxs("label",{htmlFor:"save-to-library",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Visual Library",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:a?"(save as new reusable visual)":"(make available to all dashboards)"})]})]})]}),!m&&!h&&e.jsx("p",{className:"text-sm text-destructive",children:"Please select at least one destination"})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),disabled:l,children:"Cancel"}),e.jsxs(s.Button,{onClick:b,disabled:!f||l,children:[l&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Saving...":"Save"]})]})]})})}function xn({className:t,variant:n="outline"}){var o;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(i=>i.frame);const r=s.useEditorStore(i=>i.card);os(((o=r.customCardPreferences)==null?void 0:o.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),r.sql;const l=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:c}=Me();function d(){const i=c();l==null||l(i)}return e.jsxs(s.Button,{onClick:d,className:s.cn("h-8",t),size:"sm",variant:n,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function pn({className:t,variant:n="default"}){const a=s.useQueryClient(),[r,l]=k.useState(!1),c=s.useDashboardStore(h=>h.actions.setIsDashboardPanelOpen),{setIsVisualEditing:d}=s.useDashboardActions(),{getUpdatedFrame:o}=Me(),i=s.useSelectedVisual(),u=s.useEditorStore(h=>h.frame),m=s.useUpdateVisualMutation(),x=()=>{const h=o(),p=(u==null?void 0:u.visualId)||(i==null?void 0:i.id);if(!p){s.ue.error("No visual to save");return}l(!0),m.mutate({visualId:p,data:{frameObject:h}},{onSuccess:()=>{l(!1),c(!0),s.ue.success("Visual updated successfully"),a.invalidateQueries({queryKey:["resource-by-id","visual",p],exact:!0})},onError:()=>{l(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:x,className:s.cn("h-8",t),size:"sm",variant:n,children:[r&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!r&&e.jsxs(e.Fragment,{children:[e.jsx(Oe,{className:"mr-2 size-4 font-bold"}),"Save to Library"]})]})}function fn({className:t}){const n=s.useQueryClient(),[a,r]=k.useState(!1),l=s.useSelectedVisual(),c=s.useEditorStore(h=>h.frame),d=s.useDashboardStore(h=>h.selectedSheetId),{updateFrame:o,setIsVisualEditing:i}=s.useDashboardActions(),{getUpdatedFrame:u}=Me(),m=s.useUpdateVisualMutation(),x=async()=>{if(!d){s.ue.error("No sheet selected");return}const h=(c==null?void 0:c.visualId)||(l==null?void 0:l.id);if(!h){s.ue.error("No visual to update");return}r(!0);try{const p=u();await m.mutateAsync({visualId:h,data:{frameObject:p}});const b={...p,visualId:h};o(d,b),n.invalidateQueries({queryKey:["visuals"]}),n.invalidateQueries({queryKey:["visual",h]}),s.ue.success("Saved to library and applied locally"),setTimeout(()=>{i(!1)},300)}catch(p){console.error("Failed to save and apply:",p),s.ue.error("Failed to save and apply changes")}finally{r(!1)}};return e.jsx(s.Button,{onClick:x,className:s.cn("h-8",t),size:"sm",variant:"default",disabled:a,children:a?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Oe,{className:"mr-2 size-4 font-bold"}),"Save & Apply"]})})}function gn({className:t}){const{getUpdatedFrame:n}=Me();s.useEditorStore(i=>i.frame);const a=s.useDashboardStore(i=>i.selectedSheetId),{updateFrame:r,setIsVisualEditing:l}=s.useDashboardActions(),[c,d]=k.useState(!1),o=()=>{if(!a){s.ue.error("No sheet selected");return}d(!0);const u={...n(),visualId:void 0};r(a,u),setTimeout(()=>{d(!1),s.ue.success("Changes applied. Visual is now local to this dashboard"),l(!1)},300)};return e.jsxs(s.Button,{onClick:o,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[c&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Applying"]}),!c&&e.jsxs(e.Fragment,{children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Apply Locally"]})]})}function jn({className:t}){const{setTempQueryData:n,setSqlGen:a}=s.useEditorActions(),r=s.useQueryClient(),l=s.useEditorStore(u=>u.tempQueryData),c=s.useEditorStore(u=>u.onClose),d=s.useEditorStore(u=>u.card),{queryKey:o}=s.useDashboardCardQuery(d);function i(){if(l){const{queryKey:u,queryData:m}=l;u&&m&&r.setQueryData(u,m)}a({}),c==null||c()}return e.jsxs(s.Button,{onClick:i,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function is(){const{setTempQueryData:t}=s.useEditorActions(),n=s.useQueryClient();s.useEditorStore(f=>f.isDevMode);const a=s.useEditorStore(f=>f.tempQueryData),r=s.useEditorStore(f=>f.card),{queryKey:l}=s.useDashboardCardQuery(r),{setCardSql:c,setSqlGen:d,setCardPython:o,setCardCustomCfg:i,setCardPreferences:u,updateDataSource:m,clearQueryConfig:x,setCardConfig:h,setCardType:p}=s.useEditorActions();function b(){const f=n.getQueryData(l);a!=null&&a.queryData||t({queryKey:l,queryData:f}),n.setQueryData(l,null),n.removeQueries({queryKey:l,exact:!0}),c(""),d({}),x(),h(void 0),o(""),i(""),u({}),p("bar")}return e.jsxs(s.Button,{onClick:b,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(Qt,{className:"mr-2 size-4"}),"Clear"]})}function bn(){const[t,n]=k.useState(!1),[a,r]=k.useState(!1),[l,c]=k.useState(null),d=s.useEditorStore(A=>A.frame),o=s.useEditorStore(A=>A.card),i=s.useSelectedVisual(),u=s.useDashboardStore(A=>A.selectedSheetId),m=s.useDashboardStore(A=>A.actions.setIsDashboardPanelOpen),{getUpdatedFrame:x}=Me(),{selectVisual:h}=s.useManagementActions(),{addFrame:p,setSelectedFrameId:b,setIsVisualEditing:f}=s.useDashboardActions(),j=!!(d!=null&&d.visualId),N=(i==null?void 0:i.title)||(o==null?void 0:o.title)||"Untitled Visual",C=s.useCreateVisualWithFrame(A=>{if(A!=null&&A.id){if(h(A),a&&l&&u){const w={...l,id:s.v4(),visualId:A.id};p(u,w,"end"),b(w.id),r(!1),c(null),f(!1)}m(!0),n(!1)}});return{saveAsDialogOpen:t,setSaveAsDialogOpen:n,handleSaveAs:async A=>{if(!u){s.ue.error("No sheet selected");return}const w=x();if(A.saveToLibrary){r(A.saveToCurrentDashboard),c(w);const D={title:A.name,description:A.description,frameObject:w,isPrivate:!1};C.mutate(D)}else if(A.saveToCurrentDashboard){const D={...w,id:s.v4(),visualId:void 0,cards:w.cards.map(g=>({...g,title:g.id===o.id?A.name:g.title}))};p(u,D,"end"),b(D.id),s.ue.success("Visual saved to dashboard"),n(!1),f(!1)}},isLibraryVisual:j,currentVisualName:N,isSaving:C.isPending}}function rt({className:t}){const n=s.useEditorStore(C=>C.frame),a=s.useEditorStore(C=>C.card),r=s.useManagementStore(C=>C.selectedVisual),l=s.useDashboardStore(C=>C.selectedFrameId),c=s.useDashboardStore(C=>C.selectedSheetId),{setIsVisualEditing:d}=s.useDashboardActions(),o=!!(n!=null&&n.visualId||r!=null&&r.id),i=!!(n!=null&&n.visualId&&l),u=o&&!i,{saveAsDialogOpen:m,setSaveAsDialogOpen:x,handleSaveAs:h,isLibraryVisual:p,currentVisualName:b,isSaving:f}=bn(),{handleAddLibraryVisual:j}=Me(),N=async()=>{if(!c){s.ue.error("No dashboard sheet selected");return}if(!r){s.ue.error("No visual selected");return}const C=await j(r);C.success?(s.ue.success("Visual added to dashboard"),d(!1)):s.ue.error(C.error||"Failed to add visual to dashboard")};return e.jsxs(e.Fragment,{children:[!o&&e.jsx(xn,{className:t,variant:"default"}),o&&e.jsxs(e.Fragment,{children:[i&&e.jsx(gn,{className:t}),u&&c&&a&&(a.sql||s.hasValidCardConfig(a.config))&&e.jsxs(s.Button,{onClick:N,className:s.cn(t),size:"sm",variant:"outline",children:[e.jsx(Gt,{className:"mr-2 size-4 font-bold"}),"Add to Dashboard"]}),u&&e.jsx(pn,{className:t,variant:"default"}),i&&e.jsx(fn,{className:t}),e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:s.cn(t,"w-8 p-0"),children:e.jsx(s.EllipsisVertical,{className:"h-4 w-4"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.stopPropagation(),x(!0)},children:[e.jsx(Oe,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]})]}),!o&&e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:s.cn(t,"w-8 p-0"),children:e.jsx(s.EllipsisVertical,{className:"h-4 w-4"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:()=>x(!0),children:[e.jsx(Oe,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]}),e.jsx(jn,{className:t}),e.jsx(hn,{open:m,onOpenChange:C=>{f||x(C)},isLibraryVisual:p,currentVisualName:b,isSaving:f,onConfirm:h})]})}function lt({className:t,labelClassName:n,switchClassName:a}){const r=s.useEditorStore(i=>i.isDevMode),l=s.useDashboardStore(i=>i.isVisualEditing),{setIsDevMode:c}=s.useEditorActions(),{config:d}=k.useContext(s.SemaphorContext).tokenProps,o=(d==null?void 0:d.showAdvancedMode)!==!1;return!l||!o?null:e.jsxs("div",{className:s.cn("flex items-center space-x-2",t),children:[e.jsx(s.Switch,{className:s.cn("",a),checked:r,onCheckedChange:()=>c(!r),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:s.cn("text-sm font-medium",n),children:"Advanced Mode"})]})}function vn(){var xe,ce,K;const{authToken:t,tokenProps:n,id:a}=s.useSemaphorContext(),{isLocalDev:r,isConsoleMode:l}=s.useDashboardPreferences(),{permissions:c}=s.useRoleAwareDisplayPreferences(),d=s.useHasDashboardId();s.useDashboardStore(G=>G.theme);const o=s.useDashboardStore(G=>G.lenses),i=s.useDashboardStore(G=>G.selectedLensId),u=o==null?void 0:o.find(G=>G.id===i),m=s.useDashboardStore(G=>G.dashboard);s.useDashboardStore(G=>G.selectedSheetId);const x=s.useDashboardStore(G=>G.isDashboardEditing),[h,p]=k.useState(!1),[b,f]=k.useState(!1),[j,N]=k.useState(!1),C=s.useDashboardStore(G=>G.isDashboardPanelOpen),L=s.useDashboardStore(G=>G.actions.setIsDashboardPanelOpen),A=s.useDashboardStore(G=>G.filterValues),w=s.useDashboardStore(G=>G.isVisualEditing),D=s.useEditorStore(G=>G.card),g=s.useManagementStore(G=>G.selectedDashboard),y=s.useManagementStore(G=>G.initialDashboard),v=s.useManagementStore(G=>G.selectedVisual);s.useDashboardStore(G=>G.selectedFrameId),s.useEditorStore(G=>G.frame);const R=g?(ce=g==null?void 0:g.permissions)==null?void 0:ce.canEdit:(xe=y==null?void 0:y.permissions)==null?void 0:xe.canEdit,S=s.useDashboardStore(G=>G.showFilters),F=s.useDashboardStore(G=>G.showDashboardJSON),I=s.useDashboardStore(G=>G.onSaveFunction),T=s.useDashboardStore(G=>G.actions.setShowFilters),{setIsDashboardEditing:M,setShowDashboardJSON:O}=s.useDashboardStore(G=>G.actions),{setInitialDashboard:E,clearSelectedDashboard:P}=s.useManagementStore(G=>G.actions),{resources:B}=s.useResourceManagement(s.ResourceType.DASHBOARD),{currentUser:Y}=s.useCurrentUserInfo(),q=s.canUserManageGroups(Y),z=g||y,J=z?{id:z.id,title:(m==null?void 0:m.title)||z.title||"Dashboard"}:null,{handleAddNewFrame:W}=s.useAddNewFrame(),[se,te]=k.useState(!1),oe=s.useUpdateResource(s.ResourceType.DASHBOARD);k.useEffect(()=>{if(B&&B.length>0){const G=m==null?void 0:m.id;if(G){const V=B.find(Z=>Z.id===G);V&&E(V)}}},[B,m==null?void 0:m.id,E]);const Q=n.orgUserId||n.tenantId,_=x&&!w&&Q&&R,ae=()=>{M(!0)};async function H(){const G=Ke(m);te(!0);const V={template:G};oe.mutate({resourceId:G.id,data:V},{onSuccess:()=>{te(!1),s.ue.success("Dashboard saved!")},onError:()=>{te(!1),s.ue.error("Failed to save dashboard")}})}async function re(){if(p(!0),!i||!u)return;const G=Ke(m),V=JSON.stringify(G),Z={...u,template:V,filterValues:A};await ts(n.apiServiceUrl,Z,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),I==null||I(G),p(!1)}const ie=(u==null?void 0:u.name)||m.title,U=B&&B.length>0&&(n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail),X=g&&!(n!=null&&n.dashboard_id)&&!a;return e.jsxs("div",{className:"flex h-11 items-center justify-between gap-2 border-b px-4 py-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[U&&e.jsxs(e.Fragment,{children:[e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:"Manage Dashboards",onClick:()=>{L(!C)},className:"h-7 p-2",children:e.jsx(ia,{className:"h-4 w-4"})}),X&&!w&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Dashboard Hub",onClick:()=>P(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})})]}),!w&&d&&e.jsx(s.Label,{children:ie}),w&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm font-medium",children:(v==null?void 0:v.title)||(D==null?void 0:D.title)||"Untitled Visual"}),e.jsx(at,{})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[w&&e.jsxs(e.Fragment,{children:[e.jsx(lt,{className:"mr-2"}),e.jsx(rt,{className:"h-7"})]}),r&&!w&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:()=>s.invalidateToken(n.apiServiceUrl),className:"h-7 p-2",children:e.jsx(xa,{className:"h-4 w-4"})}),!w&&d&&e.jsx(ka,{}),!w&&d&&e.jsx(qs,{}),!w&&d&&q&&e.jsx(s.IconButton,{tooltip:"Manage Groups",onClick:()=>N(!0),className:"h-7 p-2",children:e.jsx(s.Users,{className:"h-4 w-4"})}),!w&&d&&((K=z==null?void 0:z.permissions)==null?void 0:K.canShare)&&e.jsx(s.IconButton,{tooltip:"Share Dashboard",onClick:()=>f(!0),className:"h-7 p-2",children:e.jsx(Ie,{className:"h-4 w-4"})}),!S&&!w&&x&&c.canUseFilters&&d&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>T(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),x&&!w&&Q&&r&&d&&e.jsx(Da,{}),!w&&Q&&r&&d&&e.jsx(Ta,{}),x&&!w&&Q&&u&&r&&d&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:h,onClick:re,size:"sm",children:[e.jsx(Oe,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),x&&!w&&d&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!x,onClick:()=>W(),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Visual"]}),!w&&!x&&c.canEdit&&d&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:ae,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),_&&d&&e.jsxs(s.Button,{className:"h-7 p-2",disabled:se,onClick:H,size:"sm",children:[se?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Oe,{className:"mr-2 h-4 w-4"}),se?"Saving...":"Save"]}),!w&&x&&r&&d&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>O(!F),size:"sm",variant:"ghost",children:e.jsx(Us,{className:"h-4 w-4"})})}),!w&&r&&e.jsx(Na,{}),x&&!w&&d&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{M(!1),O(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),b&&J&&e.jsx(We,{resource:J,resourceType:s.ResourceType.DASHBOARD,onClose:()=>f(!1)}),e.jsx(ln,{open:j,onOpenChange:N})]})]})}function cs(t){const{tokenProps:n,authToken:a}=s.useSemaphorContext(),r=n==null?void 0:n.apiServiceUrl;return s.useQuery({queryKey:["joinability-map",t],queryFn:async()=>{if(!t||!(a!=null&&a.accessToken))return null;const l=`${r}/v1/domains/${t}/joinability`;return s.getRequest(l,a.accessToken)},enabled:!!t&&!!(a!=null&&a.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:l=>Math.min(1e3*2**l,3e4)})}function Ve(t,n,a){if(n==="source")return{isValid:!0};const r=s.getDataType(t.dataType);if(a==="kpi"){if(n==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(n==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function as(t,n,a,r,l){if(t!=="kpi"||l.length<3)return;const c=(n==null?void 0:n.groupByColumns)&&n.groupByColumns.length>0,d=(n==null?void 0:n.comparisonType)==="none";!c&&d||a(r,{groupByColumns:[],comparisonType:"none"})}const ds=t=>{var I;const n=(I=t==null?void 0:t.dataSource)==null?void 0:I.semanticDomainId,{data:a}=cs(n),{updateCardConfig:r,updateGroupByColumn:l,updateMetricColumn:c,updatePivotByColumn:d,updateSortByColumn:o,removeGroupByColumn:i,removeMetricColumn:u,removePivotByColumn:m,removeSortByColumn:x}=s.useEditorActions(),h=s.useEditorStore(T=>T.card.type),p=t==null?void 0:t.id,b=k.useCallback(T=>{if(!(t!=null&&t.config))return[];switch(T){case"groupBy":return(t.config.groupByColumns||[]).map(M=>({id:M.id,name:M.name,dataType:M.dataType,label:M.label!==void 0?M.label:M.name,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType,dateFormat:M.dateFormat,customFormat:M.customFormat,granularity:M.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(M=>({id:M.id,name:M.name,dataType:M.dataType,label:M.label!==void 0?M.label:M.name,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(M=>({id:M.id,name:M.name,dataType:M.dataType,label:M.label!==void 0?M.label:M.name,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType,direction:M.direction}));case"source":return[];default:return[]}},[t]),f=k.useCallback((T,M)=>{if(p)switch(T){case"groupBy":{r(p,{groupByColumns:M});break}case"metrics":{r(p,{metricColumns:M});break}case"pivotBy":{r(p,{pivotByColumns:M});break}case"sortBy":{r(p,{sortByColumns:M});break}}},[p,r]),j=k.useCallback((T,M,O)=>{if(!p)return;const P=b(T)[M];if(P)switch(T){case"groupBy":l(p,P.id,{label:O});break;case"metrics":c(p,P.id,{label:O});break;case"pivotBy":d(p,P.id,{label:O});break;case"sortBy":o(p,P.id,{label:O});break}},[p,b,l,c,d,o]),N=k.useCallback((T,M)=>{if(!p)return;const E=b("metrics")[T];E&&c(p,E.id,{aggregate:M,label:s.getAggregationLabel(E.name,M)})},[p,b,c]),C=k.useCallback((T,M,O)=>{if(!p)return;const P=b("groupBy")[T];if(!P)return;const B={dateFormat:M};M==="custom"&&O?B.customFormat=O:B.customFormat=void 0,l(p,P.id,B)},[p,b,l]),L=k.useCallback((T,M)=>{if(!p)return;const E=b("groupBy")[T];E&&l(p,E.id,{granularity:M})},[p,b,l]),A=k.useCallback((T,M)=>{if(!p)return;const E=b("metrics")[T];E&&c(p,E.id,{aliasTemplate:M})},[p,b,c]),w=k.useCallback((T,M)=>{if(console.log("handleValueAliasesChange",T,M),!p)return;console.log("handleValueAliasesChange",T,M);const E=b("metrics")[T];E&&(console.log("handleValueAliasesChange",M),c(p,E.id,{valueAliases:M}))},[p,b,c]),D=k.useCallback(T=>{if(!p)return;if(b("metrics").length===0){s.ue.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(p,{comparisonType:T})},[p,r,b]),g=k.useCallback(T=>{p&&r(p,{showTrendline:T})},[p,r]),y=k.useCallback(T=>{p&&r(p,{trendlineWindow:T})},[p,r]),v=k.useCallback(T=>{p&&r(p,{trendlineGranularity:T})},[p,r]),R=k.useCallback(T=>{p&&r(p,{targetValue:T})},[p,r]),S=k.useCallback(T=>{var q;if(!p)return;const M=[...b("groupBy"),...b("pivotBy"),...b("metrics"),...b("sortBy")],O=s.validateEntityConsistency(T,M,{joinPlan:(q=t==null?void 0:t.config)==null?void 0:q.joinPlan,joinabilityMap:a==null?void 0:a.joinabilityMap,semanticDomainId:n});if(!O.isValid){O.showError&&s.showJoinRequiredNotification();return}const E=s.getSmartContainerForField(T,M,h);if(!E){s.ue.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const P=Ve(T,E,h);if(!P.isValid){s.ue.error("Invalid Field Type",{description:P.reason,position:"top-center",duration:3e3});return}const B=b(E);if(s.fieldAlreadyExists(T,B))return;const Y=s.getNewField(T,E,B);if(Y){const z=[...B,Y];f(E,z),E==="metrics"&&as(h,t==null?void 0:t.config,r,p,z)}},[p,t==null?void 0:t.config,b,f,n,a,h,r]),F=k.useCallback((T,M)=>{if(!p)return;const E=b(T)[M];if(E){if(T!=="sortBy"){const P=b("sortBy"),B=P.filter(Y=>!(Y.name===E.name&&Y.qualifiedEntityName===E.qualifiedEntityName));B.length!==P.length&&r(p,{sortByColumns:B})}switch(T){case"groupBy":i(p,E.id);break;case"metrics":u(p,E.id);break;case"pivotBy":m(p,E.id);break;case"sortBy":x(p,E.id);break}}},[p,b,i,u,m,x,r]);return{getFieldsForContainer:b,setFieldsForContainer:f,updateLabel:j,handleAggregationChange:N,handleDateFormatChange:C,handleGranularityChange:L,handleAliasTemplateChange:A,handleValueAliasesChange:w,removeField:F,handleFieldClick:S,handleKpiComparisonTypeChange:D,handleKpiShowTrendlineChange:g,handleKpiTrendlineWindowChange:y,handleKpiTrendlineGranularityChange:v,handleKpiTargetValueChange:R,cardType:h}};function _e(t){return`${t}-${s.v4()}`}function ks(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"SUM":return`Sum of ${a}`;case"COUNT":return`Count of ${a}`;case"DISTINCT":return`Unique ${a}`;case"AVG":return`Average of ${a}`;case"MIN":return`Min of ${a}`;case"MAX":return`Max of ${a}`;default:return a}}function yn(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"day":return`Date of ${a}`;case"week":return`Week of ${a}`;case"month":return`Month of ${a}`;case"year":return`Year of ${a}`;default:return a}}function us(t){if(!t||!t.selectedEntities||t.selectedEntities.length===0)return{tableName:void 0,schemaName:void 0,databaseName:void 0,connectionId:t==null?void 0:t.connectionId,connectionType:t==null?void 0:t.connectionType};const n=t.selectedEntities[0];return{tableName:n==null?void 0:n.name,schemaName:n==null?void 0:n.schema,databaseName:n==null?void 0:n.database,connectionId:t.connectionId,connectionType:t.connectionType}}function ot(t){if(!t||!t.selectedEntities||t.selectedEntities.length===0)return!1;const n=t.selectedEntities[0];return!!(n!=null&&n.name)}function it(){const t=s.useEditorStore(D=>D.sqlGen),n=s.useEditorStore(D=>D.isDevMode),a=s.useEditorStore(D=>D.card.dataSource),r=s.useEditorStore(D=>{var g,y;return(y=(g=D.card)==null?void 0:g.queryConfig)==null?void 0:y.metricColumns}),{tableName:l,schemaName:c,databaseName:d}=us(a),o=ot(a),i=s.useEditorStore(D=>D.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:m,setCardSql:x,setRunSql:h,setSqlGen:p,setIsShowingVisual:b}=s.useEditorActions(),{connectionType:f,modelItems:j,selectedDatamodelName:N}=s.useEditorAside(),C=D=>({column_name:D.name,data_type:D.dataType,label:D.label,description:D.description});return{handleDevModeFieldClick:D=>{var y;if(!n)return;const g=C(D);if(n&&o&&l){const v=s.createSqlGenConfig(g,t);p(v);const R=(y=j==null?void 0:j.find(F=>F.id===i))==null?void 0:y.name,S=s.getSql(v,s.fmt(c||""),s.fmt(l),R||"",f,d||"");S&&(x(S),h(!0))}else if(!n){if(s.isTextDataType(g.data_type))if(r&&r.length>0){const v={...g,role:"groupby",id:_e(g.column_name),name:g.column_name,type:g.data_type};m(v)}else{const v={...g,role:"metric",id:_e(g.column_name),name:g.column_name,label:ks(g.column_name,"COUNT"),type:g.data_type,aggregate:"COUNT"};u(v)}if(s.isDateDataType(g.data_type)){const v={...g,role:"groupby",id:_e(g.column_name),name:g.column_name,type:g.data_type,label:yn(g.column_name,"month"),granularity:"month"};m(v)}if(s.isNumberDataType(g.data_type)){const v={...g,role:"metric",id:_e(g.column_name),name:g.column_name,label:ks(g.column_name,"SUM"),type:g.data_type,aggregate:"SUM"};u(v)}}},handleShowSample:()=>{if(!o||!l){console.warn("Cannot generate SQL: missing table metadata");return}const D=s.getFormattedTableNameForQuery({schemaName:c||"",tableName:l,modelName:N,connectionType:f,databaseName:d||""});b(!1);const g=f==="MSSQL"?`SELECT top 10 * FROM ${D}`:`SELECT * FROM ${D} LIMIT 10`;x(g),h(!0)},handleShowCount:()=>{if(!o||!l){console.warn("Cannot generate SQL: missing table metadata");return}const D=s.getFormattedTableNameForQuery({schemaName:c||"",tableName:l,modelName:N,connectionType:f,databaseName:d||""});x(`SELECT COUNT(*) as count FROM ${D}`),h(!0)},isNumberField:D=>s.isNumberDataType(D.dataType)}}function ct(){const t=s.useEditorStore(p=>p.selectedConnectionId),n=s.useEditorStore(p=>p.selectedDatamodelId),a=s.useEditorStore(p=>p.selectedDatabaseName),r=s.useEditorStore(p=>p.selectedSchemaName),l=s.useEditorStore(p=>p.selectedTableName),c=s.useDashboardStore(p=>p.dashboard.filters)||[],d=s.useDashboardStore(p=>p.actions.addFilter),o=s.useDashboardStore(p=>p.actions.removeFilter),{removeFilterValues:i}=s.useDashboardActions(),{modelItems:u,tableName:m,connectionType:x}=s.useEditorAside();function h(p,b="dashboard",f){var y;const j=s.fmt(p.column_name),N=s.fmt(a||""),C=s.fmt(r||""),L=s.fmt(m);let A=s.getQualifiedTableName({schemaName:C,tableName:L,connectionType:x,databaseName:N}),w=`${A}.${j}`;const D=(y=u==null?void 0:u.find(v=>v.id===n))==null?void 0:y.name;n&&n!=="none"&&(w=`${s.DATAMODEL_NAMESPCACE}.${D}.${j}`,A=`${s.DATAMODEL_NAMESPCACE}.${D}`),f!=null&&f.qualifiedFieldName&&(w=f.qualifiedFieldName),f!=null&&f.entityName&&(A=f.entityName);const g=c==null?void 0:c.find(v=>v.column===w&&v.table===L&&(v.database===N||v.database===a));if(g)i(g.id),o(g.id);else{const v=s.v4();return m==="api"&&t?(d({location:b,id:v,column:w,title:p.column_name,dataType:p.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(p.data_type,A,j)}),v):(d({id:v,location:b,column:w,title:p.column_name,dataType:p.data_type,table:l||"",database:a||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(p.data_type,A,j)}),v)}}return{assignFilter:h}}function Nn({column:t}){const[n,a]=k.useState(!1),r=s.useEditorStore(N=>N.card.dataSource),{tableName:l,schemaName:c,databaseName:d}=us(r),o=s.useEditorStore(N=>N.selectedDatamodelId),i=s.useEditorStore(N=>N.sqlGen),{modelItems:u,connectionType:m}=s.useEditorAside(),x=s.useEditorStore(N=>N.actions.setSqlGen),h=s.useEditorStore(N=>N.actions.setCardSql),p=s.useEditorStore(N=>N.actions.setRunSql),b=ot(r);function f(N,C){var D;if(!b||!l){console.warn("Cannot generate SQL: missing table metadata");return}const L=s.createSqlGenConfig(N,i,C),A=(D=u==null?void 0:u.find(g=>g.id===o))==null?void 0:D.name;x(L);const w=s.getSql(L,s.fmt(c||""),s.fmt(l),A||"",m,d||"");w&&(h(w),p(!0)),a(!1)}function j(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>f(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>f(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>f(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>f(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>f(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return b?e.jsxs(s.HoverCard,{openDelay:0,open:n,onOpenChange:a,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:j()})]}):null}function Cn({field:t,fieldState:n}){return e.jsxs("div",{className:"w-64 bg-background p-0",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground",children:t.label||t.name}),e.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:t.dataType})]}),t.description&&e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:t.description}),n&&n.tooltip&&e.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:n.tooltip})}),e.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.name})})]})}function Sn({field:t,context:n="editor",fieldState:a}){const r=s.useEditorStore(S=>S.isDevMode),l=n==="filter",c=r||l||(a==null?void 0:a.state)==="unreachable"&&!l,d=s.useDashboardStore(S=>S.dashboard.filters),{assignFilter:o}=ct(),i=l&&(d==null?void 0:d.some(S=>{var F;return S.title===t.name||((F=S.column)==null?void 0:F.includes(t.name))})),{attributes:u,listeners:m,setNodeRef:x,transform:h,transition:p,isDragging:b}=s.useSortable({id:t.id,disabled:c}),[f,j]=k.useState(!1),N=s.useEditorStore(S=>S.card),{handleFieldClick:C}=ds(N),{handleDevModeFieldClick:L,isNumberField:A}=it(),w=()=>{if(l){const S={column_name:t.name,data_type:t.dataType,label:t.label,description:t.description};o(S,"dashboard",t)}else r?L(t):C(t)},D={column_name:t.name,data_type:t.dataType,label:t.label,description:t.description},g={transform:s.CSS.Transform.toString(h),transition:p},v=(()=>{if(!a||l)return{};const F={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[a.state]||{};return a.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",...F},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...F},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...F}}[a.state]||F})(),R=S=>{const F=(S||"").toLowerCase(),I=s.getDataType(F);return I==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(qe,{className:"h-3 w-3"})}):I==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(rs,{className:"h-3 w-3"})}):I==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):I==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx($s,{className:"h-3 w-3"})}):I==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Us,{className:"h-3 w-3"})}):I==="geo"?e.jsx("div",{className:"bg-orange -100 flex size-6 shrink-0 items-center justify-center rounded-sm text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(oa,{className:"h-3 w-3"})}):I==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(zs,{className:"h-3 w-3"})}):null};return e.jsxs("div",{ref:x,style:g,...c?{}:u,...c?{}:m,className:s.cn("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",b&&"scale-95 opacity-50",!b&&"border",v.borderColor||"border-transparent",v.bgColor||"",v.hoverBorderColor,v.hoverBgColor||"hover:bg-muted",v.opacity,v.cursor,i&&"bg-accent border-accent-foreground/20",{"cursor-pointer":r||l,"cursor-grab active:cursor-grabbing":!c&&!r&&!l}),title:a==null?void 0:a.tooltip,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:w,children:[R(t.dataType),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${f?"whitespace-normal break-words":"truncate"}`,children:t.label||t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:e.jsx(Cn,{field:t,fieldState:a})})]})}),r&&!l&&A(t)&&e.jsx("div",{onClick:S=>S.stopPropagation(),children:e.jsx(Nn,{column:D})})]}),f&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(s.Card,{className:"",children:e.jsxs(s.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gs,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.label||t.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ba,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.name})]}),e.jsx(s.Badge,{variant:"outline",className:"mt-2 text-xs",children:t.dataType})]})})})]})}function wn({context:t="editor"}={}){var I,T,M,O;const[n,a]=k.useState(""),[r,l]=k.useState("all"),c=s.useEditorStore(E=>E.isDevMode),d=s.useEditorStore(E=>E.card.dataSource),o=s.useEditorStore(E=>E.card.config),i=s.useEditorStore(E=>E.card),{autoJoinMetadata:u}=s.useDashboardCardQuery(i),{columns:m=[],columnGroups:x=[],isLoading:h,error:p}=s.useColumns(),b=(d==null?void 0:d.mode)==="semanticDomain"?d.semanticDomainId:void 0,{data:f}=cs(b),j=[...(o==null?void 0:o.groupByColumns)||[],...(o==null?void 0:o.metricColumns)||[]];(T=(I=o==null?void 0:o.joinPlan)==null?void 0:I.baseEntity)==null||T.name,(O=(M=u==null?void 0:u.resolvedJoinPlan)==null?void 0:M.baseEntity)==null||O.name;const{handleShowSample:N,handleShowCount:C}=it(),L=m.filter(E=>E.name.toLowerCase().includes(n.toLowerCase())||E.dataType.toLowerCase().includes(n.toLowerCase())||E.label&&E.label.toLowerCase().includes(n.toLowerCase())||E.qualifiedEntityName&&E.qualifiedEntityName.toLowerCase().includes(n.toLowerCase())),A=E=>{if(E.dataType==="number"||E.dataType==="integer"||E.dataType==="float"||E.dataType==="decimal"||E.dataType==="currency")return"metrics";const P=s.getDataType(E.dataType);return["date","string","boolean"].includes(P)?"dimensions":P==="number"?"metrics":"dimensions"},D=(r==="all"?L:L.filter(E=>A(E)===r)).reduce((E,P)=>{const B=P.qualifiedEntityName||"Other Fields";return E[B]||(E[B]={label:s.toLabel(P.entityName),fields:[]}),E[B].fields.push(P),E},{}),y=Object.keys(D),v=L.filter(E=>A(E)==="dimensions").length,R=L.filter(E=>A(E)==="metrics").length,S=L.filter(E=>A(E)==="calculated").length,F=L.length>0;return h?e.jsx("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):p?e.jsxs("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:p.message||"Failed to load column data"})]}):!d||!d.selectedEntities||d.selectedEntities.length===0?e.jsx(s.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:t==="filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-full w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[c&&t!=="filter"&&m.length>0&&e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:h,onClick:N,size:"sm",variant:"secondary",className:"grow",children:[h?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(la,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:h,onClick:C,size:"sm",variant:"secondary",className:"grow",children:[h?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(pa,{className:"mr-2 size-4"}),"Count"]})]}),m.length>0&&e.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:n,onChange:E=>a(E.target.value)}),n&&e.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>a(""),type:"button",children:e.jsx(s.X,{className:"size-3.5"})})]}),F&&e.jsx(s.Tabs,{defaultValue:"all",value:r,onValueChange:E=>l(E),className:"mb-4",children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:L.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:v})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:R})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(zs,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:S})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:y,className:"space-y-2",children:Object.entries(D).map(([E,P])=>{const B=x.find(Y=>Y.entityName===E)||{entityName:E,label:P.label};return e.jsxs(s.AccordionItem,{value:E,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{title:B.label||B.entityName,className:"flex items-center gap-2",children:[e.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:B.label||B.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:P.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:P.fields.map(Y=>{const q=s.calculateFieldState(Y,{joinabilityMap:(f==null?void 0:f.joinabilityMap)||null,selectedFields:j,cardConfig:o,autoJoinMetadata:u});return e.jsx(Sn,{field:Y,context:t,fieldState:q},Y.id)})})})]},E)})}),Object.keys(D).length===0&&m.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:t==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),Object.keys(D).length===0&&m.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),e.jsx(s.ScrollBar,{orientation:"horizontal"}),e.jsx(s.ScrollBar,{orientation:"vertical"})]})]})}function dt({context:t="editor"}={}){return e.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",e.jsx(wn,{context:t})," "]})}function Dn({initialJoinPlan:t,availableDataSources:n}){const[a,r]=k.useState(t),[l,c]=k.useState(new Set),d=()=>{const D=a.joins.length>0?Math.max(...a.joins.map(y=>y.sequence))+1:1,g={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:D,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,g]}),c(new Set([...l,g.id]))},o=D=>{r({...a,joins:a.joins.filter(g=>g.id!==D)}),c(new Set([...l].filter(g=>g!==D)))},i=(D,g)=>{var S,F;const y=a.joins.find(I=>I.id===D);if(!y)return;const v={...y,...g},R=a.joins.map(I=>I.id===D?v:I);if((S=v.source)!=null&&S.name&&((F=v.target)!=null&&F.name)&&v.joinKeyGroups[0].keys.length===0){const I=n.find(E=>{var P;return E.name===((P=v.source)==null?void 0:P.name)}),T=n.find(E=>{var P;return E.name===((P=v.target)==null?void 0:P.name)}),M={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(T==null?void 0:T.name)||"",entityName:(T==null?void 0:T.name)||"",entityType:(T==null?void 0:T.type)||"table"},operator:"="},O=[...v.joinKeyGroups];O[0]={...O[0],keys:[M]},v.joinKeyGroups=O,R[R.findIndex(E=>E.id===D)]=v}r({...a,joins:R})};return{joinPlan:a,expandedJoins:l,setJoinPlan:r,addJoin:d,removeJoin:o,updateJoin:i,moveJoinUp:D=>{const g=a.joins.findIndex(y=>y.id===D);if(g>0){const y=[...a.joins],v={...y[g]},R={...y[g-1]};y[g]=R,y[g-1]=v,y.forEach((F,I)=>{F.sequence=I+1});const S={...a,joins:y};r(S)}},moveJoinDown:D=>{const g=a.joins.findIndex(y=>y.id===D);if(g<a.joins.length-1){const y=[...a.joins],v={...y[g]},R={...y[g+1]};y[g]=R,y[g+1]=v,y.forEach((F,I)=>{F.sequence=I+1});const S={...a,joins:y};r(S)}},toggleJoinExpansion:D=>{const g=new Set(l);g.has(D)?g.delete(D):g.add(D),c(g)},getAvailableSourceEntities:D=>{if(a.joins.length===0)return n;const g=a.joins.findIndex(v=>v.id===D);if(g===0)return n.filter(v=>v.name===a.baseEntity.name);const y=new Set;return a.baseEntity.name&&y.add(a.baseEntity.name),a.joins.slice(0,g).forEach(v=>{y.add(v.source.name),y.add(v.target.name)}),n.filter(v=>y.has(v.name))},getAvailableTargetEntities:D=>n.filter(g=>g.name!==D),addJoinKeyGroup:D=>{const g=a.joins.find(v=>v.id===D);if(!g)return;const y=[...g.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];i(D,{joinKeyGroups:y})},updateGroupOperator:(D,g,y)=>{const v=a.joins.find(S=>S.id===D);if(!v)return;const R=[...v.joinKeyGroups];R[g]={...R[g],operator:y},i(D,{joinKeyGroups:R})},removeJoinKeyGroup:(D,g)=>{const y=a.joins.find(R=>R.id===D);if(!y)return;const v=[...y.joinKeyGroups];v.splice(g,1),i(D,{joinKeyGroups:v})},addJoinKey:(D,g)=>{const y=a.joins.find(I=>I.id===D);if(!y)return;const v=n.find(I=>I.name===y.source.name),R=n.find(I=>I.name===y.target.name),S=[...y.joinKeyGroups],F={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(v==null?void 0:v.name)||"",entityName:(v==null?void 0:v.name)||"",entityType:(v==null?void 0:v.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(R==null?void 0:R.name)||"",entityName:(R==null?void 0:R.name)||"",entityType:(R==null?void 0:R.type)||"table"},operator:"="};S[g]={...S[g],keys:[...S[g].keys,F]},i(D,{joinKeyGroups:S})},updateJoinKey:(D,g,y,v,R)=>{const S=a.joins.find(O=>O.id===D);if(!S)return;const F=n.find(O=>O.name===S.source.name),I=n.find(O=>O.name===S.target.name),T=[...S.joinKeyGroups],M=T[g].keys[y];v==="sourceColumnName"&&F?T[g].keys[y]={...M,source:{...M.source,name:R}}:v==="targetColumnName"&&I?T[g].keys[y]={...M,target:{...M.target,name:R}}:v==="operator"&&(T[g].keys[y]={...M,operator:R}),i(D,{joinKeyGroups:T})},removeJoinKey:(D,g,y)=>{const v=a.joins.find(S=>S.id===D);if(!v)return;const R=[...v.joinKeyGroups];R[g].keys.splice(y,1),i(D,{joinKeyGroups:R})},generateSQLPreview:()=>{const D=[...a.joins].sort((v,R)=>v.sequence-R.sequence),g=a.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let y=`SELECT *
|
|
257
257
|
FROM ${g.name}`;return D.forEach(v=>{const R=n.find(I=>I.name===v.target.name);if(!R)return;const S=v.joinKeyGroups.filter(I=>I.keys&&I.keys.length>0).map(I=>{const T=I.keys.filter(M=>{var O,E,P,B;return((O=M.source)==null?void 0:O.name)&&((E=M.target)==null?void 0:E.name)&&((P=M.source)==null?void 0:P.entityName)&&((B=M.target)==null?void 0:B.entityName)}).map(M=>`${M.source.entityName}.${M.source.name} ${M.operator} ${M.target.entityName}.${M.target.name}`);return T.length>1?`(${T.join(` ${I.operator} `)})`:T[0]}).filter(Boolean),F=S.length>1?S.join(" OR "):S[0]||"condition_here";y+=`
|
|
258
258
|
${v.joinType} JOIN ${R.name}
|
|
259
259
|
ON ${F}`}),y},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(v=>!v.source.name||!v.target.name)||a.joins.some(v=>v.joinKeyGroups.some(R=>R.keys.length===0))||a.joins.some(v=>v.joinKeyGroups.some(R=>R.keys.some(S=>!S.source.name||!S.target.name||!S.operator))))}}function Tn({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:l}){const{setCardConfig:c}=s.useEditorActions();s.useEditorStore(S=>S.card.config);const{columnGroups:d}=s.useColumns(),{joinPlan:o,expandedJoins:i,setJoinPlan:u,addJoin:m,removeJoin:x,updateJoin:h,moveJoinUp:p,moveJoinDown:b,toggleJoinExpansion:f,getAvailableSourceEntities:j,getAvailableTargetEntities:N,addJoinKeyGroup:C,updateGroupOperator:L,removeJoinKeyGroup:A,addJoinKey:w,updateJoinKey:D,removeJoinKey:g,generateSQLPreview:y,isValidConfiguration:v}=Dn({initialJoinPlan:t,availableDataSources:n}),R=S=>{const F=d.find(I=>I.entityName===S);return(F==null?void 0:F.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:o.baseEntity.name,onValueChange:S=>{const F=n.find(I=>I.name===S);u({...o,baseEntity:{connectionId:(F==null?void 0:F.connectionId)||"",connectionType:(F==null?void 0:F.connectionType)||"none",type:(F==null?void 0:F.type)||"table",name:S,database:F==null?void 0:F.database,schema:F==null?void 0:F.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:n.map(S=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:S.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:S.type}),S.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},S.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:y()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",o.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:m,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),o.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:o.joins.map(S=>{const F=n.find(M=>M.name===S.source.name),I=n.find(M=>M.name===S.target.name),T=i.has(S.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{children:S.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",S.sequence,F&&I&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",F.name," → ",I.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>p(S.id),disabled:S.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>b(S.id),disabled:S.sequence===o.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>f(S.id),children:T?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:()=>x(S.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),T&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:S.source.name,onValueChange:M=>{const O=n.find(E=>E.name===M);h(S.id,{source:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:M,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 source..."})}),e.jsx(s.SelectContent,{children:j(S.id).map(M=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:M.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:M.type}),M.name]})},M.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:S.joinType,onValueChange:M=>h(S.id,{joinType:M}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:S.target.name,onValueChange:M=>{const O=n.find(E=>E.name===M);h(S.id,{target:{connectionId:(O==null?void 0:O.connectionId)||"",connectionType:(O==null?void 0:O.connectionType)||"none",type:(O==null?void 0:O.type)||"table",name:M,database:O==null?void 0:O.database,schema:O==null?void 0:O.schema}})},disabled:!S.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:S.source.name?N(S.source.name).map(M=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:M.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:M.type}),M.name,M.name===S.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},M.name)):[]})]})]})]}),S.source.name&&S.target.name&&F&&I&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>C(S.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),S.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:S.joinKeyGroups.map((M,O)=>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 ",O+1]}),O>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:M.operator,onValueChange:E=>L(S.id,O,E),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:()=>A(S.id,O),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[M.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:M.keys.map((E,P)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[P>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:M.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:E.source.name,onValueChange:B=>D(S.id,O,P,"sourceColumnName",B),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:R(S.source.name).map(B=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:B.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:B.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:B.dataType})]})},B.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:E.operator,onValueChange:B=>D(S.id,O,P,"operator",B),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:E.target.name,onValueChange:B=>D(S.id,O,P,"targetColumnName",B),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:R(S.target.name).map(B=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:B.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:B.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:B.dataType})]})},B.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>g(S.id,O,P),children:e.jsx(s.X,{className:"size-3.5"})})]},E.id||P))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>w(S.id,O),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},M.id))})]})]})]},S.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>a(o),disabled:!v(),children:"Save"})]})]})}function ns({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:l,onRemove:c,onSave:d,onCancel:o}){return e.jsxs(s.Dialog,{open:n,onOpenChange:a,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(Tn,{joinPlan:r,availableDataSources:l,onSave:d,onCancel:o,onRemove:c})]}),t]})}function kn({joins:t,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const l=[...t].sort((d,o)=>d.sequence-o.sequence),c=a.find(d=>d.name===n);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:c==null?void 0:c.type}),e.jsx("span",{className:"text-xs font-medium",children:c==null?void 0:c.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(d=>{const o=a.find(i=>i.name===d.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:d.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:o==null?void 0:o.type}),e.jsx("span",{className:"text-xs font-medium",children:o==null?void 0:o.name})]})]},d.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((l,c)=>l.sequence-c.sequence).map((l,c)=>{const d=a.find(i=>i.name===l.source.name),o=a.find(i=>i.name===l.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:c+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[d==null?void 0:d.name," → ",o==null?void 0:o.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[l.joinKeyGroups.reduce((i,u)=>i+u.keys.length,0)," ","condition",l.joinKeyGroups.reduce((i,u)=>i+u.keys.length,0)>1?"s":""]})]},l.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function En(){var x,h;const t=s.useEditorStore(p=>p.card),{autoJoinMetadata:n}=s.useDashboardCardQuery(t),a=s.useEditorStore(p=>p.actions.updateCardConfig),r=((x=t==null?void 0:t.config)==null?void 0:x.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[l,c]=k.useState(!1),d=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],o=p=>{a(t.id,{...t==null?void 0:t.config,joinPlan:p}),c(!1)},i=()=>{a(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},u=()=>{c(!1)},m=()=>{const p=[...r.joins].sort((j,N)=>j.sequence-N.sequence),b=r.baseEntity;if(!b.name)return"SELECT * FROM table -- Please select a base entity";let f=`SELECT *
|