react-semaphor 0.0.6461 → 0.0.6462
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-DZ_09XeX.js → dashboard-plus-Bl5i7UH3.js} +1 -1
- package/dist/chunks/{dashboard-plus-BuqxKXTF.js → dashboard-plus-DG8evDKF.js} +436 -436
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +1 -1
- package/package.json +1 -1
|
@@ -313,7 +313,7 @@
|
|
|
313
313
|
*
|
|
314
314
|
* This source code is licensed under the ISC license.
|
|
315
315
|
* See the LICENSE file in the root directory of this source tree.
|
|
316
|
-
*/const Ya=s.createLucideIcon("View",[["path",{d:"M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2",key:"mrq65r"}],["path",{d:"M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2",key:"be3xqs"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);function $a(){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(Va,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(Aa,{strokeWidth:1.5,className:"absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),e.jsx("span",{className:"sr-only",children:"Toggle theme"})]})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuItem,{onClick:()=>{t("light"),n("light")},children:"Light"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("dark"),n("dark")},children:"Dark"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("system"),n("system")},children:"System"})]})]})}function ss(t){var n;return{...t,sheets:(n=t==null?void 0:t.sheets)==null?void 0:n.map(a=>{var r;return{...a,frames:(r=a.frames)==null?void 0:r.map(l=>{var o;return{...l,cards:(o=l.cards)==null?void 0:o.map(c=>rt(c))}})}})}}function rt(t){return{...t,customCfg:qa(t.customCfg),data:[]}}function qa(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 Ha(t,n,a,r,l){if(!l)return null;const o=JSON.stringify(a),c=`${t}/v1/lens`;return await s.postRequest(c,l,{name:n,template:o,filterValues:r,operation:"create"})}async function vs(t,n,a){if(!a)return null;const{id:r,template:l,filterValues:o,isDefault:c,shared:i}=n,d=`${t}/v1/lens`;return await s.postRequest(d,a,{lensId:r,template:l,filterValues:o,isDefault:c,shared:i,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 Ka(){const[t,n]=M.useState(""),[a,r]=M.useState(!1),l=s.useDashboardStore(j=>j.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=M.useState(!1),[u,m]=M.useState(!1),h=s.useDashboardStore(j=>j.dashboard),x=s.useDashboardStore(j=>j.filterValues),{authToken:g,tokenProps:b}=s.useSemaphorContext();async function p(){d(!0);const j=ss(h),f=await Ha(b.apiServiceUrl,t,j,x,g==null?void 0:g.accessToken);f&&(o([...l||[],f]),c(f.id),m(!1)),d(!1)}return e.jsxs(s.Dialog,{open:u,onOpenChange:m,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange: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:p,disabled:i,children:i?"Creating...":"Add"})})]})]})}function Qa(){const[t,n]=M.useState(!1),a=s.useDashboardStore(h=>h.lenses),r=s.useDashboardStore(h=>h.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c,tokenProps:i}=s.useSemaphorContext();async function d(h){o(h)}async function u(h){if(await Wa(i.apiServiceUrl,h,c==null?void 0:c.accessToken)){const g=a==null?void 0:a.filter(b=>b.id!==h);l(g||[]),o("original")}}async function m(h){const x=a==null?void 0:a.map(p=>p.id===h.id?{...p,isDefault:!h.isDefault}:{...p,isDefault:!1});l(x||[]);const g={...h,isDefault:!h.isDefault};await vs(i.apiServiceUrl,g,c==null?void 0:c.accessToken);const b=a==null?void 0:a.find(p=>p.isDefault);if(b&&b.id!==h.id){const p={...b,isDefault:!1};await vs(i.apiServiceUrl,p,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:n,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(va,{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:d,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),a==null?void 0:a.map(h=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:h.id,children:[e.jsx("p",{children:h.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:x=>{x.preventDefault(),m(h)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!h.isDefault,"text-green-500":h.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:x=>{x.preventDefault(),u(h.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},h.id))]})]})]})}function Ja({iconClassName:t}){const[n,a]=M.useState(!1),[r,l]=M.useState(""),[o,c]=M.useState(!1),i=s.useDashboardStore(h=>h.isDownloadingPdf),{tokenProps:d}=s.useSemaphorContext();async function u(){const h=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl),s.ue.dismiss(h),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(x){s.ue.dismiss(h),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",x)}}async function m(){if(!r)return;a(!1),l(""),c(!1);const h=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl,r),s.ue.dismiss(h),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(x){s.ue.dismiss(h),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",x)}}return e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:i,children:e.jsx(s.Download,{className:s.cn("size-4",t)})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsxs(s.DropdownMenuItem,{onClick:u,children:[e.jsx(s.File,{className:"mr-2 h-4 w-4"}),"Download PDF"]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>a(!0),children:[e.jsx(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:o?"text":"password",value:r,onChange:h=>l(h.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:h=>{h.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:()=>c(!o),children:o?e.jsx(s.EyeOff,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(s.Eye,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:m,disabled:!r,children:"Download"})]})]})})]})}function lt({triggerButtonClassName:t}){const[n,a]=M.useState(!1),r=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.id}),l=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.title}),o=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.sheets}),c=s.useDashboardStore(i=>i.selectedSheetId);return o==null||o.find(i=>i.id===c),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 ts({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 Oe({currentRole:t,onRoleChange:n,roleOptions:a,disabled:r=!1,className:l="",allowDropdown:o=!0}){var d;const c=((d=a.find(u=>u.value===t))==null?void 0:d.label)||t,i=a.filter(u=>u.value!==t);return o?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${l}`,children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.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:c})}function ot({selectedUsers:t,selectedUserObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(o=>a(o.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.map(o=>{const c=t.find(d=>d.id===o.id),i=l(o.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[o.name,e.jsx(Oe,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(o.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>a(o.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},o.id)})}),e.jsx(s.Separator,{})]})}function it({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 ct({usersToUpdate:t,allUsers:n,onRemove:a,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),o=i=>{const d=n.find(u=>u.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=l.find(u=>u.value===i);return(d==null?void 0:d.label)||i};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(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(i=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:o(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>a(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function dt(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,l=M.useRef(null);return M.useEffect(()=>{const o=c=>{const i=c.target;l.current&&l.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,a,r]),l}function ye(t,n){var a;return((a=n.find(r=>r.value===t))==null?void 0:a.label)||t}function Xa(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function ut(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function Za(t,n,a){const r=ut(t),l=(a==null?void 0:a.type)||"organization";if(!(!n||!n.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in n.shares)return(n.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function en({user:t}){return ut(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 sn({user:t,userShare:n,usersToUpdate:a,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(n!=null&&n.role))return null;const c=Xa((r==null?void 0:r.type)||""),i=a.some(h=>h.id===t.id),d=a.find(h=>h.id===t.id),u=d?d.newRole:n==null?void 0:n.role,m=l(t.type);return n?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(Oe,{currentRole:u,onRoleChange:h=>{o(t.id,n.role,h)},roleOptions:m,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:ye(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function tn({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(Be,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function an({isUserRemoving:t,isSelected:n,hasAccess:a,isRemoving:r,isSharing:l}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),n&&!a&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:l?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Sharing..."]}):"Will share"})]})}function nn({existingShares:t,allUsers:n,getRoleOptions:a,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],d=c.specificTenantUsers||[],u=c.orgWide||[],m=c.orgUsersOnly||[],h=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((x,g)=>{var f,N;const b=((f=n.find(T=>T.id===x.orgUserId))==null?void 0:f.name)||"Unknown User",p=((N=n.find(T=>T.id===x.orgUserId))==null?void 0:N.type)||"",j=ye(x.role,a(p));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})]},g)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),d.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-green-600",children:["Specific Tenant Users (",d.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[d.slice(0,3).map((x,g)=>{var f,N;const b=((f=n.find(T=>T.id===x.tenantUserId))==null?void 0:f.name)||"Unknown User",p=((N=n.find(T=>T.id===x.tenantUserId))==null?void 0:N.type)||"",j=ye(x.role,a(p));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})]},g)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-purple-600",children:"All Org Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:u.map((x,g)=>{const b=ye(x.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})]},g)})})]}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-orange-600",children:"Org Users Only"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:m.map((x,g)=>{const b=ye(x.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})]},g)})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:h.map((x,g)=>{const b=ye(x.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})]},g)})})]}),!i.length&&!d.length&&!u.length&&!m.length&&!h.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],i=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",c.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[c.slice(0,3).map((d,u)=>{var g,b;const m=((g=n.find(p=>p.id===d.tenantUserId))==null?void 0:g.name)||"Unknown User",h=((b=n.find(p=>p.id===d.tenantUserId))==null?void 0:b.type)||"",x=ye(d.role,a(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:x})]},u)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:i.map((d,u)=>{const m=ye(d.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)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const o=t.shares.specificTenantUsers||[],c=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",o.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[o.slice(0,3).map((i,d)=>{var x,g;const u=((x=n.find(b=>b.id===i.tenantUserId))==null?void 0:x.name)||"Unknown User",m=((g=n.find(b=>b.id===i.tenantUserId))==null?void 0:g.type)||"",h=ye(i.role,a(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),o.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,d)=>{const u=ye(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:u})]},d)})})]}),!o.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function rn({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 ln({user:t,userShare:n,isUserRemoving:a,hasAccess:r,hasAccessFromAPI:l,isSelected:o,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:h,handleUpdateAccess:x,handleUserRoleChange:g}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!a?"border border-green-200 bg-green-50":a?"border border-red-200 bg-red-50":o?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:l?!a:o,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{l?a?m(t.id):h(t.id):m(t.id)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:t.name}),e.jsx(en,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!a?e.jsx(Oe,{currentRole:n==null?void 0:n.role,onRoleChange:b=>x(t.id,n.role,b),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(sn,{user:t,userShare:n,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:x}),o&&!l&&e.jsx("div",{onClick:b=>b.stopPropagation(),children:e.jsx(Oe,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:b=>g(t.id,b),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(tn,{hasAccess:r,isUserRemoving:a,isSelected:o,hasAccessFromAPI:l}),e.jsx(an,{isUserRemoving:a,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function mt({existingShares:t,isInitialLoading:n,isSearching:a,getRoleOptions:r,allUsers:l=[],currentUser:o,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),x=s.useShareUsersToUpdate(),g=s.useShareSearchQuery(),b=s.useShareManagementActions(),p=c||(w=>{const C=m.some(k=>k.id===w),v=h.includes(w);C?b.removeSelectedUser(w):v?b.removeUserFromRemove(w):b.addSelectedUser({id:w,role:"VIEWER"})}),j=i||b.updateSelectedUserRole,f=d||b.addUserToRemove,N=u||((w,C,v)=>{b.addUserToUpdate({id:w,currentRole:C,newRole:v})}),T=l,I=h;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["All Users (",(T??[]).length,")"]}),e.jsx(s.TooltipProvider,{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(nn,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:o})})]})})]}),(T==null?void 0:T.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===T.length?b.setSelectedUsers([]):b.setSelectedUsers(T.map(w=>({id:w.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:m.length===T.length?"Deselect all":"Select all"})]}),e.jsxs("div",{className:"max-h-60 space-y-1 overflow-y-auto rounded-md border p-2",children:[e.jsx(rn,{isInitialLoading:n,isSearching:a,searchQuery:g,availableUsers:T||[]}),!n&&!a&&(T==null?void 0:T.length)>0&&T.map(w=>{const C=t?Za(w,t,o):void 0,v=I.includes(w.id),k=!!C,y=k&&!v,O=m.some(D=>D.id===w.id),E=m.find(D=>D.id===w.id),P=r(w.type);return e.jsx(ln,{user:w,userShare:C,isUserRemoving:v,hasAccess:y,hasAccessFromAPI:k,isSelected:O,selectedUser:E,roleOptions:P,currentUser:o,usersToUpdate:x,handleUserToggle:p,handleRemoveAccess:f,handleUpdateAccess:N,handleUserRoleChange:j},w.id)})]})]})}function Ss({shareType:t,onShareTypeChange:n,currentUser:a,options:r}){const l=(a==null?void 0:a.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:n,className:`grid grid-cols-${r.length} gap-4`,children:r.map(o=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:o.value,id:o.value,className:"peer sr-only",disabled:o.disabled}),e.jsxs(s.Label,{htmlFor:o.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${o.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[o.icon||e.jsx(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:o.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o.description})]})]})]},o.value))}),!l&&r.some(o=>o.value==="all_users")&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only admins, authors, power users, and super admins can share with all users."})]})}const be=()=>[{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 on({currentUser:t,currentShare:n,isSharing:a,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:o=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),u=be().filter(N=>N.value==="VIEWER"||N.value==="EDITOR"||N.value==="CONTRIBUTOR"),m=n.role!=="NONE"?n.role:"NONE",h=l?l.newRole:m,x=n.role!=="NONE"&&!o&&(!l||l.newRole===m),g=l!==null&&l.newRole!==m,b=o,p=m==="NONE"||!m,j=N=>{switch(N){case"VIEWER":return e.jsx(s.Eye,{className:"h-4 w-4"});case"EDITOR":return e.jsx(s.SquarePen,{className:"h-4 w-4"});case"CONTRIBUTOR":return e.jsx(Pa,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},f=N=>{r(m,N)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",g&&!b&&!p?"border-orange-300 bg-orange-50":x?"border-green-300 bg-green-50":b||p?"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"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="specificOrgUsers"?"Org":"Tenant"," ","Users",x&&e.jsx(s.Badge,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),g&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(b||p)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:b||p?"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(N=>e.jsxs(s.Button,{variant:h===N.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>f(N.value),disabled:a||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[j(N.value),e.jsx("span",{className:"font-medium",children:N.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:N.description})]},N.value))})]})})]})})}function ht({currentUser:t,currentShare:n,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:o,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const u=p=>p==="OWNER"?"CONTRIBUTOR":p,h=n?{role:u(n.role)}:{role:"NONE"},x=i?{currentRole:u(i.currentRole),newRole:u(i.newRole)}:null,g=(p,j)=>{o(p,j)},b=()=>{c()};return e.jsx(on,{currentUser:t,currentShare:h,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:g,onRemoveAccess:b,allUsersToUpdate:x,allUsersToRemove:d})}function _e(t){const{debouncedSearchQuery:n,resourceId:a,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:o}=t,c=M.useMemo(()=>({search:n,active:!0,...l?{type:l}:{},...l==="tenant"&&o?{tenantId:o}:{}}),[n,l,o]),{users:i,isLoading:d,isError:u}=s.useUnifiedUsers(c),m=s.useResourceShares(r,a);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function cn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var J,Z;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),x=s.useShareSelectedUsers(),g=s.useShareUsersToRemove(),b=s.useShareUsersToUpdate(),p=s.useShareCurrentMode(),j=s.useShareOrgWideRole(),f=s.useShareManagementActions(),[N,T]=M.useState("specific_users"),I=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},w=()=>{if(i==="tenant"&&d)return d},{allUsers:C,existingShares:v,isLoadingUsers:k}=_e({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:I(),tenantId:w()});M.useEffect(()=>{f.setCurrentContext("org-tab"),f.setCurrentMode(N==="all_users"?"allOrgUsers":"specificOrgUsers")},[f,N]);const y=W=>{var G,se;const H=W;if(T(H),r==null||r(H),f.setCurrentContext("org-tab"),H==="specific_users")f.setCurrentMode("specificOrgUsers");else if(H==="all_users"){f.setCurrentMode("allOrgUsers");const _=(se=(G=v==null?void 0:v.shares)==null?void 0:G.orgUsersOnly)==null?void 0:se[0];_&&_.role!==void 0&&f.setOrgWideRole(_.role)}},O=C.filter(W=>W.name.toLowerCase().includes(u.toLowerCase())||W.email.toLowerCase().includes(u.toLowerCase())),E=C.filter(W=>x.some(H=>H.id===W.id)),P=W=>{var _,U;const H=x.some(ee=>ee.id===W),G=g.includes(W),se=(U=(_=v==null?void 0:v.shares)==null?void 0:_.specificOrgUsers)==null?void 0:U.some(ee=>ee.orgUserId===W);H?f.removeSelectedUser(W):G?f.removeUserFromRemove(W):se||f.addSelectedUser({id:W,role:"VIEWER"})},D=(W,H)=>{f.updateSelectedUserRole(W,H)},S=W=>{f.addUserToRemove(W),f.removeSelectedUser(W)},L=W=>{f.removeUserFromRemove(W)},F=W=>{f.removeUserFromUpdate(W)},R=(W,H)=>{f.setOrgWideRole(H)},A=()=>{f.setOrgWideRole((z==null?void 0:z.role)||"NONE")},z=(Z=(J=v==null?void 0:v.shares)==null?void 0:J.orgUsersOnly)==null?void 0:Z[0];M.useEffect(()=>{N==="all_users"&&z&&z.role!==void 0&&f.setOrgWideRole(z.role)},[N,z,f]);const q=k,V=!1;return a?e.jsxs(e.Fragment,{children:[e.jsx(Ss,{shareType:N,onShareTypeChange:y,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??"")}]}),N==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(ts,{value:u,onChange:m}),e.jsx(ot,{selectedUsers:x,selectedUserObjects:E,onRemove:P,onRoleChange:D,getRoleOptions:be}),e.jsx(it,{usersToRemove:g,allUsers:O,onRemove:L}),e.jsx(ct,{usersToUpdate:b,allUsers:O,onRemove:F,getRoleOptions:be}),e.jsx(mt,{existingShares:v,isInitialLoading:q,isSearching:V,resource:t,onShare:()=>{},getRoleOptions:be,allUsers:O,currentUser:a,handleUserToggle:P,handleUserRoleChange:D,handleRemoveAccess:S,handleUpdateAccess:(W,H,G)=>{f.addUserToUpdate({id:W,currentRole:H,newRole:G})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(ht,{currentUser:a,currentShare:z,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:R,onRemoveAccess:A,allUsersToUpdate:p==="allOrgUsers"&&j!==((z==null?void 0:z.role)||"NONE")?{currentRole:(z==null?void 0:z.role)||"NONE",newRole:j}:null,allUsersToRemove:p==="allOrgUsers"&&(z==null?void 0:z.role)===void 0})})]}):null}function dn(t){switch(t){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function un(t){switch(t){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function xt({groups:t,existingGroupShares:n,isLoading:a,resource:r,getRoleOptions:l,currentUser:o,handleGroupToggle:c,handleGroupRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),x=s.useShareGroupsToUpdate(),g=s.useShareManagementActions(),b=l(o==null?void 0:o.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(p=>{const j=n==null?void 0:n.find(v=>v.groupId===p.id),f=m.some(v=>v.id===p.id),N=h.includes(p.id),T=x.find(v=>v.id===p.id),I=!!j&&!N;let C=(j==null?void 0:j.role)||"VIEWER";if(f){const v=m.find(k=>k.id===p.id);C=(v==null?void 0:v.role)||"VIEWER"}else T&&(C=T.newRole);return e.jsxs("div",{className:s.cn("flex items-center justify-between rounded-lg p-2 transition-colors",I&&!N?"border border-green-200 bg-green-50":N?"border border-red-200 bg-red-50":f?"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-${p.id}`,checked:I?!N:f,disabled:!1,onCheckedChange:()=>{I?N?g.removeGroupFromRemove(p.id):d==null||d(p.id):c==null||c(p.id)}}),e.jsxs("label",{htmlFor:`group-${p.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:p.name}),p.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:[p.memberCount," members"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:s.cn("text-xs",un(p.type)),children:dn(p.type)}),p.type==="TENANT_GROUP"&&p.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",p.tenantName]})]}),p.description&&e.jsx("span",{className:"text-xs text-muted-foreground",children:p.description})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[I&&!N?e.jsx(Oe,{currentRole:C,onRoleChange:v=>{j&&v!==j.role&&(u==null||u(p.id,j.role,v))},roleOptions:b,disabled:!1,allowDropdown:!0,className:T?"border-orange-300 bg-orange-100":""}):f&&!I&&e.jsx(Oe,{currentRole:C,onRoleChange:v=>i==null?void 0:i(p.id,v),roleOptions:b,disabled:!1}),I&&!N&&!T&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>d==null?void 0:d(p.id),children:e.jsx(s.X,{className:"h-4 w-4"})}),N&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromRemove(p.id),children:"Undo"}),T&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromUpdate(p.id),children:"Cancel"})]})]},p.id)})})]})}function pt({selectedGroups:t,groupObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){if(t.length===0)return null;const o=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(c=>{const i=n.find(d=>d.id===c.id);return i?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:[i.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:i.name}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[i.memberCount," members"]}),i.type==="TENANT_GROUP"&&i.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",i.tenantName]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oe,{currentRole:c.role,onRoleChange:d=>r(c.id,d),roleOptions:o}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>a(c.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})]},c.id):null})})]})}function Us({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var fe;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),x=s.useShareUsersToUpdate(),g=s.useShareSelectedGroups(),b=s.useShareGroupsToRemove(),p=s.useShareGroupsToUpdate(),j=s.useShareCurrentMode(),f=s.useShareTenantWideRole(),N=s.useShareAllTenantsRole(),T=s.useShareSelectedTenant(),I=s.useShareManagementActions(),{data:w,isLoading:C}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"}),{groups:v,isLoading:k}=s.useShareableGroups("tenant",(a==null?void 0:a.tenantId)||T),[y,O]=M.useState((a==null?void 0:a.type)==="organization"?"all_tenants":"specific_tenant_users");M.useEffect(()=>{(a==null?void 0:a.type)==="tenant"?(I.setCurrentContext("tenant-dialog"),I.setCurrentMode("specificTenantUsers")):(I.setCurrentContext("tenant-tab"),I.setCurrentMode("allTenants"))},[I,a==null?void 0:a.type]);const E=Y=>{var X,$,te,ie;O(Y);let Q;if(Y==="specific_tenant_users"?Q="specific_users":Y==="all_tenant_users"||Y==="all_tenants"?Q="all_users":Y==="groups"?Q="groups":Q="specific_users",r==null||r(Q),Y==="groups"?(I.setCurrentContext("group-share"),I.setCurrentMode("specificGroups")):(a==null?void 0:a.type)==="tenant"?(I.setCurrentContext("tenant-dialog"),Y==="specific_tenant_users"?I.setCurrentMode("specificTenantUsers"):Y==="all_tenant_users"&&(I.setCurrentMode("allTenantUsers"),a!=null&&a.tenantId&&I.setSelectedTenant(a.tenantId))):(I.setCurrentContext("tenant-tab"),Y==="specific_tenant_users"?I.setCurrentMode("specificTenantUsers"):Y==="all_tenant_users"?I.setCurrentMode("allTenantUsers"):Y==="all_tenants"&&I.setCurrentMode("allTenants")),Y==="all_tenant_users"){const ce=($=(X=S==null?void 0:S.shares)==null?void 0:X.tenantWide)==null?void 0:$[0];ce&&ce.role!==void 0&&I.setTenantWideRole(ce.role)}else if(Y==="all_tenants"){const ce=(ie=(te=S==null?void 0:S.shares)==null?void 0:te.allTenantsOnly)==null?void 0:ie[0];ce&&ce.role!==void 0&&I.setAllTenantsRole(ce.role)}},P=Y=>{I.setSelectedTenant(Y)},{allUsers:D,existingShares:S,isLoadingUsers:L,isErrorLoadingUsers:F,isLoadingShares:R,isErrorLoadingShares:A}=_e({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant",tenantId:(a==null?void 0:a.type)==="tenant"?a.tenantId:T}),z=Y=>{var te,ie;const Q=m.some(ce=>ce.id===Y),X=h.includes(Y),$=(ie=(te=S==null?void 0:S.shares)==null?void 0:te.specificTenantUsers)==null?void 0:ie.some(ce=>ce.tenantUserId===Y);Q?I.removeSelectedUser(Y):X?I.removeUserFromRemove(Y):$||I.addSelectedUser({id:Y,role:"VIEWER"})},q=(Y,Q)=>{I.updateSelectedUserRole(Y,Q)},V=Y=>{I.addUserToRemove(Y),I.removeSelectedUser(Y)},J=Y=>{I.removeUserFromRemove(Y)},Z=Y=>{I.removeUserFromUpdate(Y)},W=(Y,Q,X)=>{I.addUserToUpdate({id:Y,currentRole:Q,newRole:X})},H=(Y,Q)=>{y==="all_tenant_users"?I.setTenantWideRole(Q):y==="all_tenants"&&I.setAllTenantsRole(Q)},G=()=>{y==="all_tenant_users"?I.setTenantWideRole("VIEWER"):y==="all_tenants"&&I.setAllTenantsRole("VIEWER")},_=(()=>{var Y,Q,X,$;return j==="allTenants"?(Q=(Y=S==null?void 0:S.shares)==null?void 0:Y.allTenantsOnly)==null?void 0:Q[0]:j==="allTenantUsers"?($=(X=S==null?void 0:S.shares)==null?void 0:X.tenantWide)==null?void 0:$[0]:null})();M.useEffect(()=>{var Y,Q,X,$;if(y==="all_tenant_users"){const te=(Q=(Y=S==null?void 0:S.shares)==null?void 0:Y.tenantWide)==null?void 0:Q[0];te&&te.role!==void 0&&I.setTenantWideRole(te.role)}else if(y==="all_tenants"){const te=($=(X=S==null?void 0:S.shares)==null?void 0:X.allTenantsOnly)==null?void 0:$[0];te&&te.role!==void 0&&I.setAllTenantsRole(te.role)}},[y,S,I]);const U=D.filter(Y=>m.some(Q=>Q.id===Y.id)),ee=Y=>{const Q=g.some(te=>te.id===Y),X=b.includes(Y),$=re==null?void 0:re.some(te=>te.groupId===Y);Q?I.removeSelectedGroup(Y):X?I.removeGroupFromRemove(Y):$||I.addSelectedGroup({id:Y,role:"VIEWER"})},ne=(Y,Q)=>{I.updateSelectedGroupRole(Y,Q)},oe=Y=>{I.addGroupToRemove(Y),I.removeSelectedGroup(Y)},B=(Y,Q,X)=>{I.addGroupToUpdate({id:Y,currentRole:Q,newRole:X})},ae=v.filter(Y=>g.some(Q=>Q.id===Y.id)),le=M.useMemo(()=>y!=="groups"?[]:v.filter(Y=>Y.type!=="TENANT_GROUP"?!1:Y.name.toLowerCase().includes(i.toLowerCase())||Y.description&&Y.description.toLowerCase().includes(i.toLowerCase())),[v,y,i]),re=M.useMemo(()=>{var Q,X;const Y=((Q=S==null?void 0:S.shares)==null?void 0:Q.specificGroups)||((X=S==null?void 0:S.shares)==null?void 0:X.groups)||[];return!Y||Y.length===0?[]:Y.filter($=>{const te=v.find(ie=>ie.id===$.groupId);return(te==null?void 0:te.type)==="TENANT_GROUP"})},[S,v]),xe=L||R||y==="groups"&&k,pe=F||A,me=()=>(a==null?void 0:a.type)==="tenant"||y==="all_tenants"||y==="groups"?!0:T&&(y==="specific_tenant_users"||y==="all_tenant_users");return e.jsxs(e.Fragment,{children:[pe&&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"})]})}),!pe&&a&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(Ss,{shareType:y,onShareTypeChange:E,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(zs,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"all_tenant_users",label:"Specific Tenant",description:"Share with all users of a specific tenant",icon:e.jsx(s.House,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"specific_tenant_users",label:"Specific Tenant User",description:"Share with users of a specific tenant",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(a==null?void 0:a.type)==="organization"&&(y==="specific_tenant_users"||y==="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:T||"",onValueChange:P,disabled:C,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:C?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(fe=w==null?void 0:w.tenants)==null?void 0:fe.map(Y=>e.jsx(s.SelectItem,{value:Y.id,children:Y.name},Y.id))})]})]}),me()?e.jsx(e.Fragment,{children:y==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(ts,{value:i,onChange:u}),e.jsx(ot,{selectedUsers:m,selectedUserObjects:U,onRemove:Y=>z(Y),onRoleChange:q,getRoleOptions:be}),e.jsx(it,{usersToRemove:h,allUsers:D,onRemove:J}),e.jsx(ct,{usersToUpdate:x,allUsers:D,onRemove:Z,getRoleOptions:be}),e.jsx(mt,{existingShares:S,isInitialLoading:!!xe,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:be,allUsers:D,currentUser:a,handleUserToggle:z,handleUserRoleChange:q,handleRemoveAccess:V,handleUpdateAccess:W})]}):y==="groups"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(ts,{value:i,onChange:u,placeholder:"Search groups..."}),e.jsx(pt,{selectedGroups:g,groupObjects:ae,onRemove:ee,onRoleChange:ne,getRoleOptions:be}),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"})]}),p.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 (",p.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(xt,{groups:le,existingGroupShares:re,isLoading:k,resource:t,getRoleOptions:be,currentUser:a,handleGroupToggle:ee,handleGroupRoleChange:ne,handleRemoveAccess:oe,handleUpdateAccess:B})]}):y==="all_tenant_users"||y==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(ht,{currentUser:a,currentShare:_,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:H,onRemoveAccess:G,allUsersToUpdate:j==="allTenantUsers"&&((_==null?void 0:_.role)===void 0||f!==_.role)||j==="allTenants"&&((_==null?void 0:_.role)===void 0||N!==_.role)?{currentRole:(_==null?void 0:_.role)||"VIEWER",newRole:j==="allTenantUsers"?f:N}:null,allUsersToRemove:j==="allTenantUsers"&&(_==null?void 0:_.role)===void 0||j==="allTenants"&&(_==null?void 0:_.role)===void 0})}):null}):(a==null?void 0:a.type)==="organization"&&(y==="specific_tenant_users"||y==="all_tenant_users")&&e.jsx("div",{className:"mt-6 flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(zs,{className:"mx-auto mb-2 h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant to continue"})]})})]})]})}function mn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var F,R;const{searchQuery:i,setSearchQuery:d}=s.useShareSearchWithDebounce(),u=s.useShareSelectedGroups(),m=s.useShareGroupsToRemove(),h=s.useShareGroupsToUpdate(),x=s.useShareManagementActions(),[g,b]=M.useState("org_groups"),[p,j]=M.useState(""),{data:f,isLoading:N}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"&&g==="tenant_groups"}),T=Array.isArray(f)?f:(f==null?void 0:f.tenants)||[],I=()=>{if((a==null?void 0:a.type)==="organization")return"organization";if((a==null?void 0:a.type)==="tenant")return"tenant"},{groups:w,isLoading:C}=s.useShareableGroups(I(),g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"?p:a==null?void 0:a.tenantId),{existingShares:v}=_e({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n}),k=w.filter(A=>g==="org_groups"&&A.type!=="ORG_GROUP"||g==="tenant_groups"&&A.type!=="TENANT_GROUP"||g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&(!p||A.tenantId&&A.tenantId!==p)?!1:A.name.toLowerCase().includes(i.toLowerCase())||A.description&&A.description.toLowerCase().includes(i.toLowerCase())),y=((F=v==null?void 0:v.shares)==null?void 0:F.specificGroups)||((R=v==null?void 0:v.shares)==null?void 0:R.groups)||[];M.useEffect(()=>{x.setCurrentContext("group-share"),x.setCurrentMode("specificGroups")},[x]);const O=A=>{const z=A;b(z),z==="org_groups"&&j(""),r==null||r(z==="org_groups"?"specific_groups":"all_groups"),x.setCurrentContext("group-share"),x.setCurrentMode("specificGroups")},E=w.filter(A=>u.some(z=>z.id===A.id)),P=A=>{const z=u.some(J=>J.id===A),q=m.includes(A),V=y==null?void 0:y.some(J=>J.groupId===A);z?x.removeSelectedGroup(A):q?x.removeGroupFromRemove(A):V||x.addSelectedGroup({id:A,role:"VIEWER"})},D=(A,z)=>{x.updateSelectedGroupRole(A,z)},S=A=>{x.addGroupToRemove(A),x.removeSelectedGroup(A)},L=(A,z,q)=>{x.addGroupToUpdate({id:A,currentRole:z,newRole:q})};return a?e.jsxs(e.Fragment,{children:[e.jsx(Ss,{shareType:g,onShareTypeChange:O,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"})}]}),g==="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:p,onValueChange:j,disabled:N,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:N?"Loading tenants...":"Select a tenant to view its groups"})}),e.jsx(s.SelectContent,{className:"z-[51]",children:T.map(A=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:A.id,children:A.name},A.id))})]})]}),e.jsx("div",{className:"mt-3 space-y-2",children:g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&!p?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(ts,{value:i,onChange:d,placeholder:"Search groups..."}),e.jsx(pt,{selectedGroups:u,groupObjects:E,onRemove:P,onRoleChange:D,getRoleOptions:be}),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"})]}),h.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 (",h.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(xt,{groups:k,existingGroupShares:y,isLoading:C,resource:t,getRoleOptions:be,currentUser:a,handleGroupToggle:P,handleGroupRoleChange:D,handleRemoveAccess:S,handleUpdateAccess:L})]})})]}):null}const ft=()=>{const t=s.useShareCurrentContext(),n=s.useShareCurrentMode(),a=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),o=s.useShareSelectedGroups(),c=s.useShareGroupsToRemove(),i=s.useShareGroupsToUpdate(),d=s.useShareSelectedTenant(),u=s.useShareOrgWideRole(),m=s.useShareAllTenantsRole(),h=s.useShareTenantWideRole(),x=s.useShareGroupWideRole(),g=M.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedGroups:o,groupsToRemove:c,groupsToUpdate:i,selectedTenant:d,orgWideRole:u,allTenantsRole:m,tenantWideRole:h}),[t,n,a,r,l,o,c,i,d,u,m,h,x]),b=M.useMemo(()=>j=>s.validateShareData(j),[]),p=M.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(!d)return!1}else if(n==="specificTenantUsers")return d?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"?o.length>0||c.length>0||i.length>0:!0}return!1},[t,n,a,r,l,o,c,i,d]);return{buildShareData:g,validateShareData:b,isCurrentStateValid:p,currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedTenant:d,orgWideRole:u,allTenantsRole:m,tenantWideRole:h}};function Gs({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),x=s.useShareUsersToUpdate(),g=s.useShareSelectedTenant(),b=s.useShareOrgWideRole(),p=s.useShareAllTenantsRole(),j=s.useShareTenantWideRole(),{buildShareData:f,validateShareData:N,isCurrentStateValid:T}=ft(),I=a||r||l,w=()=>{var O,E,P,D;if(I)return"Updating...";if(i==="specific_users"){if(m.length===0&&h.length===0&&x.length===0)return"Select users to share with";const S=m.length+h.length+x.length;return S===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${S} user${S!==1?"s":""}`:h.length>0&&m.length===0&&x.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&x.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:x.length>0&&m.length===0&&h.length===0?`Update access for ${x.length} user${x.length!==1?"s":""}`:`Update access for ${S} user${S!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const S=d.role;return b===S?"Remove Access":"Update Access"}else if(i==="all_tenants"){const S=(E=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:E[0];if(!S||S.role===void 0)return"Share with All Tenants";const L=S.role;return p===L?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const S=(D=(P=n==null?void 0:n.shares)==null?void 0:P.tenantWide)==null?void 0:D[0];if(!S||S.role===void 0)return"Share with All Tenant Users";const L=S.role;return j===L?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(m.length===0&&h.length===0&&x.length===0)return"Select users to share with";const S=m.length+h.length+x.length;return S===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${S} user${S!==1?"s":""}`:h.length>0&&m.length===0&&x.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&x.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:x.length>0&&m.length===0&&h.length===0?`Update access for ${x.length} user${x.length!==1?"s":""}`:`Update access for ${S} user${S!==1?"s":""}`}return"Share"},C=()=>I||!t||i==="all_tenant_users"&&!g||i==="specific_tenant_users"&&!g?!0:!T,v=()=>{const O=f();O&&N(O)&&o(O)},k=()=>{var O,E,P,D;if(i==="all_users")if(!d||d.role===void 0){const S=f();S&&N(S)&&o(S)}else{const S=d.role;if(b===S)u==null||u();else{const F=f();if(F&&N(F)){const R={...F,updateAccess:!0};o(R)}}}else if(i==="all_tenants"){const S=(E=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:E[0];if(!S||S.role===void 0){const L=f();L&&N(L)&&o(L)}else{const L=S.role;if(p===L)u==null||u();else{const R=f();if(R&&N(R)){const A={...R,updateAccess:!0};o(A)}}}}else if(i==="all_tenant_users"){const S=(D=(P=n==null?void 0:n.shares)==null?void 0:P.tenantWide)==null?void 0:D[0];if(!S||S.role===void 0){const L=f();L&&N(L)&&o(L)}else{const L=S.role;if(j===L)u==null||u();else{const R=f();if(R&&N(R)){const A={...R,updateAccess:!0};o(A)}}}}},y=()=>{var O,E,P,D;if(i==="all_users"){if(!d||d.role===void 0)return"default";const S=d.role;return b===S?"destructive":"default"}else if(i==="all_tenants"){const S=(E=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:E[0];if(!S||S.role===void 0)return"default";const L=S.role;return p===L?"destructive":"default"}else if(i==="all_tenant_users"){const S=(D=(P=n==null?void 0:n.shares)==null?void 0:P.tenantWide)==null?void 0:D[0];if(!S||S.role===void 0)return"default";const L=S.role;return j===L?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:I,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||h.length>0||x.length>0)&&e.jsxs(s.Button,{onClick:v,disabled:!t||I,variant:"default",children:[I?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Be,{className:"mr-2 h-4 w-4"}),!I&&w()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:k,disabled:C(),variant:y(),children:[I?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"}),!I&&w()]})]})}function hn({resource:t,isSharing:n,isRemoving:a,isUpdating:r,onShare:l,onClose:o,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate(),h=s.useShareSelectedGroups(),x=s.useShareGroupsToRemove(),g=s.useShareGroupsToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const b=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:p,validateShareData:j,isCurrentStateValid:f}=ft(),N=n||a||r,T=()=>{if(N)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&m.length===0)return"Select users to share with";const y=d.length+u.length+m.length;return y===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${y} user${y!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:d.length>0&&u.length===0&&m.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${y} user${y!==1?"s":""}`}else if(c==="groups"){if(h.length===0&&x.length===0&&g.length===0)return"Select groups to share with";const y=h.length+x.length+g.length;return y===0?"Select groups to share with":h.length>0&&x.length>0?`Update access for ${y} group${y!==1?"s":""}`:x.length>0&&h.length===0&&g.length===0?`Remove access for ${x.length} group${x.length!==1?"s":""}`:h.length>0&&x.length===0&&g.length===0?`Share with ${h.length} group${h.length!==1?"s":""}`:g.length>0&&h.length===0&&x.length===0?`Update access for ${g.length} group${g.length!==1?"s":""}`:`Update access for ${y} group${y!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const y=i.role;return b===y?"Remove Access":"Update Access"}return"Share"},I=()=>N||!t?!0:!f,w=()=>{const y=p();y&&j(y)&&l(y)},C=()=>{const y=p();y&&j(y)&&l(y)},v=()=>{if(!i||i.role==="NONE"){const y=p();y&&j(y)&&l(y)}else{const y=i.role;if(b===y){const E=p();if(E&&j(E)){const P={...E,removeAccess:!0};l(P)}}else{const E=p();if(E&&j(E)){const P={...E,updateAccess:!0};l(P)}}}},k=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:o,disabled:N,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:w,disabled:!t||N,variant:"default",children:[N?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Be,{className:"mr-2 h-4 w-4"}),!N&&T()]})}),c==="groups"&&e.jsx(e.Fragment,{children:(h.length>0||x.length>0||g.length>0)&&e.jsxs(s.Button,{onClick:C,disabled:!t||N,variant:"default",children:[N?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Be,{className:"mr-2 h-4 w-4"}),!N&&T()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:v,disabled:I(),variant:k(),children:[N?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Be,{className:"mr-2 h-4 w-4"}),!N&&T()]})]})}function xn({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllGroupsShare:d,onRemoveAccess:u}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),x=s.useShareGroupsToUpdate();s.useShareGroupWideRole(),s.useShareCurrentMode();const g=()=>{o({context:"group-share",mode:"specificGroups",selectedGroups:m,groupsToRemove:h,groupsToUpdate:x})},b=()=>m.length>0||h.length>0||x.length>0,p=()=>h.length>0&&m.length===0&&x.length===0?"Remove Access":x.length>0&&m.length===0&&h.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"]}),h.length>0&&e.jsxs("span",{className:"ml-2 text-destructive",children:["• ",h.length," to remove"]}),x.length>0&&e.jsxs("span",{className:"ml-2 text-orange-600",children:["• ",x.length," to update"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:j,children:"Cancel"}),e.jsxs(s.Button,{onClick:g,disabled:!b()||j,children:[j&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),p()]})]})]})}function je(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Se(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function pn(t,n,a){const{resourceType:r,resourceId:l,shareMutation:o,removeMutation:c,existingShares:i,resetUserSelections:d}=n;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const u=je(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const x=je(r,l,u.map(g=>({scope:"specific_org_user",orgUserId:g.id,role:g.role})));o(x,{onSuccess:()=>{d()}})}if(m&&m.length>0){const x=Se(r,l,m.map(g=>{var p,j;const b=(j=(p=i==null?void 0:i.shares)==null?void 0:p.specificOrgUsers)==null?void 0:j.find(f=>f.orgUserId===g);return{scope:"specific_org_user",orgUserId:g,role:(b==null?void 0:b.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(x=>{const g=je(r,l,[{scope:"specific_org_user",orgUserId:x.id,role:x.newRole}]);o(g,{onSuccess:()=>{d()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const u=je(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="allTenantUsers"){const u=je(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h,tenantId:x}=t;if(m&&m.length>0){const g=Se(r,l,m.map(b=>{var j,f;const p=(f=(j=i==null?void 0:i.shares)==null?void 0:j.specificTenantUsers)==null?void 0:f.find(N=>N.tenantUserId===b);return{scope:"specific_tenant_user",tenantUserId:b,tenantId:x,role:(p==null?void 0:p.role)||"VIEWER"}}));c(g,{onSuccess:()=>{d()}})}if(h&&h.length>0&&h.forEach(g=>{const b=je(r,l,[{scope:"specific_tenant_user",tenantUserId:g.id,tenantId:x,role:g.newRole}]);o(b,{onSuccess:()=>{d()}})}),u&&u.length>0){const g=je(r,l,u.map(b=>({scope:"specific_tenant_user",tenantUserId:b.id,tenantId:x,role:b.role})));o(g,{onSuccess:()=>{d()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const u=Se(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);c(u,{onSuccess:()=>{d()}})}else if(t.updateAccess){const u=je(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else{const u=je(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const x=je(r,l,u.map(g=>({scope:"specific_tenant_user",tenantUserId:g.id,role:g.role})));o(x,{onSuccess:()=>{d()}})}if(m&&m.length>0){const x=Se(r,l,m.map(g=>{var p,j;const b=(j=(p=i==null?void 0:i.shares)==null?void 0:p.specificTenantUsers)==null?void 0:j.find(f=>f.tenantUserId===g);return{scope:"specific_tenant_user",tenantUserId:g,role:(b==null?void 0:b.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(x=>{const g=je(r,l,[{scope:"specific_tenant_user",tenantUserId:x.id,role:x.newRole}]);o(g,{onSuccess:()=>{d()}})})}break;case"group-share":if(t.mode==="specificGroups"){const{selectedGroups:u,groupsToRemove:m,groupsToUpdate:h}=t;if(u&&u.length>0){const x=je(r,l,u.map(g=>({scope:"group",groupId:g.id,role:g.role})));o(x,{onSuccess:()=>{var g;d(),(g=n.resetGroupSelections)==null||g.call(n),s.ue.success(`Shared with ${u.length} group${u.length!==1?"s":""}`)}})}if(m&&m.length>0){const x=Se(r,l,m.map(g=>({scope:"group",groupId:g,role:"VIEWER"})));c(x,{onSuccess:()=>{var g;d(),(g=n.resetGroupSelections)==null||g.call(n),s.ue.success(`Removed access from ${m.length} group${m.length!==1?"s":""}`)}})}h&&h.length>0&&h.forEach(x=>{const g=je(r,l,[{scope:"group",groupId:x.id,role:x.newRole}]);o(g,{onSuccess:()=>{var b;d(),(b=n.resetGroupSelections)==null||b.call(n),s.ue.success("Updated access for group")}})})}break}}function fn(t,n,a,r){var u,m,h,x,g,b;const{resourceType:l,resourceId:o,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(o)if(t.length>0){const p=Se(l,o,t.map(j=>{var N,T;const f=(T=(N=i==null?void 0:i.shares)==null?void 0:N.specificTenantUsers)==null?void 0:T.find(I=>I.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,role:(f==null?void 0:f.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()},onError:j=>{console.error("Remove access failed:",j)}})}else{const p=n==="tenant"&&a==="allTenants",j=n==="tenant"&&a==="allTenantUsers";if(p){const f=(m=(u=i==null?void 0:i.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(f){const N=Se(l,o,[{scope:"all_tenants_only",role:f.role}]);c(N,{onSuccess:()=>{d()},onError:T=>{console.error("Remove all-tenants access failed:",T)}})}}else if(j){const f=(x=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:x[0];if(f){const N=Se(l,o,[{scope:"all_tenant_users",role:f.role}]);c(N,{onSuccess:()=>{d()},onError:T=>{console.error("Remove all-tenant-users access failed:",T)}})}}else{const f=(b=(g=i==null?void 0:i.shares)==null?void 0:g.orgUsersOnly)==null?void 0:b[0];if(f){const N=Se(l,o,[{scope:"org_users_only",role:f.role}]);c(N,{onSuccess:()=>{d()},onError:T=>{console.error("Remove org-wide access failed:",T)}})}}}}function gn(t,n,a){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=s.useCurrentUserInfo(),{existingShares:d}=_e({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),u=M.useCallback(()=>{r.resetUserSelections()},[r]),m=M.useCallback(()=>{r.resetGroupSelections()},[r]),h=M.useCallback(g=>{if(!t)return;const b={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:n,removeMutation:a,existingShares:d,resetUserSelections:u,resetGroupSelections:m};pn(g,b,i)},[t,n,a,d,u,m,i]),x=M.useCallback(()=>{if(!t)return;const g={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:a,existingShares:d,resetUserSelections:u};fn(l,o||"",c||"",g)},[t,n,a,d,u,m,l,o,c]);return{handleShareSubmit:h,handleRemoveAccess:x}}function ls({resource:t,resourceType:n,onClose:a,onShareSuccess:r,onRemoveSuccess:l}){var D,S,L,F,R,A,z,q;const{currentUser:o}=s.useCurrentUserInfo(),[c,i]=M.useState("specific_users"),[d,u]=M.useState("specific_users"),[m,h]=M.useState("specific_groups"),x=s.useShareManagementActions(),g=s.useShareSelectedTab(),b=s.useShareCurrentMode(),p=s.useShareResource(),j=s.useRemoveResourceShares(),{handleShareSubmit:f,handleRemoveAccess:N}=gn(t.id,(V,J)=>{p.mutate(V,{...J,onSuccess:()=>{var Z;(Z=J==null?void 0:J.onSuccess)==null||Z.call(J),r==null||r()}})},(V,J)=>{j.mutate(V,{...J,onSuccess:()=>{var Z;(Z=J==null?void 0:J.onSuccess)==null||Z.call(J),l==null||l()}})}),T=p.isPending,I=j.isPending,w=p.isPending,{existingShares:C}=_e({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant"}),{existingShares:v}=_e({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"organization"}),k=(S=(D=C==null?void 0:C.shares)==null?void 0:D.tenantWide)==null?void 0:S[0],y=(F=(L=v==null?void 0:v.shares)==null?void 0:L.orgUsersOnly)==null?void 0:F[0],O=()=>{if(g==="org")return d;switch(b){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},E=M.useCallback(()=>{x.resetShareState(),a()},[x,a]),P=(o==null?void 0:o.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:E,children:e.jsxs(s.DialogContent,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Be,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:P?"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."})]}),P?e.jsxs(s.Tabs,{value:g,onValueChange:V=>{const J=V;x.setSelectedTab(J),x.resetUserSelections(),x.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(cn,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:u,isSharing:T,isUpdating:w,isRemoving:I})})}),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(Us,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:V=>i(V),isSharing:T,isUpdating:w,isRemoving:I})})}),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(mn,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:h,isSharing:T,isUpdating:w,isRemoving:I})})})]}):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(Us,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:V=>i(V),isSharing:T,isUpdating:w,isRemoving:I})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:P?g==="org"?e.jsx(Gs,{resource:t,existingShares:v,isSharing:T,isRemoving:I,isUpdating:w,onShare:f,onClose:a,shareTabType:d,currentAllUsersShare:y,onRemoveAccess:N}):g==="tenant"?e.jsx(Gs,{resource:t,existingShares:C,isSharing:T,isRemoving:I,isUpdating:w,onShare:f,onClose:a,shareTabType:O(),currentAllUsersShare:k,onRemoveAccess:N}):e.jsx(xn,{resource:t,existingShares:v,isSharing:T,isRemoving:I,isUpdating:w,onShare:f,onClose:a,shareTabType:m,currentAllGroupsShare:(o==null?void 0:o.type)==="organization"?(A=(R=v==null?void 0:v.shares)==null?void 0:R.allOrgGroups)==null?void 0:A[0]:(q=(z=C==null?void 0:C.shares)==null?void 0:z.allTenantGroups)==null?void 0:q[0],onRemoveAccess:N}):e.jsx(hn,{resource:t,isSharing:T,isRemoving:I,isUpdating:w,onShare:f,onClose:a,shareTabType:c,currentAllUsersShare:k,onRemoveAccess:N})})]})})}const jn=async(t,n,a)=>{const r=`${t}/management/v1/groups`;return await s.postRequestRegular(r,n,a)},bn=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 o=await l.text();throw new Error(o||"Failed to delete group")}},vn=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`;return await s.postRequestRegular(l,n,r)},yn=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`,o=await fetch(l,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)});if(!o.ok){const c=await o.text();throw new Error(c||"Failed to remove group members")}};function Nn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>jn(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 Cn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>bn(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 Sn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>vn(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 wn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>yn(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 Dn({onSuccess:t,tenantId:n,isTenantUser:a}){const[r,l]=M.useState(""),[o,c]=M.useState(""),[i,d]=M.useState({}),u=Nn(),m=()=>{const x={};return r.trim()?r.length<3?x.name="Group name must be at least 3 characters":r.length>50&&(x.name="Group name must be less than 50 characters"):x.name="Group name is required",o&&o.length>200&&(x.description="Description must be less than 200 characters"),d(x),Object.keys(x).length===0},h=async x=>{if(x.preventDefault(),!m())return;const g={name:r.trim(),description:o.trim()||void 0,type:a?"TENANT_GROUP":"ORG_GROUP",...a&&n?{tenantId:n}:{}};try{await u.mutateAsync(g),l(""),c(""),d({}),t()}catch(b){console.error("Failed to create group:",b)}};return e.jsxs("form",{onSubmit:h,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:x=>{l(x.target.value),i.name&&d(g=>({...g,name:""}))},className:i.name?"border-destructive":"",disabled:u.isPending}),i.name&&e.jsx("p",{className:"text-sm text-destructive",children:i.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:o,onChange:x=>{c(x.target.value),i.description&&d(g=>({...g,description:""}))},className:i.description?"border-destructive":"",disabled:u.isPending,rows:3}),i.description&&e.jsx("p",{className:"text-sm text-destructive",children:i.description}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.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(""),c(""),d({})},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 Tn({open:t,onOpenChange:n,group:a,onUpdate:r}){const[l,o]=M.useState("members"),[c,i]=M.useState(""),[d,u]=M.useState([]),[m,h]=M.useState([]),{data:x,isLoading:g,refetch:b}=s.useGroupMembers(a.id),p=a.type==="TENANT_GROUP"?"tenant":"organization",{users:j,isLoading:f}=s.useUnifiedUsers({type:p,tenantId:a.tenantId||void 0,active:!0,limit:100}),N=Sn(),T=wn(),I=(x==null?void 0:x.members)||[],w=M.useMemo(()=>new Set(I.map(D=>D.userId)),[I]),C=M.useMemo(()=>j.filter(D=>!w.has(D.id)),[j,w]),v=M.useMemo(()=>{if(!c)return C;const D=c.toLowerCase();return C.filter(S=>{var L,F;return((L=S.name)==null?void 0:L.toLowerCase().includes(D))||((F=S.email)==null?void 0:F.toLowerCase().includes(D))})},[C,c]),k=M.useMemo(()=>{if(!c)return I;const D=c.toLowerCase();return I.filter(S=>{var L,F,R,A;return((F=(L=S.user)==null?void 0:L.name)==null?void 0:F.toLowerCase().includes(D))||((A=(R=S.user)==null?void 0:R.email)==null?void 0:A.toLowerCase().includes(D))})},[I,c]),y=async()=>{if(d.length!==0)try{await N.mutateAsync({groupId:a.id,data:{userIds:d,userType:p==="tenant"?"tenant":"org"}}),u([]),o("members"),b(),r==null||r()}catch(D){console.error("Failed to add members:",D)}},O=async()=>{if(m.length!==0)try{await T.mutateAsync({groupId:a.id,data:{userIds:m}}),h([]),b(),r==null||r()}catch(D){console.error("Failed to remove members:",D)}},E=D=>{u(S=>S.includes(D)?S.filter(L=>L!==D):[...S,D])},P=D=>{h(S=>S.includes(D)?S.filter(L=>L!==D):[...S,D])};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:[I.length," ",I.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:D=>{o(D),i(""),h([])},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:c,onChange:D=>i(D.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:m.length>0?"h-[300px]":"h-[350px]",children:g?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(D=>e.jsx(s.Skeleton,{className:"h-16 w-full"},D))}):k.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:c?"No members found":"No members yet"}),e.jsx("p",{className:"text-xs mt-1",children:c?"Try a different search":'Switch to the "Add Members" tab to add people to this group'})]}):e.jsx("div",{className:"space-y-2",children:k.map(D=>e.jsx(kn,{member:D,selected:m.includes(D.userId),onToggle:()=>P(D.userId)},D.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:O,disabled:T.isPending,children:T.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:c,onChange:D=>i(D.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[300px]",children:f?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(D=>e.jsx(s.Skeleton,{className:"h-16 w-full"},D))}):v.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:c?"Try a different search":"All eligible users are already members"})]}):e.jsx("div",{className:"space-y-2",children:v.map(D=>e.jsx(En,{user:D,selected:d.includes(D.id),onToggle:()=>E(D.id)},D.id))})}),d.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:[d.length," user",d.length!==1?"s":""," selected"]}),e.jsx(s.Button,{onClick:y,disabled:N.isPending,children:N.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 kn({member:t,selected:n,onToggle:a}){var l,o,c,i;const r=((o=(l=t.user)==null?void 0:l.name)==null?void 0:o.split(" ").map(d=>d[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:((c=t.user)==null?void 0:c.name)||"Unknown User"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(i=t.user)==null?void 0:i.email})]})]})}function En({user:t,selected:n,onToggle:a}){var l;const r=((l=t.name)==null?void 0:l.split(" ").map(o=>o[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 In({open:t,onOpenChange:n}){const[a,r]=M.useState("groups"),[l,o]=M.useState(""),[c,i]=M.useState(null),[d,u]=M.useState(!1),[m,h]=M.useState(null),{tokenProps:x}=s.useSemaphorContext(),{currentUser:g}=s.useCurrentUserInfo(),b=Cn(),p=(g==null?void 0:g.type)==="tenant",j=x==null?void 0:x.tenantId,{groups:f,isLoading:N,refetch:T}=s.useGroups({type:p?"TENANT_GROUP":"all",tenantId:p?j:void 0,includeMembers:!1}),I=f.filter(k=>{var y;return k.name.toLowerCase().includes(l.toLowerCase())||((y=k.description)==null?void 0:y.toLowerCase().includes(l.toLowerCase()))}),w=async()=>{if(m)try{await b.mutateAsync(m.id),h(null),T()}catch(k){console.error("Failed to delete group:",k)}},C=k=>{i(k),u(!0)},v=()=>{r("groups"),T()};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:k=>o(k.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[400px]",children:N?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(k=>e.jsx(s.Skeleton,{className:"h-24 w-full"},k))}):I.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:I.map(k=>e.jsx(An,{group:k,onManageMembers:()=>C(k),onDelete:()=>h(k),currentUserId:g==null?void 0:g.id},k.id))})})]})}),e.jsx(s.TabsContent,{value:"create",className:"mt-4",children:e.jsx(Dn,{onSuccess:v,tenantId:j,isTenantUser:p})})]})]})}),c&&e.jsx(Tn,{open:d,onOpenChange:u,group:c,onUpdate:()=>T()}),e.jsx(s.AlertDialog,{open:!!m,onOpenChange:()=>h(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 An({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 Mn(){var Y,Q,X;const{authToken:t,tokenProps:n,id:a}=s.useSemaphorContext(),{isLocalDev:r}=s.useDashboardPreferences(),{permissions:l}=s.useRoleAwareDisplayPreferences(),o=s.useHasDashboardId();s.useDashboardStore($=>$.theme);const c=s.useDashboardStore($=>$.lenses),i=s.useDashboardStore($=>$.selectedLensId),d=c==null?void 0:c.find($=>$.id===i),u=s.useDashboardStore($=>$.dashboard);s.useDashboardStore($=>$.selectedSheetId);const m=s.useDashboardStore($=>$.isDashboardEditing),h=s.useEditorStore($=>$.card),x=s.useEditorStore($=>$.selectedConnectionId),[g,b]=M.useState(!1),[p,j]=M.useState(!1),[f,N]=M.useState(!1),T=s.useDashboardStore($=>$.isDashboardPanelOpen),I=s.useDashboardStore($=>$.actions.setIsDashboardPanelOpen),w=s.useDashboardStore($=>$.filterValues),C=s.useDashboardStore($=>$.isVisualEditing),v=s.useManagementStore($=>$.selectedDashboard),k=s.useManagementStore($=>$.initialDashboard),y=v?(Q=v==null?void 0:v.permissions)==null?void 0:Q.canEdit:(Y=k==null?void 0:k.permissions)==null?void 0:Y.canEdit,O=s.useDashboardStore($=>$.showFilters),E=s.useDashboardStore($=>$.showDashboardJSON),P=s.useDashboardStore($=>$.onSaveFunction),D=s.useDashboardStore($=>$.actions.setShowFilters),{addFrame:S,setSelectedFrameId:L}=s.useDashboardStore($=>$.actions),{getSelectedSheet:F,setIsDashboardEditing:R,setShowDashboardJSON:A}=s.useDashboardStore($=>$.actions),z=F(),{setInitialDashboard:q,clearSelectedDashboard:V}=s.useManagementStore($=>$.actions),{resources:J}=s.useResourceManagement(s.ResourceType.DASHBOARD),{currentUser:Z}=s.useCurrentUserInfo(),W=s.canUserManageGroups(Z),H=v||k,G=H?{id:H.id,title:(u==null?void 0:u.title)||H.title||"Dashboard"}:null;M.useEffect(()=>{if(J&&J.length>0){const $=u==null?void 0:u.id;if($){const te=J.find(ie=>ie.id===$);te&&q(te)}}},[J,u==null?void 0:u.id,q]);const se=n.orgUserId||n.tenantId,_=m&&!C&&se&&y;function U(){var ce,Ee;const $=h.dataSource;if($)return $;const te=(Ee=(ce=u.aiContext)==null?void 0:ce.selectedEntities)==null?void 0:Ee[0],ie=te==null?void 0:te.type;if(te)return{connectionId:te.connectionId,connectionType:te.connectionType,type:ie,selectedEntities:[te]}}const ee=()=>{if(!m||!z)return;const te={dataSource:U(),mode:"explorer",connectionId:x,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},ie={id:s.v4(),cards:[te],activeCardId:te.id};S(z.id,ie),L(ie.id)},ne=()=>{R(!0)},[oe,B]=M.useState(!1),ae=s.useUpdateResource(s.ResourceType.DASHBOARD);async function le(){const $=ss(u);B(!0);const te={template:$};ae.mutate({resourceId:$.id,data:te},{onSuccess:()=>{B(!1),s.ue.success("Dashboard saved!")},onError:()=>{B(!1),s.ue.error("Failed to save dashboard")}})}async function re(){if(b(!0),!i||!d)return;const $=ss(u),te=JSON.stringify($),ie={...d,template:te,filterValues:w};await vs(n.apiServiceUrl,ie,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),P==null||P($),b(!1)}if(C)return null;const xe=(d==null?void 0:d.name)||u.title,me=J&&J.length>0&&(n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail),fe=v&&!(n!=null&&n.dashboard_id)&&!a;return e.jsxs("div",{className:"flex h-10 items-center justify-between gap-2 border-b py-2 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[me&&e.jsxs(e.Fragment,{children:[fe&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Back to Dashboard Hub",onClick:()=>V(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})}),e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:o?"Manage Dashboards":"Select a dashboard to continue",onClick:()=>{I(!T)},className:"h-7 p-2",buttonProps:{disabled:!o},children:e.jsx(Ta,{className:"h-4 w-4"})})]}),!C&&o&&e.jsx(s.Label,{children:xe})]}),e.jsxs("div",{className:"flex gap-2",children:[r&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:()=>s.invalidateToken(n.apiServiceUrl),className:"h-7 p-2",children:e.jsx(Ba,{className:"h-4 w-4"})}),!C&&o&&e.jsx(Ja,{}),!C&&o&&e.jsx(lt,{}),!C&&o&&W&&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"})}),!C&&o&&((X=H==null?void 0:H.permissions)==null?void 0:X.canShare)&&e.jsx(s.IconButton,{tooltip:"Share Dashboard",onClick:()=>j(!0),className:"h-7 p-2",children:e.jsx(s.UserPlus,{className:"h-4 w-4"})}),m&&!C&&se&&r&&o&&e.jsx(Ka,{}),!C&&se&&r&&o&&e.jsx(Qa,{}),m&&!C&&se&&d&&r&&o&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:g,onClick:re,size:"sm",children:[e.jsx(bs,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),m&&!C&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!m,onClick:ee,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!C&&!m&&l.canEdit&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:ne,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),m&&!C&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{R(!1),A(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),_&&o&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"outline",disabled:oe,onClick:le,size:"sm",children:[oe?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(bs,{className:"mr-2 h-4 w-4"}),oe?"Saving...":"Save"]}),!O&&!C&&m&&l.canUseFilters&&o&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>D(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!C&&m&&r&&o&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>A(!E),size:"sm",variant:"ghost",children:e.jsx(ze,{className:"h-4 w-4"})})}),!C&&r&&e.jsx($a,{}),p&&G&&e.jsx(ls,{resource:G,resourceType:s.ResourceType.DASHBOARD,onClose:()=>j(!1)}),e.jsx(In,{open:f,onOpenChange:N})]})]})}function Ln({name:t,items:n,value:a,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:d,showNone:u=!1}){const m=Ie.useRef(null),[h,x]=Ie.useState(!1),[g,b]=Ie.useState("100%"),p=u?[...n||[],{id:"none",name:"None"}]:n;Ie.useLayoutEffect(()=>{m.current&&b(m.current.offsetWidth)},[]);function j(){var N;return l?"Loading...":o?"Error":a?(N=n==null?void 0:n.find(T=>T.id===a))==null?void 0:N.name:`Select ${t}`}function f(N,T){r(T),x(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:x,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:m,variant:"outline",role:"combobox","aria-expanded":h,className:s.cn("flex h-9 w-full justify-between",i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx("div",{className:"mr-2",children:d}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:j()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:g},children:e.jsxs(s.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(s.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(s.IconButton,{className:"h-7",onClick:c,children:e.jsx(st,{className:s.cn("size-3.5 opacity-50",l&&"animate-spin")})})]}),e.jsxs(s.CommandList,{children:[e.jsxs(s.CommandEmpty,{children:["No ",t==null?void 0:t.toLowerCase()," found."]}),e.jsx(s.CommandGroup,{children:p==null?void 0:p.map(N=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:N.name,onSelect:T=>f(T,N.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",a===N.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:N.name,children:N.name})]})},N.id))})]})]})})]})}function Pe({title:t,items:n,value:a,isLoading:r,isError:l,refetch:o,onChange:c,showNone:i=!1,className:d,disabled:u=!1,type:m="combobox"}){const h=r?"Loading...":l?"Error":a;function x(){if(t==="Connection")return e.jsx(Oa,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Ma,{className:"size-4"});if(t==="Table")return e.jsx(s.Table2,{className:"size-4"});if(t==="Model")return e.jsx(oa,{className:"size-4"})}function g(){return e.jsxs(s.Select,{disabled:u,value:h,onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:s.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",d),children:e.jsx(s.SelectValue,{placeholder:r?"Loading...":l?"Error":`Select ${t}`})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[r?e.jsx(s.SelectLabel,{children:"Loading..."}):e.jsxs(s.SelectLabel,{className:"flex items-center justify-between gap-2",children:[t,e.jsx(st,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:o})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),n&&n.map((p,j)=>e.jsx(s.SelectItem,{value:p.id,children:p.name},j))]}),(r||l)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function b(){return e.jsx(Ln,{icon:x(),items:n,value:h,onChange:c||(()=>{}),isLoading:r,isError:l,refetch:o,name:t,showNone:i})}return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:m==="select"?g():b()})})}function Rn({column:t}){const[n,a]=M.useState(!1),r=s.useEditorStore(p=>p.selectedTableName),l=s.useEditorStore(p=>p.selectedSchemaName),o=s.useEditorStore(p=>p.selectedDatabaseName),c=s.useEditorStore(p=>p.selectedDatamodelId),i=s.useEditorStore(p=>p.sqlGen),{modelItems:d,connectionType:u}=s.useEditorAside(),m=s.useEditorStore(p=>p.actions.setSqlGen),h=s.useEditorStore(p=>p.actions.setCardSql),x=s.useEditorStore(p=>p.actions.setRunSql);function g(p,j){var I;const f=s.createSqlGenConfig(p,i,j),N=(I=d==null?void 0:d.find(w=>w.id===c))==null?void 0:I.name;m(f);const T=s.getSql(f,s.fmt(l||""),s.fmt(r),N||"",u,o||"");T&&(h(T),x(!0)),a(!1)}function b(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>g(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>g(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>g(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>g(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>g(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:n,onOpenChange:a,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]})}function On({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Re,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ze,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(qe,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Ke,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})}function ds({column:t,className:n}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center gap-2 px-3 py-[6px] text-sm",n),children:[e.jsx(On,{dataType:t.data_type}),e.jsx("span",{children:t.column_name})]})}function Fn({id:t,children:n,type:a="column"}){const{attributes:r,listeners:l,setNodeRef:o,transform:c}=s.useDraggable({id:t,data:{type:a}}),i=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:o,style:i,...l,...r,children:n})}function Pn({onClick:t,column:n}){const a=s.useDndStore(m=>m.activeId),r=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.groupByColumns}),l=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.metricColumns}),o=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.filterColumns});function c(m){return i(m)||d(m)||u(m)}function i(m){return r==null?void 0:r.some(h=>h.name===m.column_name)}function d(m){return l==null?void 0:l.some(h=>h.name===m.column_name)}function u(m){return o==null?void 0:o.some(h=>h.name===m.column_name)}return e.jsxs("div",{onClick:()=>t(n),className:s.cn("group relative grow cursor-pointer overflow-x-hidden overflow-y-hidden border border-dashed border-background transition-colors hover:bg-muted/50",{"bg-muted":c(n)}),children:[a===n.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(ds,{column:n,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),a===n.column_name&&e.jsx("div",{className:"absolute inset-0",children:a===n.column_name&&e.jsx(ds,{column:n})}),e.jsx(Fn,{id:n.column_name,type:"column",children:e.jsx(ds,{column:n})})]})}const us={id:"__placeholder__",role:"groupby",type:"string"},ms={id:"__placeholder__",role:"groupby",type:"string"},hs={id:"__placeholder__",role:"metric",type:"number"},xs={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},gt={id:"__placeholder__"},Ae="droppable-group-by",Me="droppable-metrics",Le="droppable-pivot-by",as="sortable-group-by",ys="sortable-metrics",ns="sortable-pivot-by",Ns="droppable-filters",Cs="sortable-filters",ws="sortable-order-by";function Bn(){const t=s.useDndStore(S=>S.insertIndex),n=s.useEditorStore(S=>{var L;return((L=S.card.queryConfig)==null?void 0:L.groupByColumns)||[]}),a=s.useEditorStore(S=>{var L;return((L=S.card.queryConfig)==null?void 0:L.metricColumns)||[]}),r=s.useEditorStore(S=>{var L;return((L=S.card.queryConfig)==null?void 0:L.filterColumns)||[]}),l=s.useEditorStore(S=>{var L;return((L=S.card.queryConfig)==null?void 0:L.orderBy)||[]}),o=s.useEditorStore(S=>{var L;return((L=S.card.queryConfig)==null?void 0:L.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:u,setPreviewFilterColumns:m,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:x,setMetricColumns:g,setFilterColumns:b,setOrderByColumns:p,setPivotByColumns:j}=s.useEditorActions(),{columns:f}=s.useDataColumns(),{formattedTableName:N}=s.useEditorAside(),T=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),I=S=>{var R;const{active:L,over:F}=S;if(((R=L.data.current)==null?void 0:R.type)==="column"&&F){const A=F.id,z=f.find(Z=>Z.column_name===L.id);if(!z)return;const q=s.isNumberDataType(z.data_type),V=s.isTextDataType(z.data_type),J=s.isDateDataType(z.data_type);if(V||J){if(n.some(W=>W.id===A)){const W=n.findIndex(G=>G.id===A);c(W);const H=n.filter(G=>G.id!==us.id);H.splice(W,0,us),d(H)}else if(F.id===Ae){c(n.length);const W=[...n,us];d(W),u(a),m(r)}}if(V||J){if(o.some(W=>W.id===A)){const W=o.findIndex(G=>G.id===A);c(W);const H=o.filter(G=>G.id!==ms.id);H.splice(W,0,ms),h(H)}else if(F.id===Le){c(o.length);const W=[...o,ms];h(W),d(n),u(a),m(r)}}if(q||V){if(a.some(W=>W.id===A)){console.log("isOverMetricSortable",A);const W=a.findIndex(G=>G.id===A);c(W);const H=a.filter(G=>G.id!==hs.id);H.splice(W,0,hs),u(H)}else if(F.id===Me){c(a.length);const W=[...a,hs];u(W),m(r),d(n),h(o)}}if(C(z)){if(r.some(W=>W.id===A)){const W=r.findIndex(G=>G.id===A);c(W);const H=r.filter(G=>G.id!==xs.id);H.splice(W,0,xs),m(H)}else if(F.id===Ns){c(r.length);const W=[...r,xs];m(W),u(a),d(n),h(o)}}}else d(n),u(a),m(r),h(o)};function w(S){i(S.active.id),c(null),d(n),u(a),m(r),h(o)}function C(S){return!r.some(L=>L.name===S.column_name)}function v(S,L="SUM"){const{column_name:F,data_type:R}=S,A=[...a],z=t!==null?t:a.length,q={...S,id:Ne(F),name:F,label:We(F,L),type:R,role:"metric",aggregate:L};A.splice(z,0,q),g(A)}function k(S){const L=s.isTextDataType(S.data_type);s.isDateDataType(S.data_type);const F=[...o],R=t!==null?t:o.length;let A;L?A={...S,id:Ne(S.column_name),name:S.column_name,type:S.data_type,role:"groupby"}:A={...S,id:Ne(S.column_name),name:S.column_name,type:S.data_type,role:"groupby",label:Ve(S.column_name,"month"),granularity:"month"},F.splice(R,0,A),j(F)}function y(S){const L=s.isTextDataType(S.data_type);s.isDateDataType(S.data_type);const F=[...n],R=t!==null?t:n.length;let A;L?A={...S,id:Ne(S.column_name),name:S.column_name,type:S.data_type,role:"groupby"}:A={...S,id:Ne(S.column_name),name:S.column_name,type:S.data_type,role:"groupby",label:Ve(S.column_name,"month"),granularity:"month"},F.splice(R,0,A),x(F)}function O(S){const L=[...r],F=t!==null?t:r.length,R={...S,id:Ne(S.column_name),name:S.column_name,type:S.data_type,sql:s.getDefaultFilterSql(S.data_type,N,s.fmt(S.column_name)),role:"filter"};L.splice(F,0,R),b(L)}function E(S){var A,z,q,V,J,Z,W,H;const{active:L,over:F}=S,R=L.data.current;if((R==null?void 0:R.type)==="column"&&F){const G=f.find(ee=>ee.column_name===L.id);if(!G)return;const se=s.isNumberDataType(G.data_type),_=s.isTextDataType(G.data_type),U=s.isDateDataType(G.data_type);(_||U)&&(F.id===Ae||((A=F.data.current)==null?void 0:A.type)===as)&&y(G),(_||U)&&(F.id===Le||((z=F.data.current)==null?void 0:z.type)===ns)?k(G):(se||_)&&(F.id===Me||((q=F.data.current)==null?void 0:q.type)===ys)?(se&&v(G),_&&v(G,"COUNT")):C(G)&&(F.id===Ns||((V=F.data.current)==null?void 0:V.type)===Cs)&&O(G)}if(F&&((J=F.data.current)==null?void 0:J.type)===as&&n.some(G=>G.id===L.id)){const G=n.findIndex(_=>_.id===L.id),se=n.findIndex(_=>_.id===F.id);if(G!==-1&&se!==-1&&G!==se){const _=[...n],[U]=_.splice(G,1);_.splice(se,0,U),x(_)}}if(F&&((Z=F.data.current)==null?void 0:Z.type)===ns&&o.some(G=>G.id===L.id)){const G=o.findIndex(_=>_.id===L.id),se=o.findIndex(_=>_.id===F.id);if(G!==-1&&se!==-1&&G!==se){const _=[...o],[U]=_.splice(G,1);_.splice(se,0,U),j(_)}}if(F&&((W=F.data.current)==null?void 0:W.type)===ys&&a.some(G=>G.id===L.id)){const G=a.findIndex(_=>_.id===L.id),se=a.findIndex(_=>_.id===F.id);if(G!==-1&&se!==-1&&G!==se){const _=[...a],[U]=_.splice(G,1);_.splice(se,0,U),g(_)}}if(F&&((H=F.data.current)==null?void 0:H.type)===Cs&&r.some(G=>G.id===L.id)){const G=r.findIndex(_=>_.id===L.id),se=r.findIndex(_=>_.id===F.id);if(G!==-1&&se!==-1&&G!==se){const _=[...r],[U]=_.splice(G,1);_.splice(se,0,U),b(_)}}P(S),i(null),c(null),d(n),u(a),m(r),h(o)}function P(S){const{active:L,over:F}=S,R=L.data.current;if((R==null?void 0:R.type)===ws&&F){const A=l.findIndex(q=>$e(q.columnId)===L.id),z=l.findIndex(q=>$e(q.columnId)===F.id);if(A!==-1&&z!==-1&&A!==z){const q=[...l],[V]=q.splice(A,1);q.splice(z,0,V),p(q)}}}function D(){i(null),c(null),d(n),u(a),m(r)}return{handleDragOver:I,handleDragEnd:E,handleDragStart:w,handleDragCancel:D,sensors:T}}function Ne(t){return`${t}-${s.v4()}`}function We(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 $e(t){return`${ws}-${t}`}function Ve(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 zn({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Re,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ze,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(qe,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Ke,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})}function _n({schemaName:t,tableName:n,columns:a,status:r}){const[l,o]=M.useState(""),[c,i]=M.useState("all"),d=s.useEditorStore(A=>A.sqlGen),u=s.useEditorStore(A=>A.isDevMode);s.useEditorStore(A=>A.selectedConnectionId);const m=s.useEditorStore(A=>{var z,q;return(q=(z=A.card)==null?void 0:z.queryConfig)==null?void 0:q.metricColumns});s.useEditorStore(A=>{var z,q;return(q=(z=A.card)==null?void 0:z.queryConfig)==null?void 0:q.groupByColumns});const h=s.useEditorStore(A=>A.selectedDatabaseName);s.useEditorStore(A=>A.selectedSchemaName),s.useEditorStore(A=>A.selectedTableName);const x=s.useEditorStore(A=>A.selectedDatamodelId);s.useDashboardStore(A=>A.dashboard.aiScopeTables);const{addToAIScope:g,removeFromAIScope:b}=s.useDashboardActions(),{addColumnToMetricColumns:p,addColumnToGroupBy:j,setCardSql:f,setRunSql:N,setSqlGen:T,setIsShowingVisual:I}=s.useEditorActions(),{connectionType:w,modelItems:C,selectedDatamodelName:v}=s.useEditorAside();function k(A){var z;if(u){const q=s.createSqlGenConfig(A,d);T(q);const V=(z=C==null?void 0:C.find(Z=>Z.id===x))==null?void 0:z.name,J=s.getSql(q,s.fmt(t),s.fmt(n),V||"",w,h||"");J&&(f(J),N(!0))}if(!u){if(s.isTextDataType(A.data_type))if(m&&m.length>0){const q={...A,role:"groupby",id:Ne(A.column_name),name:A.column_name,type:A.data_type};j(q)}else{const q={...A,role:"metric",id:Ne(A.column_name),name:A.column_name,label:We(A.column_name,"COUNT"),type:A.data_type,aggregate:"COUNT"};p(q)}if(s.isDateDataType(A.data_type)){const q={...A,role:"groupby",id:Ne(A.column_name),name:A.column_name,type:A.data_type,label:Ve(A.column_name,"month"),granularity:"month"};j(q)}if(s.isNumberDataType(A.data_type)){const q={...A,role:"metric",id:Ne(A.column_name),name:A.column_name,label:We(A.column_name,"SUM"),type:A.data_type,aggregate:"SUM"};p(q)}}}function y(){const A=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:w,databaseName:h||""});I(!1);const z=w==="MSSQL"?`SELECT top 10 * FROM ${A}`:`SELECT * FROM ${A} LIMIT 10`;f(z),N(!0)}function O(){const A=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:w,databaseName:h||""});f(`SELECT COUNT(*) as count FROM ${A}`),N(!0)}const E=(a==null?void 0:a.filter(A=>A.column_name.toLowerCase().includes(l.toLowerCase())))||[],P=A=>s.isNumberDataType(A.data_type)?"number":"text",D=c==="all"?E:E.filter(A=>P(A)===c),S=E.filter(A=>P(A)==="text").length,L=E.filter(A=>P(A)==="number").length;function F(A){return u?e.jsxs("div",{className:"group flex cursor-pointer items-center justify-between border border-dashed border-background px-2 py-[6px] text-sm transition-colors hover:bg-muted/50",onClick:()=>k(A),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zn,{dataType:A.data_type}),e.jsx("span",{children:A.column_name})]}),e.jsx("div",{onClick:z=>z.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(A.data_type)&&e.jsx(Rn,{column:A})})]}):e.jsx(Pn,{onClick:k,column:A})}function R(){return e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:r!=="Success",onClick:y,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(Da,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:O,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(tt,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-4",children:Array.from({length:3}).map((A,z)=>e.jsx(s.Skeleton,{className:"h-8 w-full"},z))}):e.jsxs("div",{className:"flex grow flex-col",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-4",children:[u&&e.jsx("div",{className:"flex items-center justify-center gap-2",children:R()}),a&&a.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:l,onChange:A=>o(A.target.value)})]}),E.length>0&&e.jsx(s.Tabs,{defaultValue:"all",value:c,onValueChange:A=>i(A),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:E.length})]}),e.jsxs(s.TabsTrigger,{value:"text",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:S})]}),e.jsxs(s.TabsTrigger,{value:"number",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:L})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-4 pt-3",children:[D.length===0&&l&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',l,'"']}),D.length===0&&!l&&c!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",c," fields found"]}),e.jsx("div",{className:"flex flex-col gap-1",children:D==null?void 0:D.map(A=>e.jsx("div",{children:F(A)},A.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function jt({ColumnsComponent:t,type:n}){var Q;const[a,r]=M.useState(!1),l=s.useEditorStore(X=>X.card),o=s.useEditorStore(X=>X.selectedConnectionId),c=s.useDashboardStore(X=>X.showFilters),i=s.useEditorStore(X=>X.selectedDatamodelId),d=s.useEditorStore(X=>X.selectedDatabaseName),u=s.useEditorStore(X=>X.selectedSchemaName),m=s.useEditorStore(X=>X.selectedTableName),h=s.useEditorStore(X=>X.isDevMode),{setSelectedTableName:x,setIsDevMode:g,setCardSql:b}=s.useEditorActions(),{connectionItems:p,modelItems:j,schemaItems:f,databaseItems:N,tableItems:T,columns:I,isConnectionsLoading:w,isModelsLoading:C,isConnectionsError:v,isModelsError:k,isDatabasesLoadingOrFetching:y,isDatabaseError:O,isSchemaLoadingOrFetching:E,isSchemaError:P,isColumnsError:D,isColumnsLoadingOrFetching:S,isTableLoadingOrFetching:L,isTableError:F,connectionType:R,isNonDbConnection:A,refetchDatabases:z,refetchModels:q,refetchSchemas:V,refetchTables:J,refetchColumns:Z,refetchConnections:W,handleConnectionChange:H,handleDatabaseChange:G,handleSchemaChange:se,handleDatamodelChange:_,handleTableChange:U,tableName:ee,schemaName:ne}=s.useEditorAside(),{data:oe,refetch:B}=s.useDashboardCardQuery(l);function ae(){return t?t(ne,ee,I):e.jsx(_n,{schemaName:ne,tableName:ee,columns:I,status:S?"Loading...":D?"Error":"Success"})}function le(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function re(X){X===!0?oe&&(b(oe.userSql),setTimeout(()=>{B()},100)):b(""),g(X)}function xe(){if(!o||R==="S3"||R==="API")return null;if(!i||i==="none")return e.jsx(Pe,{refetch:z,showNone:!0,onChange:G,isError:O,isLoading:y,items:N,value:d||"",title:"Database",type:"combobox"})}function pe(){if(o&&!A&&(!d||d==="none")&&(!i||i==="none"))return e.jsxs("div",{className:"grid grid-cols-3",children:[e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})})]})}function me(){if(!o||R==="S3"||R==="API")return null;if(!d||d==="none")return e.jsx(Pe,{refetch:q,showNone:!0,onChange:_,isError:k,isLoading:C,items:j,value:i||"",title:"Model",type:"combobox"})}function fe(){return!o||R==="S3"||R==="API"||!d||d==="none"?null:e.jsx(Pe,{refetch:V,onChange:se,isError:P,isLoading:E,items:f,value:u||"",title:"Schema",type:"combobox"})}function Y(){function X(){let $=!1;return R==="API"?($=!1,$):((R==="S3"||o&&d&&d!=="none"&&u)&&($=!0),$)}return X()?e.jsx(Pe,{refetch:J,onChange:U,isError:F,items:T,isLoading:L,value:m||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:s.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!c}),children:[e.jsxs("section",{className:s.cn("px-4",{"px-4 pb-0 pt-4":a,"px-4 py-4":!a}),children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Direct Source"}),e.jsx(s.Button,{onClick:()=>r(!a),size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:a?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),!a&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Pe,{refetch:W,items:p,title:"Connection",value:o||"",onChange:H,isLoading:w,isError:v,type:"combobox",connectionTooltip:((Q=p==null?void 0:p.find(X=>X.id===o))==null?void 0:Q.type)||""}),xe(),pe(),me(),fe(),Y()]})]}),ae(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:n==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:h,onCheckedChange:re,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:le,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(ka,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function bt({error:t,errorSql:n,onSendFeedback:a,className:r,showFeedbackButton:l=!0}){const[o,c]=M.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-destructive/30 bg-destructive/5 p-4",r),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(s.CircleAlert,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-destructive"}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:"Query Error"}),e.jsxs("div",{className:"relative rounded-md bg-background/60 p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 h-6 w-6 z-10"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"font-mono text-xs text-foreground/80 break-all",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:o?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),l&&a&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:a,children:[e.jsx(Ia,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),n&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleContent,{className:"space-y-2",children:e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Error SQL Query"}),e.jsx(s.CopyButton,{text:n,className:"h-6 w-6"})]}),e.jsx("div",{className:"rounded-md bg-background/60 p-2 max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:n,language:"sql"})})]})})})]})]})})}function vt({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){const l=s.useEditorStore(u=>u.isDevMode),{setIsDevMode:o,setCardSql:c,setRunSql:i}=s.useEditorActions();function d(){o(!l),c(t),setTimeout(()=>{i(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-3",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[n&&e.jsx(bt,{error:n,errorSql:a,showFeedbackButton:!1}),!n&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!l&&t&&!n&&e.jsxs(s.Button,{onClick:d,variant:"secondary",size:"sm",children:[e.jsx(fa,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),n&&r&&e.jsxs(s.Button,{onClick:r,size:"sm",variant:"outline",children:[e.jsx(ya,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function yt({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:n?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:n?e.jsx(da,{className:"h-4 w-4 text-red-500"}):e.jsx(s.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(s.HoverCardContent,{align:"start",className:"flex w-[700px]",children:e.jsx(vt,{errorSql:a,sql:t,error:n,onDebugWithAssistant:r})})]})}function Vn(t){return s.GenIcon({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(t)}function Nt(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(p=>p.theme),r=s.useEditorStore(p=>p.frame),l=s.useEditorStore(p=>p.card),o=s.useEditorStore(p=>p.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(l),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),m=M.useRef(),h=M.useRef({}),x=r.cards.find(p=>p.id===o),g=M.useCallback(()=>{let p="";return t==="python"&&(p=(x==null?void 0:x.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(p=(x==null?void 0:x.sql)||""),p},[t,x]);M.useEffect(()=>{if(o&&l.id&&l.id!==o){if(m.current&&c){const p=m.current.getModel();p&&(h.current[l.id]=p);let j=h.current[o];if(!j){const f=g();j=c.editor.createModel(f,t),h.current[o]=j}m.current.setModel(j)}d(o,l),u(!0)}},[o,l,d,c,u,t,g]),M.useEffect(()=>{if(!c)return;const p=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",j=a==="system"?p:a;c.editor.defineTheme("default",{base:j==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":j==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[n,a,c]),M.useEffect(()=>{const p=m.current;p&&c&&l&&p.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function b(p,j){if(m.current=p,!h.current[l.id]){const f=p.getModel(),N=g();h.current[l.id]=f||(j==null?void 0:j.editor.createModel(N,t))||p.getModel()}p.setModel(h.current[l.id])}return{handleEditorDidMount:b}}function Un(){const t=s.useEditorStore(c=>c.card.sql),n=s.useEditorStore(c=>c.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=Nt("sql");function o(c){a(c),s.isObjectEmpty(n)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:o,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function Gn(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=Nt("python");function r(l){n(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:a})}function Yn({jsonString:t}){return e.jsx(s.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:t,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function Ds(t){const[n,a]=M.useState(null),[r,l]=M.useState(null);return M.useEffect(()=>{if(!t||t.trim()===""){a(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");a(()=>d.useChartStore),l(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),l(i),a(null)}})()},[t]),n}function $n(t){const n=t.toUpperCase().indexOf("WHERE"),a=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let o=t.length;if(l!==-1&&(o=l),r!==-1&&r<o&&(o=r),n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,o),i=t.substring(o);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function qn(t,n){if(t.length===0)return"";if(n){const a=t.find(r=>r.id===n);if(a){const r=a.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const o=r.split("__")[0],c=t.find(i=>i.tabTitle===o);return c?c.id:t[0].id}return n}}return t[0].id}async function Ys(t,n,a,r){if(!n||!a)throw new Error("Missing auth token or visual ID");const l=["resource-by-id","visual",a],o=r.getQueryData(l);if(o)return console.log("Using cached visual data for:",a),{data:o,fromCache:!0};console.log("Fetching visual data from network for:",a);const c=s.ue.loading("Loading visual...",{position:"top-center"});try{const i=await fetch(`${t}/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${n}`}});if(!i.ok)throw new Error("Failed to load visual");const d=await i.json();return r.setQueryData(l,d),s.ue.dismiss(c),{data:d,fromCache:!1}}catch(i){throw s.ue.dismiss(c),i}}function Hn(t,n,a,r,l){const o=t.frameObject;n(o);const c=o.cards.find(i=>i.id===o.activeCardId);c&&a(c),r(!0),l(!0)}function Wn(){var x;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(g=>g.frame),a=s.useEditorStore(g=>g.card),r=Ds(((x=a.customCardPreferences)==null?void 0:x.url)||""),l=s.useEditorStore(g=>g.selectedSchemaName),o=s.useEditorStore(g=>g.selectedDatamodelId),c=s.useEditorStore(g=>g.selectedDatabaseName),i=s.useEditorStore(g=>g.selectedTableName),d=s.useEditorStore(g=>g.selectedConnectionId),u=s.useEditorStore(g=>g.isShowingVisual),m=a.sql;return{getUpdatedFrame:M.useCallback(()=>{var f;let g=m;m&&!m.includes("{{")&&(g=$n(m),t(g));const b=(f=r==null?void 0:r.getState())==null?void 0:f.settings,p={...a,dataSource:a.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:o,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:g,customCfg:u?a.customCfg:null,preferences:a.preferences,...b&&{customCardPreferences:{...a.customCardPreferences,settings:b}}},j=n.cards.map(N=>N.id===a.id?p:N);return{...n,cards:j,activeCardId:qn(j,n.activeCardId)}},[a,n,u,l,o,c,i,d,t,r,m])}}function Ts(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient(),r=s.useSelectedVisual(),{selectVisual:l}=s.useManagementActions(),{setFrame:o,setCard:c}=s.useEditorActions(),{setIsDashboardEditing:i,setIsVisualEditing:d,setSelectedFrameId:u,addFrame:m,setIsDashboardPanelOpen:h}=s.useDashboardActions(),x=s.useDashboardStore(j=>j.selectedSheetId),g=s.useVisualById((r==null?void 0:r.id)||"",{enabled:!!(r!=null&&r.id)&&!!(t!=null&&t.accessToken)}),b=M.useCallback(async j=>{try{l(j);const{data:f,fromCache:N}=await Ys(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",j.id,a);return Hn(f,o,c,i,d),{success:!0,fromCache:N}}catch(f){return console.error("Error editing visual:",f),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,o,c,i,d]),p=M.useCallback(async j=>{try{if(l(j),!x)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:f,fromCache:N}=await Ys(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",j.id,a),T=f.frameObject;if(!T)return{success:!1,error:"Visual has no frame data"};const I={...T,id:s.v4()};return m(x,I,"end"),i(!0),u(I.id),h(!1),{success:!0,fromCache:N}}catch(f){return console.error("Error adding visual:",f),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,x,m,i,u,h]);return{visual:g.data,isLoading:g.isLoading,isError:g.isError,error:g.error,handleEditLibraryVisual:b,handleAddLibraryVisual:p,getUpdatedFrame:Wn().getUpdatedFrame,refetch:g.refetch}}function ks({variant:t="outline"}){var c;const{setCardSql:n}=s.useEditorActions();s.useEditorStore(i=>i.frame);const a=s.useEditorStore(i=>i.card);Ds(((c=a.customCardPreferences)==null?void 0:c.url)||""),s.useEditorStore(i=>i.selectedSchemaName),s.useEditorStore(i=>i.selectedDatamodelId),s.useEditorStore(i=>i.selectedDatabaseName),s.useEditorStore(i=>i.selectedTableName),s.useEditorStore(i=>i.selectedConnectionId),s.useEditorStore(i=>i.isShowingVisual),a.sql;const r=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:l}=Ts();function o(){const i=l();r==null||r(i)}return e.jsxs(s.Button,{onClick:o,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Kn(){const t=s.useQueryClient(),[n,a]=M.useState(!1),r=s.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{setIsVisualEditing:l}=s.useDashboardActions(),{getUpdatedFrame:o}=Ts(),c=s.useSelectedVisual(),i=s.useUpdateVisualMutation(),d=()=>{const u=o();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}a(!0),i.mutate({visualId:c.id,data:{frameObject:u}},{onSuccess:()=>{a(!1),l(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{a(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:d,className:"h-8",size:"sm",children:[n&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!n&&e.jsxs(e.Fragment,{children:[e.jsx(bs,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function Es(){const{setTempQueryData:t,setSqlGen:n}=s.useEditorActions(),a=s.useQueryClient(),r=s.useEditorStore(d=>d.tempQueryData),l=s.useEditorStore(d=>d.onClose),o=s.useEditorStore(d=>d.card),{queryKey:c}=s.useDashboardCardQuery(o);function i(){if(r){const{queryKey:d,queryData:u}=r;d&&u&&a.setQueryData(d,u)}n({}),l==null||l()}return e.jsxs(s.Button,{onClick:i,className:"h-8",size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function os(){const{setTempQueryData:t}=s.useEditorActions(),n=s.useQueryClient(),a=s.useEditorStore(j=>j.isDevMode),r=s.useEditorStore(j=>j.tempQueryData),l=s.useEditorStore(j=>j.card),{queryKey:o}=s.useDashboardCardQuery(l),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:u,setCardPreferences:m,updateDataSource:h,clearQueryConfig:x,setCardConfig:g,setCardType:b}=s.useEditorActions();function p(){const j=n.getQueryData(o);r!=null&&r.queryData||t({queryKey:o,queryData:j}),n.setQueryData(o,null),n.removeQueries({queryKey:o,exact:!0}),a&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),x(),g(void 0),d(""),u(""),m({}),b("bar")}return e.jsxs(s.Button,{onClick:p,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function Qn(){const t=s.useQueryClient(),[n,a]=M.useState(!1),[r,l]=M.useState(!1);s.useEditorStore(V=>V.frame);const o=s.useEditorStore(V=>V.card);s.useEditorStore(V=>V.isShowingVisual),s.useEditorStore(V=>V.selectedConnectionId),s.useEditorStore(V=>V.tempQueryData),s.useEditorStore(V=>V.selectedDatabaseName),s.useEditorStore(V=>V.selectedDatamodelId),s.useEditorStore(V=>V.selectedSchemaName);const c=s.useEditorStore(V=>V.showAIDialog);s.useEditorStore(V=>V.selectedTableName);const i=s.useEditorStore(V=>{var J;return(J=V==null?void 0:V.card)==null?void 0:J.sql}),d=s.useEditorStore(V=>{var J;return(J=V==null?void 0:V.card)==null?void 0:J.python}),{sheetFilterValues:u}=s.useSheetFilterValues(),{setCardCustomCfg:m,setQueryResultColumns:h,setCardSql:x,setTempQueryData:g,setPythonStdOut:b,setCardPreferences:p,setCardType:j,setCardPython:f,runAssistant:N,setShowAIDialog:T}=s.useEditorActions();s.useEditorStore(V=>V.onSave),s.useEditorStore(V=>V.onClose),s.useEditorStore(V=>V.actions.setSqlGen);const I=s.useEditorStore(V=>V.runSql),w=s.useEditorStore(V=>V.actions.setRunSql),C=s.useEditorStore(V=>V.actions.setIsSqlRunning),{data:v,isLoading:k,isFetching:y,isSuccess:O,isError:E,error:P,errorSql:D,queryKey:S,refetch:L,errorMessage:F}=s.useDashboardCardQuery(o);M.useEffect(()=>{if(v&&(v.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),b((v==null?void 0:v.output)||""),v.records.length>0)){const{dimensionKeys:V}=s.getKeys(v.records);h(V)}},[v,h,b]),M.useEffect(()=>{(k||y)&&C(!0),(E||O)&&C(!1),E&&(h([]),b(""))},[k,y,v,b,E,O,C,h,P]),M.useEffect(()=>{I&&(t.getQueryData(S)||L(),w(!1))},[I,L,w,S,t]);async function R(){const V=`Can you help me debug this query?
|
|
316
|
+
*/const Ya=s.createLucideIcon("View",[["path",{d:"M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2",key:"mrq65r"}],["path",{d:"M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2",key:"be3xqs"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);function $a(){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(Va,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(Aa,{strokeWidth:1.5,className:"absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),e.jsx("span",{className:"sr-only",children:"Toggle theme"})]})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuItem,{onClick:()=>{t("light"),n("light")},children:"Light"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("dark"),n("dark")},children:"Dark"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("system"),n("system")},children:"System"})]})]})}function ss(t){var n;return{...t,sheets:(n=t==null?void 0:t.sheets)==null?void 0:n.map(a=>{var r;return{...a,frames:(r=a.frames)==null?void 0:r.map(l=>{var o;return{...l,cards:(o=l.cards)==null?void 0:o.map(c=>rt(c))}})}})}}function rt(t){return{...t,customCfg:qa(t.customCfg),data:[]}}function qa(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 Ha(t,n,a,r,l){if(!l)return null;const o=JSON.stringify(a),c=`${t}/v1/lens`;return await s.postRequest(c,l,{name:n,template:o,filterValues:r,operation:"create"})}async function vs(t,n,a){if(!a)return null;const{id:r,template:l,filterValues:o,isDefault:c,shared:i}=n,d=`${t}/v1/lens`;return await s.postRequest(d,a,{lensId:r,template:l,filterValues:o,isDefault:c,shared:i,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 Ka(){const[t,n]=M.useState(""),[a,r]=M.useState(!1),l=s.useDashboardStore(j=>j.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=M.useState(!1),[u,m]=M.useState(!1),h=s.useDashboardStore(j=>j.dashboard),x=s.useDashboardStore(j=>j.filterValues),{authToken:g,tokenProps:b}=s.useSemaphorContext();async function p(){d(!0);const j=ss(h),f=await Ha(b.apiServiceUrl,t,j,x,g==null?void 0:g.accessToken);f&&(o([...l||[],f]),c(f.id),m(!1)),d(!1)}return e.jsxs(s.Dialog,{open:u,onOpenChange:m,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange: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:p,disabled:i,children:i?"Creating...":"Add"})})]})]})}function Qa(){const[t,n]=M.useState(!1),a=s.useDashboardStore(h=>h.lenses),r=s.useDashboardStore(h=>h.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c,tokenProps:i}=s.useSemaphorContext();async function d(h){o(h)}async function u(h){if(await Wa(i.apiServiceUrl,h,c==null?void 0:c.accessToken)){const g=a==null?void 0:a.filter(b=>b.id!==h);l(g||[]),o("original")}}async function m(h){const x=a==null?void 0:a.map(p=>p.id===h.id?{...p,isDefault:!h.isDefault}:{...p,isDefault:!1});l(x||[]);const g={...h,isDefault:!h.isDefault};await vs(i.apiServiceUrl,g,c==null?void 0:c.accessToken);const b=a==null?void 0:a.find(p=>p.isDefault);if(b&&b.id!==h.id){const p={...b,isDefault:!1};await vs(i.apiServiceUrl,p,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:n,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(va,{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:d,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),a==null?void 0:a.map(h=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:h.id,children:[e.jsx("p",{children:h.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:x=>{x.preventDefault(),m(h)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!h.isDefault,"text-green-500":h.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:x=>{x.preventDefault(),u(h.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},h.id))]})]})]})}function Ja({iconClassName:t}){const[n,a]=M.useState(!1),[r,l]=M.useState(""),[o,c]=M.useState(!1),i=s.useDashboardStore(h=>h.isDownloadingPdf),{tokenProps:d}=s.useSemaphorContext();async function u(){const h=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl),s.ue.dismiss(h),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(x){s.ue.dismiss(h),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",x)}}async function m(){if(!r)return;a(!1),l(""),c(!1);const h=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(d.apiServiceUrl,r),s.ue.dismiss(h),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(x){s.ue.dismiss(h),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",x)}}return e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:i,children:e.jsx(s.Download,{className:s.cn("size-4",t)})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsxs(s.DropdownMenuItem,{onClick:u,children:[e.jsx(s.File,{className:"mr-2 h-4 w-4"}),"Download PDF"]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>a(!0),children:[e.jsx(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:o?"text":"password",value:r,onChange:h=>l(h.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:h=>{h.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:()=>c(!o),children:o?e.jsx(s.EyeOff,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(s.Eye,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:m,disabled:!r,children:"Download"})]})]})})]})}function lt({triggerButtonClassName:t}){const[n,a]=M.useState(!1),r=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.id}),l=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.title}),o=s.useDashboardStore(i=>{var d;return(d=i.dashboard)==null?void 0:d.sheets}),c=s.useDashboardStore(i=>i.selectedSheetId);return o==null||o.find(i=>i.id===c),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 ts({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 Oe({currentRole:t,onRoleChange:n,roleOptions:a,disabled:r=!1,className:l="",allowDropdown:o=!0}){var d;const c=((d=a.find(u=>u.value===t))==null?void 0:d.label)||t,i=a.filter(u=>u.value!==t);return o?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${l}`,children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.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:c})}function ot({selectedUsers:t,selectedUserObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(o=>a(o.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.map(o=>{const c=t.find(d=>d.id===o.id),i=l(o.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[o.name,e.jsx(Oe,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(o.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>a(o.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},o.id)})}),e.jsx(s.Separator,{})]})}function it({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 ct({usersToUpdate:t,allUsers:n,onRemove:a,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),o=i=>{const d=n.find(u=>u.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=l.find(u=>u.value===i);return(d==null?void 0:d.label)||i};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(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(i=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:o(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>a(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function dt(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,l=M.useRef(null);return M.useEffect(()=>{const o=c=>{const i=c.target;l.current&&l.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,a,r]),l}function ye(t,n){var a;return((a=n.find(r=>r.value===t))==null?void 0:a.label)||t}function Xa(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function ut(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function Za(t,n,a){const r=ut(t),l=(a==null?void 0:a.type)||"organization";if(!(!n||!n.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in n.shares)return(n.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(n.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function en({user:t}){return ut(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 sn({user:t,userShare:n,usersToUpdate:a,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(n!=null&&n.role))return null;const c=Xa((r==null?void 0:r.type)||""),i=a.some(h=>h.id===t.id),d=a.find(h=>h.id===t.id),u=d?d.newRole:n==null?void 0:n.role,m=l(t.type);return n?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(Oe,{currentRole:u,onRoleChange:h=>{o(t.id,n.role,h)},roleOptions:m,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:ye(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function tn({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(Be,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function an({isUserRemoving:t,isSelected:n,hasAccess:a,isRemoving:r,isSharing:l}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),n&&!a&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:l?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Sharing..."]}):"Will share"})]})}function nn({existingShares:t,allUsers:n,getRoleOptions:a,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],d=c.specificTenantUsers||[],u=c.orgWide||[],m=c.orgUsersOnly||[],h=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((x,g)=>{var f,N;const b=((f=n.find(T=>T.id===x.orgUserId))==null?void 0:f.name)||"Unknown User",p=((N=n.find(T=>T.id===x.orgUserId))==null?void 0:N.type)||"",j=ye(x.role,a(p));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})]},g)}),i.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),d.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-green-600",children:["Specific Tenant Users (",d.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[d.slice(0,3).map((x,g)=>{var f,N;const b=((f=n.find(T=>T.id===x.tenantUserId))==null?void 0:f.name)||"Unknown User",p=((N=n.find(T=>T.id===x.tenantUserId))==null?void 0:N.type)||"",j=ye(x.role,a(p));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})]},g)}),d.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",d.length-3," more users"]})]})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-purple-600",children:"All Org Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:u.map((x,g)=>{const b=ye(x.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})]},g)})})]}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-orange-600",children:"Org Users Only"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:m.map((x,g)=>{const b=ye(x.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})]},g)})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:h.map((x,g)=>{const b=ye(x.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})]},g)})})]}),!i.length&&!d.length&&!u.length&&!m.length&&!h.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const c=t.shares.specificTenantUsers||[],i=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",c.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[c.slice(0,3).map((d,u)=>{var g,b;const m=((g=n.find(p=>p.id===d.tenantUserId))==null?void 0:g.name)||"Unknown User",h=((b=n.find(p=>p.id===d.tenantUserId))==null?void 0:b.type)||"",x=ye(d.role,a(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:x})]},u)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:i.map((d,u)=>{const m=ye(d.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)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const o=t.shares.specificTenantUsers||[],c=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",o.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[o.slice(0,3).map((i,d)=>{var x,g;const u=((x=n.find(b=>b.id===i.tenantUserId))==null?void 0:x.name)||"Unknown User",m=((g=n.find(b=>b.id===i.tenantUserId))==null?void 0:g.type)||"",h=ye(i.role,a(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),o.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,d)=>{const u=ye(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:u})]},d)})})]}),!o.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function rn({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 ln({user:t,userShare:n,isUserRemoving:a,hasAccess:r,hasAccessFromAPI:l,isSelected:o,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:h,handleUpdateAccess:x,handleUserRoleChange:g}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!a?"border border-green-200 bg-green-50":a?"border border-red-200 bg-red-50":o?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:l?!a:o,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{l?a?m(t.id):h(t.id):m(t.id)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:t.name}),e.jsx(en,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!a?e.jsx(Oe,{currentRole:n==null?void 0:n.role,onRoleChange:b=>x(t.id,n.role,b),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(sn,{user:t,userShare:n,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:x}),o&&!l&&e.jsx("div",{onClick:b=>b.stopPropagation(),children:e.jsx(Oe,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:b=>g(t.id,b),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(tn,{hasAccess:r,isUserRemoving:a,isSelected:o,hasAccessFromAPI:l}),e.jsx(an,{isUserRemoving:a,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function mt({existingShares:t,isInitialLoading:n,isSearching:a,getRoleOptions:r,allUsers:l=[],currentUser:o,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),x=s.useShareUsersToUpdate(),g=s.useShareSearchQuery(),b=s.useShareManagementActions(),p=c||(w=>{const C=m.some(k=>k.id===w),v=h.includes(w);C?b.removeSelectedUser(w):v?b.removeUserFromRemove(w):b.addSelectedUser({id:w,role:"VIEWER"})}),j=i||b.updateSelectedUserRole,f=d||b.addUserToRemove,N=u||((w,C,v)=>{b.addUserToUpdate({id:w,currentRole:C,newRole:v})}),T=l,I=h;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["All Users (",(T??[]).length,")"]}),e.jsx(s.TooltipProvider,{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(nn,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:o})})]})})]}),(T==null?void 0:T.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===T.length?b.setSelectedUsers([]):b.setSelectedUsers(T.map(w=>({id:w.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:m.length===T.length?"Deselect all":"Select all"})]}),e.jsxs("div",{className:"max-h-60 space-y-1 overflow-y-auto rounded-md border p-2",children:[e.jsx(rn,{isInitialLoading:n,isSearching:a,searchQuery:g,availableUsers:T||[]}),!n&&!a&&(T==null?void 0:T.length)>0&&T.map(w=>{const C=t?Za(w,t,o):void 0,v=I.includes(w.id),k=!!C,y=k&&!v,O=m.some(D=>D.id===w.id),E=m.find(D=>D.id===w.id),P=r(w.type);return e.jsx(ln,{user:w,userShare:C,isUserRemoving:v,hasAccess:y,hasAccessFromAPI:k,isSelected:O,selectedUser:E,roleOptions:P,currentUser:o,usersToUpdate:x,handleUserToggle:p,handleRemoveAccess:f,handleUpdateAccess:N,handleUserRoleChange:j},w.id)})]})]})}function Ss({shareType:t,onShareTypeChange:n,currentUser:a,options:r}){const l=(a==null?void 0:a.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:n,className:`grid grid-cols-${r.length} gap-4`,children:r.map(o=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:o.value,id:o.value,className:"peer sr-only",disabled:o.disabled}),e.jsxs(s.Label,{htmlFor:o.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${o.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[o.icon||e.jsx(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:o.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o.description})]})]})]},o.value))}),!l&&r.some(o=>o.value==="all_users")&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only admins, authors, power users, and super admins can share with all users."})]})}const be=()=>[{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 on({currentUser:t,currentShare:n,isSharing:a,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:o=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),u=be().filter(N=>N.value==="VIEWER"||N.value==="EDITOR"||N.value==="CONTRIBUTOR"),m=n.role!=="NONE"?n.role:"NONE",h=l?l.newRole:m,x=n.role!=="NONE"&&!o&&(!l||l.newRole===m),g=l!==null&&l.newRole!==m,b=o,p=m==="NONE"||!m,j=N=>{switch(N){case"VIEWER":return e.jsx(s.Eye,{className:"h-4 w-4"});case"EDITOR":return e.jsx(s.SquarePen,{className:"h-4 w-4"});case"CONTRIBUTOR":return e.jsx(Pa,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},f=N=>{r(m,N)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",g&&!b&&!p?"border-orange-300 bg-orange-50":x?"border-green-300 bg-green-50":b||p?"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"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="specificOrgUsers"?"Org":"Tenant"," ","Users",x&&e.jsx(s.Badge,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),g&&e.jsx(s.Badge,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(b||p)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:b||p?"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(N=>e.jsxs(s.Button,{variant:h===N.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>f(N.value),disabled:a||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[j(N.value),e.jsx("span",{className:"font-medium",children:N.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:N.description})]},N.value))})]})})]})})}function ht({currentUser:t,currentShare:n,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:o,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const u=p=>p==="OWNER"?"CONTRIBUTOR":p,h=n?{role:u(n.role)}:{role:"NONE"},x=i?{currentRole:u(i.currentRole),newRole:u(i.newRole)}:null,g=(p,j)=>{o(p,j)},b=()=>{c()};return e.jsx(on,{currentUser:t,currentShare:h,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:g,onRemoveAccess:b,allUsersToUpdate:x,allUsersToRemove:d})}function _e(t){const{debouncedSearchQuery:n,resourceId:a,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:o}=t,c=M.useMemo(()=>({search:n,active:!0,...l?{type:l}:{},...l==="tenant"&&o?{tenantId:o}:{}}),[n,l,o]),{users:i,isLoading:d,isError:u}=s.useUnifiedUsers(c),m=s.useResourceShares(r,a);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function cn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var J,Z;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),x=s.useShareSelectedUsers(),g=s.useShareUsersToRemove(),b=s.useShareUsersToUpdate(),p=s.useShareCurrentMode(),j=s.useShareOrgWideRole(),f=s.useShareManagementActions(),[N,T]=M.useState("specific_users"),I=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},w=()=>{if(i==="tenant"&&d)return d},{allUsers:C,existingShares:v,isLoadingUsers:k}=_e({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:I(),tenantId:w()});M.useEffect(()=>{f.setCurrentContext("org-tab"),f.setCurrentMode(N==="all_users"?"allOrgUsers":"specificOrgUsers")},[f,N]);const y=W=>{var G,se;const H=W;if(T(H),r==null||r(H),f.setCurrentContext("org-tab"),H==="specific_users")f.setCurrentMode("specificOrgUsers");else if(H==="all_users"){f.setCurrentMode("allOrgUsers");const _=(se=(G=v==null?void 0:v.shares)==null?void 0:G.orgUsersOnly)==null?void 0:se[0];_&&_.role!==void 0&&f.setOrgWideRole(_.role)}},O=C.filter(W=>W.name.toLowerCase().includes(u.toLowerCase())||W.email.toLowerCase().includes(u.toLowerCase())),E=C.filter(W=>x.some(H=>H.id===W.id)),P=W=>{var _,U;const H=x.some(ee=>ee.id===W),G=g.includes(W),se=(U=(_=v==null?void 0:v.shares)==null?void 0:_.specificOrgUsers)==null?void 0:U.some(ee=>ee.orgUserId===W);H?f.removeSelectedUser(W):G?f.removeUserFromRemove(W):se||f.addSelectedUser({id:W,role:"VIEWER"})},D=(W,H)=>{f.updateSelectedUserRole(W,H)},S=W=>{f.addUserToRemove(W),f.removeSelectedUser(W)},L=W=>{f.removeUserFromRemove(W)},F=W=>{f.removeUserFromUpdate(W)},R=(W,H)=>{f.setOrgWideRole(H)},A=()=>{f.setOrgWideRole((z==null?void 0:z.role)||"NONE")},z=(Z=(J=v==null?void 0:v.shares)==null?void 0:J.orgUsersOnly)==null?void 0:Z[0];M.useEffect(()=>{N==="all_users"&&z&&z.role!==void 0&&f.setOrgWideRole(z.role)},[N,z,f]);const q=k,V=!1;return a?e.jsxs(e.Fragment,{children:[e.jsx(Ss,{shareType:N,onShareTypeChange:y,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??"")}]}),N==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(ts,{value:u,onChange:m}),e.jsx(ot,{selectedUsers:x,selectedUserObjects:E,onRemove:P,onRoleChange:D,getRoleOptions:be}),e.jsx(it,{usersToRemove:g,allUsers:O,onRemove:L}),e.jsx(ct,{usersToUpdate:b,allUsers:O,onRemove:F,getRoleOptions:be}),e.jsx(mt,{existingShares:v,isInitialLoading:q,isSearching:V,resource:t,onShare:()=>{},getRoleOptions:be,allUsers:O,currentUser:a,handleUserToggle:P,handleUserRoleChange:D,handleRemoveAccess:S,handleUpdateAccess:(W,H,G)=>{f.addUserToUpdate({id:W,currentRole:H,newRole:G})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(ht,{currentUser:a,currentShare:z,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:R,onRemoveAccess:A,allUsersToUpdate:p==="allOrgUsers"&&j!==((z==null?void 0:z.role)||"NONE")?{currentRole:(z==null?void 0:z.role)||"NONE",newRole:j}:null,allUsersToRemove:p==="allOrgUsers"&&(z==null?void 0:z.role)===void 0})})]}):null}function dn(t){switch(t){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function un(t){switch(t){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function xt({groups:t,existingGroupShares:n,isLoading:a,resource:r,getRoleOptions:l,currentUser:o,handleGroupToggle:c,handleGroupRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),x=s.useShareGroupsToUpdate(),g=s.useShareManagementActions(),b=l(o==null?void 0:o.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(p=>{const j=n==null?void 0:n.find(v=>v.groupId===p.id),f=m.some(v=>v.id===p.id),N=h.includes(p.id),T=x.find(v=>v.id===p.id),I=!!j&&!N;let C=(j==null?void 0:j.role)||"VIEWER";if(f){const v=m.find(k=>k.id===p.id);C=(v==null?void 0:v.role)||"VIEWER"}else T&&(C=T.newRole);return e.jsxs("div",{className:s.cn("flex items-center justify-between rounded-lg p-2 transition-colors",I&&!N?"border border-green-200 bg-green-50":N?"border border-red-200 bg-red-50":f?"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-${p.id}`,checked:I?!N:f,disabled:!1,onCheckedChange:()=>{I?N?g.removeGroupFromRemove(p.id):d==null||d(p.id):c==null||c(p.id)}}),e.jsxs("label",{htmlFor:`group-${p.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:p.name}),p.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:[p.memberCount," members"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:s.cn("text-xs",un(p.type)),children:dn(p.type)}),p.type==="TENANT_GROUP"&&p.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",p.tenantName]})]}),p.description&&e.jsx("span",{className:"text-xs text-muted-foreground",children:p.description})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[I&&!N?e.jsx(Oe,{currentRole:C,onRoleChange:v=>{j&&v!==j.role&&(u==null||u(p.id,j.role,v))},roleOptions:b,disabled:!1,allowDropdown:!0,className:T?"border-orange-300 bg-orange-100":""}):f&&!I&&e.jsx(Oe,{currentRole:C,onRoleChange:v=>i==null?void 0:i(p.id,v),roleOptions:b,disabled:!1}),I&&!N&&!T&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>d==null?void 0:d(p.id),children:e.jsx(s.X,{className:"h-4 w-4"})}),N&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromRemove(p.id),children:"Undo"}),T&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromUpdate(p.id),children:"Cancel"})]})]},p.id)})})]})}function pt({selectedGroups:t,groupObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:l}){if(t.length===0)return null;const o=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(c=>{const i=n.find(d=>d.id===c.id);return i?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:[i.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:i.name}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[i.memberCount," members"]}),i.type==="TENANT_GROUP"&&i.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",i.tenantName]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oe,{currentRole:c.role,onRoleChange:d=>r(c.id,d),roleOptions:o}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>a(c.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})]},c.id):null})})]})}function Us({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var fe;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),x=s.useShareUsersToUpdate(),g=s.useShareSelectedGroups(),b=s.useShareGroupsToRemove(),p=s.useShareGroupsToUpdate(),j=s.useShareCurrentMode(),f=s.useShareTenantWideRole(),N=s.useShareAllTenantsRole(),T=s.useShareSelectedTenant(),I=s.useShareManagementActions(),{data:w,isLoading:C}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"}),{groups:v,isLoading:k}=s.useShareableGroups("tenant",(a==null?void 0:a.tenantId)||T),[y,O]=M.useState((a==null?void 0:a.type)==="organization"?"all_tenants":"specific_tenant_users");M.useEffect(()=>{(a==null?void 0:a.type)==="tenant"?(I.setCurrentContext("tenant-dialog"),I.setCurrentMode("specificTenantUsers")):(I.setCurrentContext("tenant-tab"),I.setCurrentMode("allTenants"))},[I,a==null?void 0:a.type]);const E=Y=>{var X,$,te,ie;O(Y);let Q;if(Y==="specific_tenant_users"?Q="specific_users":Y==="all_tenant_users"||Y==="all_tenants"?Q="all_users":Y==="groups"?Q="groups":Q="specific_users",r==null||r(Q),Y==="groups"?(I.setCurrentContext("group-share"),I.setCurrentMode("specificGroups")):(a==null?void 0:a.type)==="tenant"?(I.setCurrentContext("tenant-dialog"),Y==="specific_tenant_users"?I.setCurrentMode("specificTenantUsers"):Y==="all_tenant_users"&&(I.setCurrentMode("allTenantUsers"),a!=null&&a.tenantId&&I.setSelectedTenant(a.tenantId))):(I.setCurrentContext("tenant-tab"),Y==="specific_tenant_users"?I.setCurrentMode("specificTenantUsers"):Y==="all_tenant_users"?I.setCurrentMode("allTenantUsers"):Y==="all_tenants"&&I.setCurrentMode("allTenants")),Y==="all_tenant_users"){const ce=($=(X=S==null?void 0:S.shares)==null?void 0:X.tenantWide)==null?void 0:$[0];ce&&ce.role!==void 0&&I.setTenantWideRole(ce.role)}else if(Y==="all_tenants"){const ce=(ie=(te=S==null?void 0:S.shares)==null?void 0:te.allTenantsOnly)==null?void 0:ie[0];ce&&ce.role!==void 0&&I.setAllTenantsRole(ce.role)}},P=Y=>{I.setSelectedTenant(Y)},{allUsers:D,existingShares:S,isLoadingUsers:L,isErrorLoadingUsers:F,isLoadingShares:R,isErrorLoadingShares:A}=_e({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant",tenantId:(a==null?void 0:a.type)==="tenant"?a.tenantId:T}),z=Y=>{var te,ie;const Q=m.some(ce=>ce.id===Y),X=h.includes(Y),$=(ie=(te=S==null?void 0:S.shares)==null?void 0:te.specificTenantUsers)==null?void 0:ie.some(ce=>ce.tenantUserId===Y);Q?I.removeSelectedUser(Y):X?I.removeUserFromRemove(Y):$||I.addSelectedUser({id:Y,role:"VIEWER"})},q=(Y,Q)=>{I.updateSelectedUserRole(Y,Q)},V=Y=>{I.addUserToRemove(Y),I.removeSelectedUser(Y)},J=Y=>{I.removeUserFromRemove(Y)},Z=Y=>{I.removeUserFromUpdate(Y)},W=(Y,Q,X)=>{I.addUserToUpdate({id:Y,currentRole:Q,newRole:X})},H=(Y,Q)=>{y==="all_tenant_users"?I.setTenantWideRole(Q):y==="all_tenants"&&I.setAllTenantsRole(Q)},G=()=>{y==="all_tenant_users"?I.setTenantWideRole("VIEWER"):y==="all_tenants"&&I.setAllTenantsRole("VIEWER")},_=(()=>{var Y,Q,X,$;return j==="allTenants"?(Q=(Y=S==null?void 0:S.shares)==null?void 0:Y.allTenantsOnly)==null?void 0:Q[0]:j==="allTenantUsers"?($=(X=S==null?void 0:S.shares)==null?void 0:X.tenantWide)==null?void 0:$[0]:null})();M.useEffect(()=>{var Y,Q,X,$;if(y==="all_tenant_users"){const te=(Q=(Y=S==null?void 0:S.shares)==null?void 0:Y.tenantWide)==null?void 0:Q[0];te&&te.role!==void 0&&I.setTenantWideRole(te.role)}else if(y==="all_tenants"){const te=($=(X=S==null?void 0:S.shares)==null?void 0:X.allTenantsOnly)==null?void 0:$[0];te&&te.role!==void 0&&I.setAllTenantsRole(te.role)}},[y,S,I]);const U=D.filter(Y=>m.some(Q=>Q.id===Y.id)),ee=Y=>{const Q=g.some(te=>te.id===Y),X=b.includes(Y),$=re==null?void 0:re.some(te=>te.groupId===Y);Q?I.removeSelectedGroup(Y):X?I.removeGroupFromRemove(Y):$||I.addSelectedGroup({id:Y,role:"VIEWER"})},ne=(Y,Q)=>{I.updateSelectedGroupRole(Y,Q)},oe=Y=>{I.addGroupToRemove(Y),I.removeSelectedGroup(Y)},B=(Y,Q,X)=>{I.addGroupToUpdate({id:Y,currentRole:Q,newRole:X})},ae=v.filter(Y=>g.some(Q=>Q.id===Y.id)),le=M.useMemo(()=>y!=="groups"?[]:v.filter(Y=>Y.type!=="TENANT_GROUP"?!1:Y.name.toLowerCase().includes(i.toLowerCase())||Y.description&&Y.description.toLowerCase().includes(i.toLowerCase())),[v,y,i]),re=M.useMemo(()=>{var Q,X;const Y=((Q=S==null?void 0:S.shares)==null?void 0:Q.specificGroups)||((X=S==null?void 0:S.shares)==null?void 0:X.groups)||[];return!Y||Y.length===0?[]:Y.filter($=>{const te=v.find(ie=>ie.id===$.groupId);return(te==null?void 0:te.type)==="TENANT_GROUP"})},[S,v]),xe=L||R||y==="groups"&&k,pe=F||A,me=()=>(a==null?void 0:a.type)==="tenant"||y==="all_tenants"||y==="groups"?!0:T&&(y==="specific_tenant_users"||y==="all_tenant_users");return e.jsxs(e.Fragment,{children:[pe&&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"})]})}),!pe&&a&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(Ss,{shareType:y,onShareTypeChange:E,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(zs,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"all_tenant_users",label:"Specific Tenant",description:"Share with all users of a specific tenant",icon:e.jsx(s.House,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"specific_tenant_users",label:"Specific Tenant User",description:"Share with users of a specific tenant",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(a==null?void 0:a.type)==="organization"&&(y==="specific_tenant_users"||y==="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:T||"",onValueChange:P,disabled:C,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:C?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(fe=w==null?void 0:w.tenants)==null?void 0:fe.map(Y=>e.jsx(s.SelectItem,{value:Y.id,children:Y.name},Y.id))})]})]}),me()?e.jsx(e.Fragment,{children:y==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(ts,{value:i,onChange:u}),e.jsx(ot,{selectedUsers:m,selectedUserObjects:U,onRemove:Y=>z(Y),onRoleChange:q,getRoleOptions:be}),e.jsx(it,{usersToRemove:h,allUsers:D,onRemove:J}),e.jsx(ct,{usersToUpdate:x,allUsers:D,onRemove:Z,getRoleOptions:be}),e.jsx(mt,{existingShares:S,isInitialLoading:!!xe,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:be,allUsers:D,currentUser:a,handleUserToggle:z,handleUserRoleChange:q,handleRemoveAccess:V,handleUpdateAccess:W})]}):y==="groups"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(ts,{value:i,onChange:u,placeholder:"Search groups..."}),e.jsx(pt,{selectedGroups:g,groupObjects:ae,onRemove:ee,onRoleChange:ne,getRoleOptions:be}),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"})]}),p.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 (",p.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(xt,{groups:le,existingGroupShares:re,isLoading:k,resource:t,getRoleOptions:be,currentUser:a,handleGroupToggle:ee,handleGroupRoleChange:ne,handleRemoveAccess:oe,handleUpdateAccess:B})]}):y==="all_tenant_users"||y==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(ht,{currentUser:a,currentShare:_,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:H,onRemoveAccess:G,allUsersToUpdate:j==="allTenantUsers"&&((_==null?void 0:_.role)===void 0||f!==_.role)||j==="allTenants"&&((_==null?void 0:_.role)===void 0||N!==_.role)?{currentRole:(_==null?void 0:_.role)||"VIEWER",newRole:j==="allTenantUsers"?f:N}:null,allUsersToRemove:j==="allTenantUsers"&&(_==null?void 0:_.role)===void 0||j==="allTenants"&&(_==null?void 0:_.role)===void 0})}):null}):(a==null?void 0:a.type)==="organization"&&(y==="specific_tenant_users"||y==="all_tenant_users")&&e.jsx("div",{className:"mt-6 flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(zs,{className:"mx-auto mb-2 h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant to continue"})]})})]})]})}function mn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var F,R;const{searchQuery:i,setSearchQuery:d}=s.useShareSearchWithDebounce(),u=s.useShareSelectedGroups(),m=s.useShareGroupsToRemove(),h=s.useShareGroupsToUpdate(),x=s.useShareManagementActions(),[g,b]=M.useState("org_groups"),[p,j]=M.useState(""),{data:f,isLoading:N}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"&&g==="tenant_groups"}),T=Array.isArray(f)?f:(f==null?void 0:f.tenants)||[],I=()=>{if((a==null?void 0:a.type)==="organization")return"organization";if((a==null?void 0:a.type)==="tenant")return"tenant"},{groups:w,isLoading:C}=s.useShareableGroups(I(),g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"?p:a==null?void 0:a.tenantId),{existingShares:v}=_e({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n}),k=w.filter(A=>g==="org_groups"&&A.type!=="ORG_GROUP"||g==="tenant_groups"&&A.type!=="TENANT_GROUP"||g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&(!p||A.tenantId&&A.tenantId!==p)?!1:A.name.toLowerCase().includes(i.toLowerCase())||A.description&&A.description.toLowerCase().includes(i.toLowerCase())),y=((F=v==null?void 0:v.shares)==null?void 0:F.specificGroups)||((R=v==null?void 0:v.shares)==null?void 0:R.groups)||[];M.useEffect(()=>{x.setCurrentContext("group-share"),x.setCurrentMode("specificGroups")},[x]);const O=A=>{const z=A;b(z),z==="org_groups"&&j(""),r==null||r(z==="org_groups"?"specific_groups":"all_groups"),x.setCurrentContext("group-share"),x.setCurrentMode("specificGroups")},E=w.filter(A=>u.some(z=>z.id===A.id)),P=A=>{const z=u.some(J=>J.id===A),q=m.includes(A),V=y==null?void 0:y.some(J=>J.groupId===A);z?x.removeSelectedGroup(A):q?x.removeGroupFromRemove(A):V||x.addSelectedGroup({id:A,role:"VIEWER"})},D=(A,z)=>{x.updateSelectedGroupRole(A,z)},S=A=>{x.addGroupToRemove(A),x.removeSelectedGroup(A)},L=(A,z,q)=>{x.addGroupToUpdate({id:A,currentRole:z,newRole:q})};return a?e.jsxs(e.Fragment,{children:[e.jsx(Ss,{shareType:g,onShareTypeChange:O,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"})}]}),g==="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:p,onValueChange:j,disabled:N,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:N?"Loading tenants...":"Select a tenant to view its groups"})}),e.jsx(s.SelectContent,{className:"z-[51]",children:T.map(A=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:A.id,children:A.name},A.id))})]})]}),e.jsx("div",{className:"mt-3 space-y-2",children:g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&!p?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(ts,{value:i,onChange:d,placeholder:"Search groups..."}),e.jsx(pt,{selectedGroups:u,groupObjects:E,onRemove:P,onRoleChange:D,getRoleOptions:be}),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"})]}),h.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 (",h.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(xt,{groups:k,existingGroupShares:y,isLoading:C,resource:t,getRoleOptions:be,currentUser:a,handleGroupToggle:P,handleGroupRoleChange:D,handleRemoveAccess:S,handleUpdateAccess:L})]})})]}):null}const ft=()=>{const t=s.useShareCurrentContext(),n=s.useShareCurrentMode(),a=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),o=s.useShareSelectedGroups(),c=s.useShareGroupsToRemove(),i=s.useShareGroupsToUpdate(),d=s.useShareSelectedTenant(),u=s.useShareOrgWideRole(),m=s.useShareAllTenantsRole(),h=s.useShareTenantWideRole(),x=s.useShareGroupWideRole(),g=M.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedGroups:o,groupsToRemove:c,groupsToUpdate:i,selectedTenant:d,orgWideRole:u,allTenantsRole:m,tenantWideRole:h}),[t,n,a,r,l,o,c,i,d,u,m,h,x]),b=M.useMemo(()=>j=>s.validateShareData(j),[]),p=M.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(!d)return!1}else if(n==="specificTenantUsers")return d?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"?o.length>0||c.length>0||i.length>0:!0}return!1},[t,n,a,r,l,o,c,i,d]);return{buildShareData:g,validateShareData:b,isCurrentStateValid:p,currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:l,selectedTenant:d,orgWideRole:u,allTenantsRole:m,tenantWideRole:h}};function Gs({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),x=s.useShareUsersToUpdate(),g=s.useShareSelectedTenant(),b=s.useShareOrgWideRole(),p=s.useShareAllTenantsRole(),j=s.useShareTenantWideRole(),{buildShareData:f,validateShareData:N,isCurrentStateValid:T}=ft(),I=a||r||l,w=()=>{var O,E,P,D;if(I)return"Updating...";if(i==="specific_users"){if(m.length===0&&h.length===0&&x.length===0)return"Select users to share with";const S=m.length+h.length+x.length;return S===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${S} user${S!==1?"s":""}`:h.length>0&&m.length===0&&x.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&x.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:x.length>0&&m.length===0&&h.length===0?`Update access for ${x.length} user${x.length!==1?"s":""}`:`Update access for ${S} user${S!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const S=d.role;return b===S?"Remove Access":"Update Access"}else if(i==="all_tenants"){const S=(E=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:E[0];if(!S||S.role===void 0)return"Share with All Tenants";const L=S.role;return p===L?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const S=(D=(P=n==null?void 0:n.shares)==null?void 0:P.tenantWide)==null?void 0:D[0];if(!S||S.role===void 0)return"Share with All Tenant Users";const L=S.role;return j===L?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(m.length===0&&h.length===0&&x.length===0)return"Select users to share with";const S=m.length+h.length+x.length;return S===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${S} user${S!==1?"s":""}`:h.length>0&&m.length===0&&x.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&x.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:x.length>0&&m.length===0&&h.length===0?`Update access for ${x.length} user${x.length!==1?"s":""}`:`Update access for ${S} user${S!==1?"s":""}`}return"Share"},C=()=>I||!t||i==="all_tenant_users"&&!g||i==="specific_tenant_users"&&!g?!0:!T,v=()=>{const O=f();O&&N(O)&&o(O)},k=()=>{var O,E,P,D;if(i==="all_users")if(!d||d.role===void 0){const S=f();S&&N(S)&&o(S)}else{const S=d.role;if(b===S)u==null||u();else{const F=f();if(F&&N(F)){const R={...F,updateAccess:!0};o(R)}}}else if(i==="all_tenants"){const S=(E=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:E[0];if(!S||S.role===void 0){const L=f();L&&N(L)&&o(L)}else{const L=S.role;if(p===L)u==null||u();else{const R=f();if(R&&N(R)){const A={...R,updateAccess:!0};o(A)}}}}else if(i==="all_tenant_users"){const S=(D=(P=n==null?void 0:n.shares)==null?void 0:P.tenantWide)==null?void 0:D[0];if(!S||S.role===void 0){const L=f();L&&N(L)&&o(L)}else{const L=S.role;if(j===L)u==null||u();else{const R=f();if(R&&N(R)){const A={...R,updateAccess:!0};o(A)}}}}},y=()=>{var O,E,P,D;if(i==="all_users"){if(!d||d.role===void 0)return"default";const S=d.role;return b===S?"destructive":"default"}else if(i==="all_tenants"){const S=(E=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:E[0];if(!S||S.role===void 0)return"default";const L=S.role;return p===L?"destructive":"default"}else if(i==="all_tenant_users"){const S=(D=(P=n==null?void 0:n.shares)==null?void 0:P.tenantWide)==null?void 0:D[0];if(!S||S.role===void 0)return"default";const L=S.role;return j===L?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:I,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||h.length>0||x.length>0)&&e.jsxs(s.Button,{onClick:v,disabled:!t||I,variant:"default",children:[I?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Be,{className:"mr-2 h-4 w-4"}),!I&&w()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:k,disabled:C(),variant:y(),children:[I?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"}),!I&&w()]})]})}function hn({resource:t,isSharing:n,isRemoving:a,isUpdating:r,onShare:l,onClose:o,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate(),h=s.useShareSelectedGroups(),x=s.useShareGroupsToRemove(),g=s.useShareGroupsToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const b=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:p,validateShareData:j,isCurrentStateValid:f}=ft(),N=n||a||r,T=()=>{if(N)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&m.length===0)return"Select users to share with";const y=d.length+u.length+m.length;return y===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${y} user${y!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:d.length>0&&u.length===0&&m.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${y} user${y!==1?"s":""}`}else if(c==="groups"){if(h.length===0&&x.length===0&&g.length===0)return"Select groups to share with";const y=h.length+x.length+g.length;return y===0?"Select groups to share with":h.length>0&&x.length>0?`Update access for ${y} group${y!==1?"s":""}`:x.length>0&&h.length===0&&g.length===0?`Remove access for ${x.length} group${x.length!==1?"s":""}`:h.length>0&&x.length===0&&g.length===0?`Share with ${h.length} group${h.length!==1?"s":""}`:g.length>0&&h.length===0&&x.length===0?`Update access for ${g.length} group${g.length!==1?"s":""}`:`Update access for ${y} group${y!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const y=i.role;return b===y?"Remove Access":"Update Access"}return"Share"},I=()=>N||!t?!0:!f,w=()=>{const y=p();y&&j(y)&&l(y)},C=()=>{const y=p();y&&j(y)&&l(y)},v=()=>{if(!i||i.role==="NONE"){const y=p();y&&j(y)&&l(y)}else{const y=i.role;if(b===y){const E=p();if(E&&j(E)){const P={...E,removeAccess:!0};l(P)}}else{const E=p();if(E&&j(E)){const P={...E,updateAccess:!0};l(P)}}}},k=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:o,disabled:N,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:w,disabled:!t||N,variant:"default",children:[N?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Be,{className:"mr-2 h-4 w-4"}),!N&&T()]})}),c==="groups"&&e.jsx(e.Fragment,{children:(h.length>0||x.length>0||g.length>0)&&e.jsxs(s.Button,{onClick:C,disabled:!t||N,variant:"default",children:[N?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Be,{className:"mr-2 h-4 w-4"}),!N&&T()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:v,disabled:I(),variant:k(),children:[N?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Be,{className:"mr-2 h-4 w-4"}),!N&&T()]})]})}function xn({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllGroupsShare:d,onRemoveAccess:u}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),x=s.useShareGroupsToUpdate();s.useShareGroupWideRole(),s.useShareCurrentMode();const g=()=>{o({context:"group-share",mode:"specificGroups",selectedGroups:m,groupsToRemove:h,groupsToUpdate:x})},b=()=>m.length>0||h.length>0||x.length>0,p=()=>h.length>0&&m.length===0&&x.length===0?"Remove Access":x.length>0&&m.length===0&&h.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"]}),h.length>0&&e.jsxs("span",{className:"ml-2 text-destructive",children:["• ",h.length," to remove"]}),x.length>0&&e.jsxs("span",{className:"ml-2 text-orange-600",children:["• ",x.length," to update"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:j,children:"Cancel"}),e.jsxs(s.Button,{onClick:g,disabled:!b()||j,children:[j&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),p()]})]})]})}function je(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Se(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function pn(t,n,a){const{resourceType:r,resourceId:l,shareMutation:o,removeMutation:c,existingShares:i,resetUserSelections:d}=n;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const u=je(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const x=je(r,l,u.map(g=>({scope:"specific_org_user",orgUserId:g.id,role:g.role})));o(x,{onSuccess:()=>{d()}})}if(m&&m.length>0){const x=Se(r,l,m.map(g=>{var p,j;const b=(j=(p=i==null?void 0:i.shares)==null?void 0:p.specificOrgUsers)==null?void 0:j.find(f=>f.orgUserId===g);return{scope:"specific_org_user",orgUserId:g,role:(b==null?void 0:b.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(x=>{const g=je(r,l,[{scope:"specific_org_user",orgUserId:x.id,role:x.newRole}]);o(g,{onSuccess:()=>{d()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const u=je(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="allTenantUsers"){const u=je(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h,tenantId:x}=t;if(m&&m.length>0){const g=Se(r,l,m.map(b=>{var j,f;const p=(f=(j=i==null?void 0:i.shares)==null?void 0:j.specificTenantUsers)==null?void 0:f.find(N=>N.tenantUserId===b);return{scope:"specific_tenant_user",tenantUserId:b,tenantId:x,role:(p==null?void 0:p.role)||"VIEWER"}}));c(g,{onSuccess:()=>{d()}})}if(h&&h.length>0&&h.forEach(g=>{const b=je(r,l,[{scope:"specific_tenant_user",tenantUserId:g.id,tenantId:x,role:g.newRole}]);o(b,{onSuccess:()=>{d()}})}),u&&u.length>0){const g=je(r,l,u.map(b=>({scope:"specific_tenant_user",tenantUserId:b.id,tenantId:x,role:b.role})));o(g,{onSuccess:()=>{d()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const u=Se(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);c(u,{onSuccess:()=>{d()}})}else if(t.updateAccess){const u=je(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else{const u=je(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const x=je(r,l,u.map(g=>({scope:"specific_tenant_user",tenantUserId:g.id,role:g.role})));o(x,{onSuccess:()=>{d()}})}if(m&&m.length>0){const x=Se(r,l,m.map(g=>{var p,j;const b=(j=(p=i==null?void 0:i.shares)==null?void 0:p.specificTenantUsers)==null?void 0:j.find(f=>f.tenantUserId===g);return{scope:"specific_tenant_user",tenantUserId:g,role:(b==null?void 0:b.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(x=>{const g=je(r,l,[{scope:"specific_tenant_user",tenantUserId:x.id,role:x.newRole}]);o(g,{onSuccess:()=>{d()}})})}break;case"group-share":if(t.mode==="specificGroups"){const{selectedGroups:u,groupsToRemove:m,groupsToUpdate:h}=t;if(u&&u.length>0){const x=je(r,l,u.map(g=>({scope:"group",groupId:g.id,role:g.role})));o(x,{onSuccess:()=>{var g;d(),(g=n.resetGroupSelections)==null||g.call(n),s.ue.success(`Shared with ${u.length} group${u.length!==1?"s":""}`)}})}if(m&&m.length>0){const x=Se(r,l,m.map(g=>({scope:"group",groupId:g,role:"VIEWER"})));c(x,{onSuccess:()=>{var g;d(),(g=n.resetGroupSelections)==null||g.call(n),s.ue.success(`Removed access from ${m.length} group${m.length!==1?"s":""}`)}})}h&&h.length>0&&h.forEach(x=>{const g=je(r,l,[{scope:"group",groupId:x.id,role:x.newRole}]);o(g,{onSuccess:()=>{var b;d(),(b=n.resetGroupSelections)==null||b.call(n),s.ue.success("Updated access for group")}})})}break}}function fn(t,n,a,r){var u,m,h,x,g,b;const{resourceType:l,resourceId:o,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(o)if(t.length>0){const p=Se(l,o,t.map(j=>{var N,T;const f=(T=(N=i==null?void 0:i.shares)==null?void 0:N.specificTenantUsers)==null?void 0:T.find(I=>I.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,role:(f==null?void 0:f.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()},onError:j=>{console.error("Remove access failed:",j)}})}else{const p=n==="tenant"&&a==="allTenants",j=n==="tenant"&&a==="allTenantUsers";if(p){const f=(m=(u=i==null?void 0:i.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(f){const N=Se(l,o,[{scope:"all_tenants_only",role:f.role}]);c(N,{onSuccess:()=>{d()},onError:T=>{console.error("Remove all-tenants access failed:",T)}})}}else if(j){const f=(x=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:x[0];if(f){const N=Se(l,o,[{scope:"all_tenant_users",role:f.role}]);c(N,{onSuccess:()=>{d()},onError:T=>{console.error("Remove all-tenant-users access failed:",T)}})}}else{const f=(b=(g=i==null?void 0:i.shares)==null?void 0:g.orgUsersOnly)==null?void 0:b[0];if(f){const N=Se(l,o,[{scope:"org_users_only",role:f.role}]);c(N,{onSuccess:()=>{d()},onError:T=>{console.error("Remove org-wide access failed:",T)}})}}}}function gn(t,n,a){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=s.useCurrentUserInfo(),{existingShares:d}=_e({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),u=M.useCallback(()=>{r.resetUserSelections()},[r]),m=M.useCallback(()=>{r.resetGroupSelections()},[r]),h=M.useCallback(g=>{if(!t)return;const b={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:n,removeMutation:a,existingShares:d,resetUserSelections:u,resetGroupSelections:m};pn(g,b,i)},[t,n,a,d,u,m,i]),x=M.useCallback(()=>{if(!t)return;const g={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:a,existingShares:d,resetUserSelections:u};fn(l,o||"",c||"",g)},[t,n,a,d,u,m,l,o,c]);return{handleShareSubmit:h,handleRemoveAccess:x}}function ls({resource:t,resourceType:n,onClose:a,onShareSuccess:r,onRemoveSuccess:l}){var D,S,L,F,R,A,z,q;const{currentUser:o}=s.useCurrentUserInfo(),[c,i]=M.useState("specific_users"),[d,u]=M.useState("specific_users"),[m,h]=M.useState("specific_groups"),x=s.useShareManagementActions(),g=s.useShareSelectedTab(),b=s.useShareCurrentMode(),p=s.useShareResource(),j=s.useRemoveResourceShares(),{handleShareSubmit:f,handleRemoveAccess:N}=gn(t.id,(V,J)=>{p.mutate(V,{...J,onSuccess:()=>{var Z;(Z=J==null?void 0:J.onSuccess)==null||Z.call(J),r==null||r()}})},(V,J)=>{j.mutate(V,{...J,onSuccess:()=>{var Z;(Z=J==null?void 0:J.onSuccess)==null||Z.call(J),l==null||l()}})}),T=p.isPending,I=j.isPending,w=p.isPending,{existingShares:C}=_e({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant"}),{existingShares:v}=_e({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"organization"}),k=(S=(D=C==null?void 0:C.shares)==null?void 0:D.tenantWide)==null?void 0:S[0],y=(F=(L=v==null?void 0:v.shares)==null?void 0:L.orgUsersOnly)==null?void 0:F[0],O=()=>{if(g==="org")return d;switch(b){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},E=M.useCallback(()=>{x.resetShareState(),a()},[x,a]),P=(o==null?void 0:o.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:E,children:e.jsxs(s.DialogContent,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Be,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:P?"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."})]}),P?e.jsxs(s.Tabs,{value:g,onValueChange:V=>{const J=V;x.setSelectedTab(J),x.resetUserSelections(),x.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(cn,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:u,isSharing:T,isUpdating:w,isRemoving:I})})}),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(Us,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:V=>i(V),isSharing:T,isUpdating:w,isRemoving:I})})}),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(mn,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:h,isSharing:T,isUpdating:w,isRemoving:I})})})]}):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(Us,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:V=>i(V),isSharing:T,isUpdating:w,isRemoving:I})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:P?g==="org"?e.jsx(Gs,{resource:t,existingShares:v,isSharing:T,isRemoving:I,isUpdating:w,onShare:f,onClose:a,shareTabType:d,currentAllUsersShare:y,onRemoveAccess:N}):g==="tenant"?e.jsx(Gs,{resource:t,existingShares:C,isSharing:T,isRemoving:I,isUpdating:w,onShare:f,onClose:a,shareTabType:O(),currentAllUsersShare:k,onRemoveAccess:N}):e.jsx(xn,{resource:t,existingShares:v,isSharing:T,isRemoving:I,isUpdating:w,onShare:f,onClose:a,shareTabType:m,currentAllGroupsShare:(o==null?void 0:o.type)==="organization"?(A=(R=v==null?void 0:v.shares)==null?void 0:R.allOrgGroups)==null?void 0:A[0]:(q=(z=C==null?void 0:C.shares)==null?void 0:z.allTenantGroups)==null?void 0:q[0],onRemoveAccess:N}):e.jsx(hn,{resource:t,isSharing:T,isRemoving:I,isUpdating:w,onShare:f,onClose:a,shareTabType:c,currentAllUsersShare:k,onRemoveAccess:N})})]})})}const jn=async(t,n,a)=>{const r=`${t}/management/v1/groups`;return await s.postRequestRegular(r,n,a)},bn=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 o=await l.text();throw new Error(o||"Failed to delete group")}},vn=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`;return await s.postRequestRegular(l,n,r)},yn=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`,o=await fetch(l,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)});if(!o.ok){const c=await o.text();throw new Error(c||"Failed to remove group members")}};function Nn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>jn(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 Cn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>bn(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 Sn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>vn(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 wn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>yn(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 Dn({onSuccess:t,tenantId:n,isTenantUser:a}){const[r,l]=M.useState(""),[o,c]=M.useState(""),[i,d]=M.useState({}),u=Nn(),m=()=>{const x={};return r.trim()?r.length<3?x.name="Group name must be at least 3 characters":r.length>50&&(x.name="Group name must be less than 50 characters"):x.name="Group name is required",o&&o.length>200&&(x.description="Description must be less than 200 characters"),d(x),Object.keys(x).length===0},h=async x=>{if(x.preventDefault(),!m())return;const g={name:r.trim(),description:o.trim()||void 0,type:a?"TENANT_GROUP":"ORG_GROUP",...a&&n?{tenantId:n}:{}};try{await u.mutateAsync(g),l(""),c(""),d({}),t()}catch(b){console.error("Failed to create group:",b)}};return e.jsxs("form",{onSubmit:h,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:x=>{l(x.target.value),i.name&&d(g=>({...g,name:""}))},className:i.name?"border-destructive":"",disabled:u.isPending}),i.name&&e.jsx("p",{className:"text-sm text-destructive",children:i.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:o,onChange:x=>{c(x.target.value),i.description&&d(g=>({...g,description:""}))},className:i.description?"border-destructive":"",disabled:u.isPending,rows:3}),i.description&&e.jsx("p",{className:"text-sm text-destructive",children:i.description}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.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(""),c(""),d({})},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 Tn({open:t,onOpenChange:n,group:a,onUpdate:r}){const[l,o]=M.useState("members"),[c,i]=M.useState(""),[d,u]=M.useState([]),[m,h]=M.useState([]),{data:x,isLoading:g,refetch:b}=s.useGroupMembers(a.id),p=a.type==="TENANT_GROUP"?"tenant":"organization",{users:j,isLoading:f}=s.useUnifiedUsers({type:p,tenantId:a.tenantId||void 0,active:!0,limit:100}),N=Sn(),T=wn(),I=(x==null?void 0:x.members)||[],w=M.useMemo(()=>new Set(I.map(D=>D.userId)),[I]),C=M.useMemo(()=>j.filter(D=>!w.has(D.id)),[j,w]),v=M.useMemo(()=>{if(!c)return C;const D=c.toLowerCase();return C.filter(S=>{var L,F;return((L=S.name)==null?void 0:L.toLowerCase().includes(D))||((F=S.email)==null?void 0:F.toLowerCase().includes(D))})},[C,c]),k=M.useMemo(()=>{if(!c)return I;const D=c.toLowerCase();return I.filter(S=>{var L,F,R,A;return((F=(L=S.user)==null?void 0:L.name)==null?void 0:F.toLowerCase().includes(D))||((A=(R=S.user)==null?void 0:R.email)==null?void 0:A.toLowerCase().includes(D))})},[I,c]),y=async()=>{if(d.length!==0)try{await N.mutateAsync({groupId:a.id,data:{userIds:d,userType:p==="tenant"?"tenant":"org"}}),u([]),o("members"),b(),r==null||r()}catch(D){console.error("Failed to add members:",D)}},O=async()=>{if(m.length!==0)try{await T.mutateAsync({groupId:a.id,data:{userIds:m}}),h([]),b(),r==null||r()}catch(D){console.error("Failed to remove members:",D)}},E=D=>{u(S=>S.includes(D)?S.filter(L=>L!==D):[...S,D])},P=D=>{h(S=>S.includes(D)?S.filter(L=>L!==D):[...S,D])};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:[I.length," ",I.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:D=>{o(D),i(""),h([])},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:c,onChange:D=>i(D.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:m.length>0?"h-[300px]":"h-[350px]",children:g?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(D=>e.jsx(s.Skeleton,{className:"h-16 w-full"},D))}):k.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:c?"No members found":"No members yet"}),e.jsx("p",{className:"text-xs mt-1",children:c?"Try a different search":'Switch to the "Add Members" tab to add people to this group'})]}):e.jsx("div",{className:"space-y-2",children:k.map(D=>e.jsx(kn,{member:D,selected:m.includes(D.userId),onToggle:()=>P(D.userId)},D.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:O,disabled:T.isPending,children:T.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:c,onChange:D=>i(D.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[300px]",children:f?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(D=>e.jsx(s.Skeleton,{className:"h-16 w-full"},D))}):v.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:c?"Try a different search":"All eligible users are already members"})]}):e.jsx("div",{className:"space-y-2",children:v.map(D=>e.jsx(En,{user:D,selected:d.includes(D.id),onToggle:()=>E(D.id)},D.id))})}),d.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:[d.length," user",d.length!==1?"s":""," selected"]}),e.jsx(s.Button,{onClick:y,disabled:N.isPending,children:N.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 kn({member:t,selected:n,onToggle:a}){var l,o,c,i;const r=((o=(l=t.user)==null?void 0:l.name)==null?void 0:o.split(" ").map(d=>d[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:((c=t.user)==null?void 0:c.name)||"Unknown User"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(i=t.user)==null?void 0:i.email})]})]})}function En({user:t,selected:n,onToggle:a}){var l;const r=((l=t.name)==null?void 0:l.split(" ").map(o=>o[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 In({open:t,onOpenChange:n}){const[a,r]=M.useState("groups"),[l,o]=M.useState(""),[c,i]=M.useState(null),[d,u]=M.useState(!1),[m,h]=M.useState(null),{tokenProps:x}=s.useSemaphorContext(),{currentUser:g}=s.useCurrentUserInfo(),b=Cn(),p=(g==null?void 0:g.type)==="tenant",j=x==null?void 0:x.tenantId,{groups:f,isLoading:N,refetch:T}=s.useGroups({type:p?"TENANT_GROUP":"all",tenantId:p?j:void 0,includeMembers:!1}),I=f.filter(k=>{var y;return k.name.toLowerCase().includes(l.toLowerCase())||((y=k.description)==null?void 0:y.toLowerCase().includes(l.toLowerCase()))}),w=async()=>{if(m)try{await b.mutateAsync(m.id),h(null),T()}catch(k){console.error("Failed to delete group:",k)}},C=k=>{i(k),u(!0)},v=()=>{r("groups"),T()};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:k=>o(k.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[400px]",children:N?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(k=>e.jsx(s.Skeleton,{className:"h-24 w-full"},k))}):I.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:I.map(k=>e.jsx(An,{group:k,onManageMembers:()=>C(k),onDelete:()=>h(k),currentUserId:g==null?void 0:g.id},k.id))})})]})}),e.jsx(s.TabsContent,{value:"create",className:"mt-4",children:e.jsx(Dn,{onSuccess:v,tenantId:j,isTenantUser:p})})]})]})}),c&&e.jsx(Tn,{open:d,onOpenChange:u,group:c,onUpdate:()=>T()}),e.jsx(s.AlertDialog,{open:!!m,onOpenChange:()=>h(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 An({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 Mn(){var Y,Q,X;const{authToken:t,tokenProps:n,id:a}=s.useSemaphorContext(),{isLocalDev:r}=s.useDashboardPreferences(),{permissions:l}=s.useRoleAwareDisplayPreferences(),o=s.useHasDashboardId();s.useDashboardStore($=>$.theme);const c=s.useDashboardStore($=>$.lenses),i=s.useDashboardStore($=>$.selectedLensId),d=c==null?void 0:c.find($=>$.id===i),u=s.useDashboardStore($=>$.dashboard);s.useDashboardStore($=>$.selectedSheetId);const m=s.useDashboardStore($=>$.isDashboardEditing),h=s.useEditorStore($=>$.card),x=s.useEditorStore($=>$.selectedConnectionId),[g,b]=M.useState(!1),[p,j]=M.useState(!1),[f,N]=M.useState(!1),T=s.useDashboardStore($=>$.isDashboardPanelOpen),I=s.useDashboardStore($=>$.actions.setIsDashboardPanelOpen),w=s.useDashboardStore($=>$.filterValues),C=s.useDashboardStore($=>$.isVisualEditing),v=s.useManagementStore($=>$.selectedDashboard),k=s.useManagementStore($=>$.initialDashboard),y=v?(Q=v==null?void 0:v.permissions)==null?void 0:Q.canEdit:(Y=k==null?void 0:k.permissions)==null?void 0:Y.canEdit,O=s.useDashboardStore($=>$.showFilters),E=s.useDashboardStore($=>$.showDashboardJSON),P=s.useDashboardStore($=>$.onSaveFunction),D=s.useDashboardStore($=>$.actions.setShowFilters),{addFrame:S,setSelectedFrameId:L}=s.useDashboardStore($=>$.actions),{getSelectedSheet:F,setIsDashboardEditing:R,setShowDashboardJSON:A}=s.useDashboardStore($=>$.actions),z=F(),{setInitialDashboard:q,clearSelectedDashboard:V}=s.useManagementStore($=>$.actions),{resources:J}=s.useResourceManagement(s.ResourceType.DASHBOARD),{currentUser:Z}=s.useCurrentUserInfo(),W=s.canUserManageGroups(Z),H=v||k,G=H?{id:H.id,title:(u==null?void 0:u.title)||H.title||"Dashboard"}:null;M.useEffect(()=>{if(J&&J.length>0){const $=u==null?void 0:u.id;if($){const te=J.find(ie=>ie.id===$);te&&q(te)}}},[J,u==null?void 0:u.id,q]);const se=n.orgUserId||n.tenantId,_=m&&!C&&se&&y;function U(){var ce,Ee;const $=h.dataSource;if($)return $;const te=(Ee=(ce=u.aiContext)==null?void 0:ce.selectedEntities)==null?void 0:Ee[0],ie=te==null?void 0:te.type;if(te)return{connectionId:te.connectionId,connectionType:te.connectionType,type:ie,selectedEntities:[te]}}const ee=()=>{if(!m||!z)return;const te={dataSource:U(),mode:"explorer",connectionId:x,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},ie={id:s.v4(),cards:[te],activeCardId:te.id};S(z.id,ie),L(ie.id)},ne=()=>{R(!0)},[oe,B]=M.useState(!1),ae=s.useUpdateResource(s.ResourceType.DASHBOARD);async function le(){const $=ss(u);B(!0);const te={template:$};ae.mutate({resourceId:$.id,data:te},{onSuccess:()=>{B(!1),s.ue.success("Dashboard saved!")},onError:()=>{B(!1),s.ue.error("Failed to save dashboard")}})}async function re(){if(b(!0),!i||!d)return;const $=ss(u),te=JSON.stringify($),ie={...d,template:te,filterValues:w};await vs(n.apiServiceUrl,ie,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),P==null||P($),b(!1)}if(C)return null;const xe=(d==null?void 0:d.name)||u.title,me=J&&J.length>0&&(n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail),fe=v&&!(n!=null&&n.dashboard_id)&&!a;return e.jsxs("div",{className:"flex h-10 items-center justify-between gap-2 border-b py-2 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[me&&e.jsxs(e.Fragment,{children:[fe&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Back to Dashboard Hub",onClick:()=>V(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})}),e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:o?"Manage Dashboards":"Select a dashboard to continue",onClick:()=>{console.log("isDashboardPanelOpen",T),I(!T)},className:"h-7 p-2",buttonProps:{disabled:!o},children:e.jsx(Ta,{className:"h-4 w-4"})})]}),!C&&o&&e.jsx(s.Label,{children:xe})]}),e.jsxs("div",{className:"flex gap-2",children:[r&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:()=>s.invalidateToken(n.apiServiceUrl),className:"h-7 p-2",children:e.jsx(Ba,{className:"h-4 w-4"})}),!C&&o&&e.jsx(Ja,{}),!C&&o&&e.jsx(lt,{}),!C&&o&&W&&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"})}),!C&&o&&((X=H==null?void 0:H.permissions)==null?void 0:X.canShare)&&e.jsx(s.IconButton,{tooltip:"Share Dashboard",onClick:()=>j(!0),className:"h-7 p-2",children:e.jsx(s.UserPlus,{className:"h-4 w-4"})}),m&&!C&&se&&r&&o&&e.jsx(Ka,{}),!C&&se&&r&&o&&e.jsx(Qa,{}),m&&!C&&se&&d&&r&&o&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:g,onClick:re,size:"sm",children:[e.jsx(bs,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),m&&!C&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!m,onClick:ee,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!C&&!m&&l.canEdit&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:ne,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),m&&!C&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{R(!1),A(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),_&&o&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"outline",disabled:oe,onClick:le,size:"sm",children:[oe?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(bs,{className:"mr-2 h-4 w-4"}),oe?"Saving...":"Save"]}),!O&&!C&&m&&l.canUseFilters&&o&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>D(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!C&&m&&r&&o&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>A(!E),size:"sm",variant:"ghost",children:e.jsx(ze,{className:"h-4 w-4"})})}),!C&&r&&e.jsx($a,{}),p&&G&&e.jsx(ls,{resource:G,resourceType:s.ResourceType.DASHBOARD,onClose:()=>j(!1)}),e.jsx(In,{open:f,onOpenChange:N})]})]})}function Ln({name:t,items:n,value:a,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:d,showNone:u=!1}){const m=Ie.useRef(null),[h,x]=Ie.useState(!1),[g,b]=Ie.useState("100%"),p=u?[...n||[],{id:"none",name:"None"}]:n;Ie.useLayoutEffect(()=>{m.current&&b(m.current.offsetWidth)},[]);function j(){var N;return l?"Loading...":o?"Error":a?(N=n==null?void 0:n.find(T=>T.id===a))==null?void 0:N.name:`Select ${t}`}function f(N,T){r(T),x(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:x,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:m,variant:"outline",role:"combobox","aria-expanded":h,className:s.cn("flex h-9 w-full justify-between",i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx("div",{className:"mr-2",children:d}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:j()})]}),e.jsx(s.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-full p-0",style:{minWidth:g},children:e.jsxs(s.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(s.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(s.IconButton,{className:"h-7",onClick:c,children:e.jsx(st,{className:s.cn("size-3.5 opacity-50",l&&"animate-spin")})})]}),e.jsxs(s.CommandList,{children:[e.jsxs(s.CommandEmpty,{children:["No ",t==null?void 0:t.toLowerCase()," found."]}),e.jsx(s.CommandGroup,{children:p==null?void 0:p.map(N=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:N.name,onSelect:T=>f(T,N.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",a===N.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:N.name,children:N.name})]})},N.id))})]})]})})]})}function Pe({title:t,items:n,value:a,isLoading:r,isError:l,refetch:o,onChange:c,showNone:i=!1,className:d,disabled:u=!1,type:m="combobox"}){const h=r?"Loading...":l?"Error":a;function x(){if(t==="Connection")return e.jsx(Oa,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Ma,{className:"size-4"});if(t==="Table")return e.jsx(s.Table2,{className:"size-4"});if(t==="Model")return e.jsx(oa,{className:"size-4"})}function g(){return e.jsxs(s.Select,{disabled:u,value:h,onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:s.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",d),children:e.jsx(s.SelectValue,{placeholder:r?"Loading...":l?"Error":`Select ${t}`})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[r?e.jsx(s.SelectLabel,{children:"Loading..."}):e.jsxs(s.SelectLabel,{className:"flex items-center justify-between gap-2",children:[t,e.jsx(st,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:o})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),n&&n.map((p,j)=>e.jsx(s.SelectItem,{value:p.id,children:p.name},j))]}),(r||l)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function b(){return e.jsx(Ln,{icon:x(),items:n,value:h,onChange:c||(()=>{}),isLoading:r,isError:l,refetch:o,name:t,showNone:i})}return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:m==="select"?g():b()})})}function Rn({column:t}){const[n,a]=M.useState(!1),r=s.useEditorStore(p=>p.selectedTableName),l=s.useEditorStore(p=>p.selectedSchemaName),o=s.useEditorStore(p=>p.selectedDatabaseName),c=s.useEditorStore(p=>p.selectedDatamodelId),i=s.useEditorStore(p=>p.sqlGen),{modelItems:d,connectionType:u}=s.useEditorAside(),m=s.useEditorStore(p=>p.actions.setSqlGen),h=s.useEditorStore(p=>p.actions.setCardSql),x=s.useEditorStore(p=>p.actions.setRunSql);function g(p,j){var I;const f=s.createSqlGenConfig(p,i,j),N=(I=d==null?void 0:d.find(w=>w.id===c))==null?void 0:I.name;m(f);const T=s.getSql(f,s.fmt(l||""),s.fmt(r),N||"",u,o||"");T&&(h(T),x(!0)),a(!1)}function b(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>g(t,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>g(t,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>g(t,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>g(t,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>g(t,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(s.HoverCard,{openDelay:0,open:n,onOpenChange:a,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]})}function On({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Re,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ze,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(qe,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Ke,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})}function ds({column:t,className:n}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center gap-2 px-3 py-[6px] text-sm",n),children:[e.jsx(On,{dataType:t.data_type}),e.jsx("span",{children:t.column_name})]})}function Fn({id:t,children:n,type:a="column"}){const{attributes:r,listeners:l,setNodeRef:o,transform:c}=s.useDraggable({id:t,data:{type:a}}),i=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:o,style:i,...l,...r,children:n})}function Pn({onClick:t,column:n}){const a=s.useDndStore(m=>m.activeId),r=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.groupByColumns}),l=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.metricColumns}),o=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.filterColumns});function c(m){return i(m)||d(m)||u(m)}function i(m){return r==null?void 0:r.some(h=>h.name===m.column_name)}function d(m){return l==null?void 0:l.some(h=>h.name===m.column_name)}function u(m){return o==null?void 0:o.some(h=>h.name===m.column_name)}return e.jsxs("div",{onClick:()=>t(n),className:s.cn("group relative grow cursor-pointer overflow-x-hidden overflow-y-hidden border border-dashed border-background transition-colors hover:bg-muted/50",{"bg-muted":c(n)}),children:[a===n.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(ds,{column:n,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),a===n.column_name&&e.jsx("div",{className:"absolute inset-0",children:a===n.column_name&&e.jsx(ds,{column:n})}),e.jsx(Fn,{id:n.column_name,type:"column",children:e.jsx(ds,{column:n})})]})}const us={id:"__placeholder__",role:"groupby",type:"string"},ms={id:"__placeholder__",role:"groupby",type:"string"},hs={id:"__placeholder__",role:"metric",type:"number"},xs={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},gt={id:"__placeholder__"},Ae="droppable-group-by",Me="droppable-metrics",Le="droppable-pivot-by",as="sortable-group-by",ys="sortable-metrics",ns="sortable-pivot-by",Ns="droppable-filters",Cs="sortable-filters",ws="sortable-order-by";function Bn(){const t=s.useDndStore(S=>S.insertIndex),n=s.useEditorStore(S=>{var L;return((L=S.card.queryConfig)==null?void 0:L.groupByColumns)||[]}),a=s.useEditorStore(S=>{var L;return((L=S.card.queryConfig)==null?void 0:L.metricColumns)||[]}),r=s.useEditorStore(S=>{var L;return((L=S.card.queryConfig)==null?void 0:L.filterColumns)||[]}),l=s.useEditorStore(S=>{var L;return((L=S.card.queryConfig)==null?void 0:L.orderBy)||[]}),o=s.useEditorStore(S=>{var L;return((L=S.card.queryConfig)==null?void 0:L.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:u,setPreviewFilterColumns:m,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:x,setMetricColumns:g,setFilterColumns:b,setOrderByColumns:p,setPivotByColumns:j}=s.useEditorActions(),{columns:f}=s.useDataColumns(),{formattedTableName:N}=s.useEditorAside(),T=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),I=S=>{var R;const{active:L,over:F}=S;if(((R=L.data.current)==null?void 0:R.type)==="column"&&F){const A=F.id,z=f.find(Z=>Z.column_name===L.id);if(!z)return;const q=s.isNumberDataType(z.data_type),V=s.isTextDataType(z.data_type),J=s.isDateDataType(z.data_type);if(V||J){if(n.some(W=>W.id===A)){const W=n.findIndex(G=>G.id===A);c(W);const H=n.filter(G=>G.id!==us.id);H.splice(W,0,us),d(H)}else if(F.id===Ae){c(n.length);const W=[...n,us];d(W),u(a),m(r)}}if(V||J){if(o.some(W=>W.id===A)){const W=o.findIndex(G=>G.id===A);c(W);const H=o.filter(G=>G.id!==ms.id);H.splice(W,0,ms),h(H)}else if(F.id===Le){c(o.length);const W=[...o,ms];h(W),d(n),u(a),m(r)}}if(q||V){if(a.some(W=>W.id===A)){console.log("isOverMetricSortable",A);const W=a.findIndex(G=>G.id===A);c(W);const H=a.filter(G=>G.id!==hs.id);H.splice(W,0,hs),u(H)}else if(F.id===Me){c(a.length);const W=[...a,hs];u(W),m(r),d(n),h(o)}}if(C(z)){if(r.some(W=>W.id===A)){const W=r.findIndex(G=>G.id===A);c(W);const H=r.filter(G=>G.id!==xs.id);H.splice(W,0,xs),m(H)}else if(F.id===Ns){c(r.length);const W=[...r,xs];m(W),u(a),d(n),h(o)}}}else d(n),u(a),m(r),h(o)};function w(S){i(S.active.id),c(null),d(n),u(a),m(r),h(o)}function C(S){return!r.some(L=>L.name===S.column_name)}function v(S,L="SUM"){const{column_name:F,data_type:R}=S,A=[...a],z=t!==null?t:a.length,q={...S,id:Ne(F),name:F,label:We(F,L),type:R,role:"metric",aggregate:L};A.splice(z,0,q),g(A)}function k(S){const L=s.isTextDataType(S.data_type);s.isDateDataType(S.data_type);const F=[...o],R=t!==null?t:o.length;let A;L?A={...S,id:Ne(S.column_name),name:S.column_name,type:S.data_type,role:"groupby"}:A={...S,id:Ne(S.column_name),name:S.column_name,type:S.data_type,role:"groupby",label:Ve(S.column_name,"month"),granularity:"month"},F.splice(R,0,A),j(F)}function y(S){const L=s.isTextDataType(S.data_type);s.isDateDataType(S.data_type);const F=[...n],R=t!==null?t:n.length;let A;L?A={...S,id:Ne(S.column_name),name:S.column_name,type:S.data_type,role:"groupby"}:A={...S,id:Ne(S.column_name),name:S.column_name,type:S.data_type,role:"groupby",label:Ve(S.column_name,"month"),granularity:"month"},F.splice(R,0,A),x(F)}function O(S){const L=[...r],F=t!==null?t:r.length,R={...S,id:Ne(S.column_name),name:S.column_name,type:S.data_type,sql:s.getDefaultFilterSql(S.data_type,N,s.fmt(S.column_name)),role:"filter"};L.splice(F,0,R),b(L)}function E(S){var A,z,q,V,J,Z,W,H;const{active:L,over:F}=S,R=L.data.current;if((R==null?void 0:R.type)==="column"&&F){const G=f.find(ee=>ee.column_name===L.id);if(!G)return;const se=s.isNumberDataType(G.data_type),_=s.isTextDataType(G.data_type),U=s.isDateDataType(G.data_type);(_||U)&&(F.id===Ae||((A=F.data.current)==null?void 0:A.type)===as)&&y(G),(_||U)&&(F.id===Le||((z=F.data.current)==null?void 0:z.type)===ns)?k(G):(se||_)&&(F.id===Me||((q=F.data.current)==null?void 0:q.type)===ys)?(se&&v(G),_&&v(G,"COUNT")):C(G)&&(F.id===Ns||((V=F.data.current)==null?void 0:V.type)===Cs)&&O(G)}if(F&&((J=F.data.current)==null?void 0:J.type)===as&&n.some(G=>G.id===L.id)){const G=n.findIndex(_=>_.id===L.id),se=n.findIndex(_=>_.id===F.id);if(G!==-1&&se!==-1&&G!==se){const _=[...n],[U]=_.splice(G,1);_.splice(se,0,U),x(_)}}if(F&&((Z=F.data.current)==null?void 0:Z.type)===ns&&o.some(G=>G.id===L.id)){const G=o.findIndex(_=>_.id===L.id),se=o.findIndex(_=>_.id===F.id);if(G!==-1&&se!==-1&&G!==se){const _=[...o],[U]=_.splice(G,1);_.splice(se,0,U),j(_)}}if(F&&((W=F.data.current)==null?void 0:W.type)===ys&&a.some(G=>G.id===L.id)){const G=a.findIndex(_=>_.id===L.id),se=a.findIndex(_=>_.id===F.id);if(G!==-1&&se!==-1&&G!==se){const _=[...a],[U]=_.splice(G,1);_.splice(se,0,U),g(_)}}if(F&&((H=F.data.current)==null?void 0:H.type)===Cs&&r.some(G=>G.id===L.id)){const G=r.findIndex(_=>_.id===L.id),se=r.findIndex(_=>_.id===F.id);if(G!==-1&&se!==-1&&G!==se){const _=[...r],[U]=_.splice(G,1);_.splice(se,0,U),b(_)}}P(S),i(null),c(null),d(n),u(a),m(r),h(o)}function P(S){const{active:L,over:F}=S,R=L.data.current;if((R==null?void 0:R.type)===ws&&F){const A=l.findIndex(q=>$e(q.columnId)===L.id),z=l.findIndex(q=>$e(q.columnId)===F.id);if(A!==-1&&z!==-1&&A!==z){const q=[...l],[V]=q.splice(A,1);q.splice(z,0,V),p(q)}}}function D(){i(null),c(null),d(n),u(a),m(r)}return{handleDragOver:I,handleDragEnd:E,handleDragStart:w,handleDragCancel:D,sensors:T}}function Ne(t){return`${t}-${s.v4()}`}function We(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 $e(t){return`${ws}-${t}`}function Ve(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 zn({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Re,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ze,{className:"h-3 w-3"})}):n==="geo"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(qe,{className:"h-3 w-3"})}):n==="calculated"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(Ke,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})}function _n({schemaName:t,tableName:n,columns:a,status:r}){const[l,o]=M.useState(""),[c,i]=M.useState("all"),d=s.useEditorStore(A=>A.sqlGen),u=s.useEditorStore(A=>A.isDevMode);s.useEditorStore(A=>A.selectedConnectionId);const m=s.useEditorStore(A=>{var z,q;return(q=(z=A.card)==null?void 0:z.queryConfig)==null?void 0:q.metricColumns});s.useEditorStore(A=>{var z,q;return(q=(z=A.card)==null?void 0:z.queryConfig)==null?void 0:q.groupByColumns});const h=s.useEditorStore(A=>A.selectedDatabaseName);s.useEditorStore(A=>A.selectedSchemaName),s.useEditorStore(A=>A.selectedTableName);const x=s.useEditorStore(A=>A.selectedDatamodelId);s.useDashboardStore(A=>A.dashboard.aiScopeTables);const{addToAIScope:g,removeFromAIScope:b}=s.useDashboardActions(),{addColumnToMetricColumns:p,addColumnToGroupBy:j,setCardSql:f,setRunSql:N,setSqlGen:T,setIsShowingVisual:I}=s.useEditorActions(),{connectionType:w,modelItems:C,selectedDatamodelName:v}=s.useEditorAside();function k(A){var z;if(u){const q=s.createSqlGenConfig(A,d);T(q);const V=(z=C==null?void 0:C.find(Z=>Z.id===x))==null?void 0:z.name,J=s.getSql(q,s.fmt(t),s.fmt(n),V||"",w,h||"");J&&(f(J),N(!0))}if(!u){if(s.isTextDataType(A.data_type))if(m&&m.length>0){const q={...A,role:"groupby",id:Ne(A.column_name),name:A.column_name,type:A.data_type};j(q)}else{const q={...A,role:"metric",id:Ne(A.column_name),name:A.column_name,label:We(A.column_name,"COUNT"),type:A.data_type,aggregate:"COUNT"};p(q)}if(s.isDateDataType(A.data_type)){const q={...A,role:"groupby",id:Ne(A.column_name),name:A.column_name,type:A.data_type,label:Ve(A.column_name,"month"),granularity:"month"};j(q)}if(s.isNumberDataType(A.data_type)){const q={...A,role:"metric",id:Ne(A.column_name),name:A.column_name,label:We(A.column_name,"SUM"),type:A.data_type,aggregate:"SUM"};p(q)}}}function y(){const A=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:w,databaseName:h||""});I(!1);const z=w==="MSSQL"?`SELECT top 10 * FROM ${A}`:`SELECT * FROM ${A} LIMIT 10`;f(z),N(!0)}function O(){const A=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:w,databaseName:h||""});f(`SELECT COUNT(*) as count FROM ${A}`),N(!0)}const E=(a==null?void 0:a.filter(A=>A.column_name.toLowerCase().includes(l.toLowerCase())))||[],P=A=>s.isNumberDataType(A.data_type)?"number":"text",D=c==="all"?E:E.filter(A=>P(A)===c),S=E.filter(A=>P(A)==="text").length,L=E.filter(A=>P(A)==="number").length;function F(A){return u?e.jsxs("div",{className:"group flex cursor-pointer items-center justify-between border border-dashed border-background px-2 py-[6px] text-sm transition-colors hover:bg-muted/50",onClick:()=>k(A),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zn,{dataType:A.data_type}),e.jsx("span",{children:A.column_name})]}),e.jsx("div",{onClick:z=>z.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(A.data_type)&&e.jsx(Rn,{column:A})})]}):e.jsx(Pn,{onClick:k,column:A})}function R(){return e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:r!=="Success",onClick:y,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(Da,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:O,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(tt,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-4",children:Array.from({length:3}).map((A,z)=>e.jsx(s.Skeleton,{className:"h-8 w-full"},z))}):e.jsxs("div",{className:"flex grow flex-col",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-4",children:[u&&e.jsx("div",{className:"flex items-center justify-center gap-2",children:R()}),a&&a.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:l,onChange:A=>o(A.target.value)})]}),E.length>0&&e.jsx(s.Tabs,{defaultValue:"all",value:c,onValueChange:A=>i(A),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:E.length})]}),e.jsxs(s.TabsTrigger,{value:"text",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:S})]}),e.jsxs(s.TabsTrigger,{value:"number",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:L})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-4 pt-3",children:[D.length===0&&l&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',l,'"']}),D.length===0&&!l&&c!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",c," fields found"]}),e.jsx("div",{className:"flex flex-col gap-1",children:D==null?void 0:D.map(A=>e.jsx("div",{children:F(A)},A.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function jt({ColumnsComponent:t,type:n}){var Q;const[a,r]=M.useState(!1),l=s.useEditorStore(X=>X.card),o=s.useEditorStore(X=>X.selectedConnectionId),c=s.useDashboardStore(X=>X.showFilters),i=s.useEditorStore(X=>X.selectedDatamodelId),d=s.useEditorStore(X=>X.selectedDatabaseName),u=s.useEditorStore(X=>X.selectedSchemaName),m=s.useEditorStore(X=>X.selectedTableName),h=s.useEditorStore(X=>X.isDevMode),{setSelectedTableName:x,setIsDevMode:g,setCardSql:b}=s.useEditorActions(),{connectionItems:p,modelItems:j,schemaItems:f,databaseItems:N,tableItems:T,columns:I,isConnectionsLoading:w,isModelsLoading:C,isConnectionsError:v,isModelsError:k,isDatabasesLoadingOrFetching:y,isDatabaseError:O,isSchemaLoadingOrFetching:E,isSchemaError:P,isColumnsError:D,isColumnsLoadingOrFetching:S,isTableLoadingOrFetching:L,isTableError:F,connectionType:R,isNonDbConnection:A,refetchDatabases:z,refetchModels:q,refetchSchemas:V,refetchTables:J,refetchColumns:Z,refetchConnections:W,handleConnectionChange:H,handleDatabaseChange:G,handleSchemaChange:se,handleDatamodelChange:_,handleTableChange:U,tableName:ee,schemaName:ne}=s.useEditorAside(),{data:oe,refetch:B}=s.useDashboardCardQuery(l);function ae(){return t?t(ne,ee,I):e.jsx(_n,{schemaName:ne,tableName:ee,columns:I,status:S?"Loading...":D?"Error":"Success"})}function le(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function re(X){X===!0?oe&&(b(oe.userSql),setTimeout(()=>{B()},100)):b(""),g(X)}function xe(){if(!o||R==="S3"||R==="API")return null;if(!i||i==="none")return e.jsx(Pe,{refetch:z,showNone:!0,onChange:G,isError:O,isLoading:y,items:N,value:d||"",title:"Database",type:"combobox"})}function pe(){if(o&&!A&&(!d||d==="none")&&(!i||i==="none"))return e.jsxs("div",{className:"grid grid-cols-3",children:[e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})})]})}function me(){if(!o||R==="S3"||R==="API")return null;if(!d||d==="none")return e.jsx(Pe,{refetch:q,showNone:!0,onChange:_,isError:k,isLoading:C,items:j,value:i||"",title:"Model",type:"combobox"})}function fe(){return!o||R==="S3"||R==="API"||!d||d==="none"?null:e.jsx(Pe,{refetch:V,onChange:se,isError:P,isLoading:E,items:f,value:u||"",title:"Schema",type:"combobox"})}function Y(){function X(){let $=!1;return R==="API"?($=!1,$):((R==="S3"||o&&d&&d!=="none"&&u)&&($=!0),$)}return X()?e.jsx(Pe,{refetch:J,onChange:U,isError:F,items:T,isLoading:L,value:m||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:s.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!c}),children:[e.jsxs("section",{className:s.cn("px-4",{"px-4 pb-0 pt-4":a,"px-4 py-4":!a}),children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Direct Source"}),e.jsx(s.Button,{onClick:()=>r(!a),size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:a?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),!a&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Pe,{refetch:W,items:p,title:"Connection",value:o||"",onChange:H,isLoading:w,isError:v,type:"combobox",connectionTooltip:((Q=p==null?void 0:p.find(X=>X.id===o))==null?void 0:Q.type)||""}),xe(),pe(),me(),fe(),Y()]})]}),ae(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:n==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:h,onCheckedChange:re,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:le,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(ka,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function bt({error:t,errorSql:n,onSendFeedback:a,className:r,showFeedbackButton:l=!0}){const[o,c]=M.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-destructive/30 bg-destructive/5 p-4",r),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(s.CircleAlert,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-destructive"}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:"Query Error"}),e.jsxs("div",{className:"relative rounded-md bg-background/60 p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 h-6 w-6 z-10"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"font-mono text-xs text-foreground/80 break-all",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:o?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),l&&a&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:a,children:[e.jsx(Ia,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),n&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleContent,{className:"space-y-2",children:e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Error SQL Query"}),e.jsx(s.CopyButton,{text:n,className:"h-6 w-6"})]}),e.jsx("div",{className:"rounded-md bg-background/60 p-2 max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:n,language:"sql"})})]})})})]})]})})}function vt({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){const l=s.useEditorStore(u=>u.isDevMode),{setIsDevMode:o,setCardSql:c,setRunSql:i}=s.useEditorActions();function d(){o(!l),c(t),setTimeout(()=>{i(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-3",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[n&&e.jsx(bt,{error:n,errorSql:a,showFeedbackButton:!1}),!n&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!l&&t&&!n&&e.jsxs(s.Button,{onClick:d,variant:"secondary",size:"sm",children:[e.jsx(fa,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),n&&r&&e.jsxs(s.Button,{onClick:r,size:"sm",variant:"outline",children:[e.jsx(ya,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function yt({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:n?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:n?e.jsx(da,{className:"h-4 w-4 text-red-500"}):e.jsx(s.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(s.HoverCardContent,{align:"start",className:"flex w-[700px]",children:e.jsx(vt,{errorSql:a,sql:t,error:n,onDebugWithAssistant:r})})]})}function Vn(t){return s.GenIcon({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(t)}function Nt(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(p=>p.theme),r=s.useEditorStore(p=>p.frame),l=s.useEditorStore(p=>p.card),o=s.useEditorStore(p=>p.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(l),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),m=M.useRef(),h=M.useRef({}),x=r.cards.find(p=>p.id===o),g=M.useCallback(()=>{let p="";return t==="python"&&(p=(x==null?void 0:x.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(p=(x==null?void 0:x.sql)||""),p},[t,x]);M.useEffect(()=>{if(o&&l.id&&l.id!==o){if(m.current&&c){const p=m.current.getModel();p&&(h.current[l.id]=p);let j=h.current[o];if(!j){const f=g();j=c.editor.createModel(f,t),h.current[o]=j}m.current.setModel(j)}d(o,l),u(!0)}},[o,l,d,c,u,t,g]),M.useEffect(()=>{if(!c)return;const p=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",j=a==="system"?p:a;c.editor.defineTheme("default",{base:j==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":j==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[n,a,c]),M.useEffect(()=>{const p=m.current;p&&c&&l&&p.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function b(p,j){if(m.current=p,!h.current[l.id]){const f=p.getModel(),N=g();h.current[l.id]=f||(j==null?void 0:j.editor.createModel(N,t))||p.getModel()}p.setModel(h.current[l.id])}return{handleEditorDidMount:b}}function Un(){const t=s.useEditorStore(c=>c.card.sql),n=s.useEditorStore(c=>c.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=Nt("sql");function o(c){a(c),s.isObjectEmpty(n)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:o,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function Gn(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=Nt("python");function r(l){n(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:a})}function Yn({jsonString:t}){return e.jsx(s.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:t,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function Ds(t){const[n,a]=M.useState(null),[r,l]=M.useState(null);return M.useEffect(()=>{if(!t||t.trim()===""){a(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");a(()=>d.useChartStore),l(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),l(i),a(null)}})()},[t]),n}function $n(t){const n=t.toUpperCase().indexOf("WHERE"),a=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let o=t.length;if(l!==-1&&(o=l),r!==-1&&r<o&&(o=r),n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,o),i=t.substring(o);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function qn(t,n){if(t.length===0)return"";if(n){const a=t.find(r=>r.id===n);if(a){const r=a.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const o=r.split("__")[0],c=t.find(i=>i.tabTitle===o);return c?c.id:t[0].id}return n}}return t[0].id}async function Ys(t,n,a,r){if(!n||!a)throw new Error("Missing auth token or visual ID");const l=["resource-by-id","visual",a],o=r.getQueryData(l);if(o)return console.log("Using cached visual data for:",a),{data:o,fromCache:!0};console.log("Fetching visual data from network for:",a);const c=s.ue.loading("Loading visual...",{position:"top-center"});try{const i=await fetch(`${t}/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${n}`}});if(!i.ok)throw new Error("Failed to load visual");const d=await i.json();return r.setQueryData(l,d),s.ue.dismiss(c),{data:d,fromCache:!1}}catch(i){throw s.ue.dismiss(c),i}}function Hn(t,n,a,r,l){const o=t.frameObject;n(o);const c=o.cards.find(i=>i.id===o.activeCardId);c&&a(c),r(!0),l(!0)}function Wn(){var x;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(g=>g.frame),a=s.useEditorStore(g=>g.card),r=Ds(((x=a.customCardPreferences)==null?void 0:x.url)||""),l=s.useEditorStore(g=>g.selectedSchemaName),o=s.useEditorStore(g=>g.selectedDatamodelId),c=s.useEditorStore(g=>g.selectedDatabaseName),i=s.useEditorStore(g=>g.selectedTableName),d=s.useEditorStore(g=>g.selectedConnectionId),u=s.useEditorStore(g=>g.isShowingVisual),m=a.sql;return{getUpdatedFrame:M.useCallback(()=>{var f;let g=m;m&&!m.includes("{{")&&(g=$n(m),t(g));const b=(f=r==null?void 0:r.getState())==null?void 0:f.settings,p={...a,dataSource:a.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:o,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:g,customCfg:u?a.customCfg:null,preferences:a.preferences,...b&&{customCardPreferences:{...a.customCardPreferences,settings:b}}},j=n.cards.map(N=>N.id===a.id?p:N);return{...n,cards:j,activeCardId:qn(j,n.activeCardId)}},[a,n,u,l,o,c,i,d,t,r,m])}}function Ts(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient(),r=s.useSelectedVisual(),{selectVisual:l}=s.useManagementActions(),{setFrame:o,setCard:c}=s.useEditorActions(),{setIsDashboardEditing:i,setIsVisualEditing:d,setSelectedFrameId:u,addFrame:m,setIsDashboardPanelOpen:h}=s.useDashboardActions(),x=s.useDashboardStore(j=>j.selectedSheetId),g=s.useVisualById((r==null?void 0:r.id)||"",{enabled:!!(r!=null&&r.id)&&!!(t!=null&&t.accessToken)}),b=M.useCallback(async j=>{try{l(j);const{data:f,fromCache:N}=await Ys(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",j.id,a);return Hn(f,o,c,i,d),{success:!0,fromCache:N}}catch(f){return console.error("Error editing visual:",f),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,o,c,i,d]),p=M.useCallback(async j=>{try{if(l(j),!x)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:f,fromCache:N}=await Ys(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",j.id,a),T=f.frameObject;if(!T)return{success:!1,error:"Visual has no frame data"};const I={...T,id:s.v4()};return m(x,I,"end"),i(!0),u(I.id),h(!1),{success:!0,fromCache:N}}catch(f){return console.error("Error adding visual:",f),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,x,m,i,u,h]);return{visual:g.data,isLoading:g.isLoading,isError:g.isError,error:g.error,handleEditLibraryVisual:b,handleAddLibraryVisual:p,getUpdatedFrame:Wn().getUpdatedFrame,refetch:g.refetch}}function ks({variant:t="outline"}){var c;const{setCardSql:n}=s.useEditorActions();s.useEditorStore(i=>i.frame);const a=s.useEditorStore(i=>i.card);Ds(((c=a.customCardPreferences)==null?void 0:c.url)||""),s.useEditorStore(i=>i.selectedSchemaName),s.useEditorStore(i=>i.selectedDatamodelId),s.useEditorStore(i=>i.selectedDatabaseName),s.useEditorStore(i=>i.selectedTableName),s.useEditorStore(i=>i.selectedConnectionId),s.useEditorStore(i=>i.isShowingVisual),a.sql;const r=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:l}=Ts();function o(){const i=l();r==null||r(i)}return e.jsxs(s.Button,{onClick:o,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Kn(){const t=s.useQueryClient(),[n,a]=M.useState(!1),r=s.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{setIsVisualEditing:l}=s.useDashboardActions(),{getUpdatedFrame:o}=Ts(),c=s.useSelectedVisual(),i=s.useUpdateVisualMutation(),d=()=>{const u=o();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}a(!0),i.mutate({visualId:c.id,data:{frameObject:u}},{onSuccess:()=>{a(!1),l(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{a(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:d,className:"h-8",size:"sm",children:[n&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!n&&e.jsxs(e.Fragment,{children:[e.jsx(bs,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function Es(){const{setTempQueryData:t,setSqlGen:n}=s.useEditorActions(),a=s.useQueryClient(),r=s.useEditorStore(d=>d.tempQueryData),l=s.useEditorStore(d=>d.onClose),o=s.useEditorStore(d=>d.card),{queryKey:c}=s.useDashboardCardQuery(o);function i(){if(r){const{queryKey:d,queryData:u}=r;d&&u&&a.setQueryData(d,u)}n({}),l==null||l()}return e.jsxs(s.Button,{onClick:i,className:"h-8",size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function os(){const{setTempQueryData:t}=s.useEditorActions(),n=s.useQueryClient(),a=s.useEditorStore(j=>j.isDevMode),r=s.useEditorStore(j=>j.tempQueryData),l=s.useEditorStore(j=>j.card),{queryKey:o}=s.useDashboardCardQuery(l),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:u,setCardPreferences:m,updateDataSource:h,clearQueryConfig:x,setCardConfig:g,setCardType:b}=s.useEditorActions();function p(){const j=n.getQueryData(o);r!=null&&r.queryData||t({queryKey:o,queryData:j}),n.setQueryData(o,null),n.removeQueries({queryKey:o,exact:!0}),a&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),x(),g(void 0),d(""),u(""),m({}),b("bar")}return e.jsxs(s.Button,{onClick:p,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function Qn(){const t=s.useQueryClient(),[n,a]=M.useState(!1),[r,l]=M.useState(!1);s.useEditorStore(V=>V.frame);const o=s.useEditorStore(V=>V.card);s.useEditorStore(V=>V.isShowingVisual),s.useEditorStore(V=>V.selectedConnectionId),s.useEditorStore(V=>V.tempQueryData),s.useEditorStore(V=>V.selectedDatabaseName),s.useEditorStore(V=>V.selectedDatamodelId),s.useEditorStore(V=>V.selectedSchemaName);const c=s.useEditorStore(V=>V.showAIDialog);s.useEditorStore(V=>V.selectedTableName);const i=s.useEditorStore(V=>{var J;return(J=V==null?void 0:V.card)==null?void 0:J.sql}),d=s.useEditorStore(V=>{var J;return(J=V==null?void 0:V.card)==null?void 0:J.python}),{sheetFilterValues:u}=s.useSheetFilterValues(),{setCardCustomCfg:m,setQueryResultColumns:h,setCardSql:x,setTempQueryData:g,setPythonStdOut:b,setCardPreferences:p,setCardType:j,setCardPython:f,runAssistant:N,setShowAIDialog:T}=s.useEditorActions();s.useEditorStore(V=>V.onSave),s.useEditorStore(V=>V.onClose),s.useEditorStore(V=>V.actions.setSqlGen);const I=s.useEditorStore(V=>V.runSql),w=s.useEditorStore(V=>V.actions.setRunSql),C=s.useEditorStore(V=>V.actions.setIsSqlRunning),{data:v,isLoading:k,isFetching:y,isSuccess:O,isError:E,error:P,errorSql:D,queryKey:S,refetch:L,errorMessage:F}=s.useDashboardCardQuery(o);M.useEffect(()=>{if(v&&(v.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),b((v==null?void 0:v.output)||""),v.records.length>0)){const{dimensionKeys:V}=s.getKeys(v.records);h(V)}},[v,h,b]),M.useEffect(()=>{(k||y)&&C(!0),(E||O)&&C(!1),E&&(h([]),b(""))},[k,y,v,b,E,O,C,h,P]),M.useEffect(()=>{I&&(t.getQueryData(S)||L(),w(!1))},[I,L,w,S,t]);async function R(){const V=`Can you help me debug this query?
|
|
317
317
|
|
|
318
318
|
Error:
|
|
319
319
|
|