react-semaphor 0.0.679 → 0.0.680
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-L8lLx8X5.js → dashboard-plus-CIa_bbdW.js} +2 -2
- package/dist/chunks/{dashboard-plus-DCH_ymxQ.js → dashboard-plus-_RvcYPUc.js} +2 -2
- package/dist/chunks/{index-Dn6IF-mM.js → index-CcU18VfZ.js} +26441 -25993
- package/dist/chunks/{index-CZt-w3pv.js → index-J633tFTS.js} +177 -177
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +3 -3
- package/dist/style.css +1 -1
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +1 -1
- package/dist/types/dashboard.d.ts +4 -0
- package/dist/types/main.d.ts +4 -0
- package/dist/types/surfboard.d.ts +4 -0
- package/dist/types/types.d.ts +4 -0
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";const e=require("react/jsx-runtime"),s=require("./index-
|
|
1
|
+
"use strict";const e=require("react/jsx-runtime"),s=require("./index-J633tFTS.js"),A=require("react"),ra=require("react-dom");function la(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>t[a]})}}return n.default=t,Object.freeze(n)}const Re=la(A);/**
|
|
2
2
|
* @license lucide-react v0.453.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -308,7 +308,7 @@
|
|
|
308
308
|
*
|
|
309
309
|
* This source code is licensed under the ISC license.
|
|
310
310
|
* See the LICENSE file in the root directory of this source tree.
|
|
311
|
-
*/const Ka=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 Qa(){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(qa,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(Fa,{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 is(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=>ct(c))}})}})}}function ct(t){return{...t,customCfg:Ja(t.customCfg),data:[]}}function Ja(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 Xa(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 Ds(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 Za(t,n,a){if(!a)return null;const r=`${t}/v1/lens`;return await s.postRequest(r,a,{operation:"delete",lensId:n})}function en(){const[t,n]=A.useState(""),[a,r]=A.useState(!1),l=s.useDashboardStore(j=>j.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=A.useState(!1),[u,m]=A.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=is(h),f=await Xa(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 sn(){const[t,n]=A.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 Za(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 Ds(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 Ds(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(Ta,{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 tn({iconClassName:t}){const[n,a]=A.useState(!1),[r,l]=A.useState(""),[o,c]=A.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 dt({triggerButtonClassName:t}){const[n,a]=A.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 cs({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 ze({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 ut({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(ze,{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 mt({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 ht({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 xt(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,l=A.useRef(null);return A.useEffect(()=>{const o=c=>{const i=c.target;l.current&&l.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,a,r]),l}function we(t,n){var a;return((a=n.find(r=>r.value===t))==null?void 0:a.label)||t}function an(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function pt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function nn(t,n,a){const r=pt(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 rn({user:t}){return pt(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 ln({user:t,userShare:n,usersToUpdate:a,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(n!=null&&n.role))return null;const c=an((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(ze,{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:we(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function on({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(Ye,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function cn({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 dn({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,y;const b=((f=n.find(E=>E.id===x.orgUserId))==null?void 0:f.name)||"Unknown User",p=((y=n.find(E=>E.id===x.orgUserId))==null?void 0:y.type)||"",j=we(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,y;const b=((f=n.find(E=>E.id===x.tenantUserId))==null?void 0:f.name)||"Unknown User",p=((y=n.find(E=>E.id===x.tenantUserId))==null?void 0:y.type)||"",j=we(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=we(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=we(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=we(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=we(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=we(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=we(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=we(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 un({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 mn({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(rn,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!a?e.jsx(ze,{currentRole:n==null?void 0:n.role,onRoleChange:b=>x(t.id,n.role,b),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(ln,{user:t,userShare:n,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:x}),o&&!l&&e.jsx("div",{onClick:b=>b.stopPropagation(),children:e.jsx(ze,{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(on,{hasAccess:r,isUserRemoving:a,isSelected:o,hasAccessFromAPI:l}),e.jsx(cn,{isUserRemoving:a,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function ft({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||(C=>{const S=m.some(k=>k.id===C),v=h.includes(C);S?b.removeSelectedUser(C):v?b.removeUserFromRemove(C):b.addSelectedUser({id:C,role:"VIEWER"})}),j=i||b.updateSelectedUserRole,f=d||b.addUserToRemove,y=u||((C,S,v)=>{b.addUserToUpdate({id:C,currentRole:S,newRole:v})}),E=l,D=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 (",(E??[]).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(dn,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:o})})]})})]}),(E==null?void 0:E.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===E.length?b.setSelectedUsers([]):b.setSelectedUsers(E.map(C=>({id:C.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:m.length===E.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(un,{isInitialLoading:n,isSearching:a,searchQuery:g,availableUsers:E||[]}),!n&&!a&&(E==null?void 0:E.length)>0&&E.map(C=>{const S=t?nn(C,t,o):void 0,v=D.includes(C.id),k=!!S,N=k&&!v,F=m.some(I=>I.id===C.id),T=m.find(I=>I.id===C.id),B=r(C.type);return e.jsx(mn,{user:C,userShare:S,isUserRemoving:v,hasAccess:N,hasAccessFromAPI:k,isSelected:F,selectedUser:T,roleOptions:B,currentUser:o,usersToUpdate:x,handleUserToggle:p,handleRemoveAccess:f,handleUpdateAccess:y,handleUserRoleChange:j},C.id)})]})]})}function Is({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 Ce=()=>[{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 hn({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=Ce().filter(y=>y.value==="VIEWER"||y.value==="EDITOR"||y.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=y=>{switch(y){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(Ua,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},f=y=>{r(m,y)};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(y=>e.jsxs(s.Button,{variant:h===y.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>f(y.value),disabled:a||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[j(y.value),e.jsx("span",{className:"font-medium",children:y.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:y.description})]},y.value))})]})})]})})}function gt({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(hn,{currentUser:t,currentShare:h,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:g,onRemoveAccess:b,allUsersToUpdate:x,allUsersToRemove:d})}function He(t){const{debouncedSearchQuery:n,resourceId:a,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:o}=t,c=A.useMemo(()=>({search:n,active:!0,...l?{type:l}:{},...l==="tenant"&&o?{tenantId:o}:{}}),[n,l,o]),{users:i,isLoading: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 xn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var _,W;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(),[y,E]=A.useState("specific_users"),D=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},C=()=>{if(i==="tenant"&&d)return d},{allUsers:S,existingShares:v,isLoadingUsers:k}=He({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:D(),tenantId:C()});A.useEffect(()=>{f.setCurrentContext("org-tab"),f.setCurrentMode(y==="all_users"?"allOrgUsers":"specificOrgUsers")},[f,y]);const N=$=>{var Y,K;const X=$;if(E(X),r==null||r(X),f.setCurrentContext("org-tab"),X==="specific_users")f.setCurrentMode("specificOrgUsers");else if(X==="all_users"){f.setCurrentMode("allOrgUsers");const U=(K=(Y=v==null?void 0:v.shares)==null?void 0:Y.orgUsersOnly)==null?void 0:K[0];U&&U.role!==void 0&&f.setOrgWideRole(U.role)}},F=S.filter($=>$.name.toLowerCase().includes(u.toLowerCase())||$.email.toLowerCase().includes(u.toLowerCase())),T=S.filter($=>x.some(X=>X.id===$.id)),B=$=>{var U,Z;const X=x.some(ne=>ne.id===$),Y=g.includes($),K=(Z=(U=v==null?void 0:v.shares)==null?void 0:U.specificOrgUsers)==null?void 0:Z.some(ne=>ne.orgUserId===$);X?f.removeSelectedUser($):Y?f.removeUserFromRemove($):K||f.addSelectedUser({id:$,role:"VIEWER"})},I=($,X)=>{f.updateSelectedUserRole($,X)},w=$=>{f.addUserToRemove($),f.removeSelectedUser($)},M=$=>{f.removeUserFromRemove($)},L=$=>{f.removeUserFromUpdate($)},O=($,X)=>{f.setOrgWideRole(X)},R=()=>{f.setOrgWideRole((z==null?void 0:z.role)||"NONE")},z=(W=(_=v==null?void 0:v.shares)==null?void 0:_.orgUsersOnly)==null?void 0:W[0];A.useEffect(()=>{y==="all_users"&&z&&z.role!==void 0&&f.setOrgWideRole(z.role)},[y,z,f]);const G=k,Q=!1;return a?e.jsxs(e.Fragment,{children:[e.jsx(Is,{shareType:y,onShareTypeChange:N,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??"")}]}),y==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(cs,{value:u,onChange:m}),e.jsx(ut,{selectedUsers:x,selectedUserObjects:T,onRemove:B,onRoleChange:I,getRoleOptions:Ce}),e.jsx(mt,{usersToRemove:g,allUsers:F,onRemove:M}),e.jsx(ht,{usersToUpdate:b,allUsers:F,onRemove:L,getRoleOptions:Ce}),e.jsx(ft,{existingShares:v,isInitialLoading:G,isSearching:Q,resource:t,onShare:()=>{},getRoleOptions:Ce,allUsers:F,currentUser:a,handleUserToggle:B,handleUserRoleChange:I,handleRemoveAccess:w,handleUpdateAccess:($,X,Y)=>{f.addUserToUpdate({id:$,currentRole:X,newRole:Y})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(gt,{currentUser:a,currentShare:z,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:O,onRemoveAccess:R,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 pn(t){switch(t){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function fn(t){switch(t){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function jt({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),y=h.includes(p.id),E=x.find(v=>v.id===p.id),D=!!j&&!y;let S=(j==null?void 0:j.role)||"VIEWER";if(f){const v=m.find(k=>k.id===p.id);S=(v==null?void 0:v.role)||"VIEWER"}else E&&(S=E.newRole);return e.jsxs("div",{className:s.cn("flex items-center justify-between rounded-lg p-2 transition-colors",D&&!y?"border border-green-200 bg-green-50":y?"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:D?!y:f,disabled:!1,onCheckedChange:()=>{D?y?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",fn(p.type)),children:pn(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:[D&&!y?e.jsx(ze,{currentRole:S,onRoleChange:v=>{j&&v!==j.role&&(u==null||u(p.id,j.role,v))},roleOptions:b,disabled:!1,allowDropdown:!0,className:E?"border-orange-300 bg-orange-100":""}):f&&!D&&e.jsx(ze,{currentRole:S,onRoleChange:v=>i==null?void 0:i(p.id,v),roleOptions:b,disabled:!1}),D&&!y&&!E&&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"})}),y&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromRemove(p.id),children:"Undo"}),E&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromUpdate(p.id),children:"Cancel"})]})]},p.id)})})]})}function bt({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(ze,{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 qs({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var H;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(),y=s.useShareAllTenantsRole(),E=s.useShareSelectedTenant(),D=s.useShareManagementActions(),{data:C,isLoading:S}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"}),{groups:v,isLoading:k}=s.useShareableGroups("tenant",(a==null?void 0:a.tenantId)||E),[N,F]=A.useState((a==null?void 0:a.type)==="organization"?"all_tenants":"specific_tenant_users");A.useEffect(()=>{(a==null?void 0:a.type)==="tenant"?(D.setCurrentContext("tenant-dialog"),D.setCurrentMode("specificTenantUsers")):(D.setCurrentContext("tenant-tab"),D.setCurrentMode("allTenants"))},[D,a==null?void 0:a.type]);const T=P=>{var ee,oe,le,ue;F(P);let J;if(P==="specific_tenant_users"?J="specific_users":P==="all_tenant_users"||P==="all_tenants"?J="all_users":P==="groups"?J="groups":J="specific_users",r==null||r(J),P==="groups"?(D.setCurrentContext("group-share"),D.setCurrentMode("specificGroups")):(a==null?void 0:a.type)==="tenant"?(D.setCurrentContext("tenant-dialog"),P==="specific_tenant_users"?D.setCurrentMode("specificTenantUsers"):P==="all_tenant_users"&&(D.setCurrentMode("allTenantUsers"),a!=null&&a.tenantId&&D.setSelectedTenant(a.tenantId))):(D.setCurrentContext("tenant-tab"),P==="specific_tenant_users"?D.setCurrentMode("specificTenantUsers"):P==="all_tenant_users"?D.setCurrentMode("allTenantUsers"):P==="all_tenants"&&D.setCurrentMode("allTenants")),P==="all_tenant_users"){const ce=(oe=(ee=w==null?void 0:w.shares)==null?void 0:ee.tenantWide)==null?void 0:oe[0];ce&&ce.role!==void 0&&D.setTenantWideRole(ce.role)}else if(P==="all_tenants"){const ce=(ue=(le=w==null?void 0:w.shares)==null?void 0:le.allTenantsOnly)==null?void 0:ue[0];ce&&ce.role!==void 0&&D.setAllTenantsRole(ce.role)}},B=P=>{D.setSelectedTenant(P)},{allUsers:I,existingShares:w,isLoadingUsers:M,isErrorLoadingUsers:L,isLoadingShares:O,isErrorLoadingShares:R}=He({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant",tenantId:(a==null?void 0:a.type)==="tenant"?a.tenantId:E}),z=P=>{var le,ue;const J=m.some(ce=>ce.id===P),ee=h.includes(P),oe=(ue=(le=w==null?void 0:w.shares)==null?void 0:le.specificTenantUsers)==null?void 0:ue.some(ce=>ce.tenantUserId===P);J?D.removeSelectedUser(P):ee?D.removeUserFromRemove(P):oe||D.addSelectedUser({id:P,role:"VIEWER"})},G=(P,J)=>{D.updateSelectedUserRole(P,J)},Q=P=>{D.addUserToRemove(P),D.removeSelectedUser(P)},_=P=>{D.removeUserFromRemove(P)},W=P=>{D.removeUserFromUpdate(P)},$=(P,J,ee)=>{D.addUserToUpdate({id:P,currentRole:J,newRole:ee})},X=(P,J)=>{N==="all_tenant_users"?D.setTenantWideRole(J):N==="all_tenants"&&D.setAllTenantsRole(J)},Y=()=>{N==="all_tenant_users"?D.setTenantWideRole("VIEWER"):N==="all_tenants"&&D.setAllTenantsRole("VIEWER")},U=(()=>{var P,J,ee,oe;return j==="allTenants"?(J=(P=w==null?void 0:w.shares)==null?void 0:P.allTenantsOnly)==null?void 0:J[0]:j==="allTenantUsers"?(oe=(ee=w==null?void 0:w.shares)==null?void 0:ee.tenantWide)==null?void 0:oe[0]:null})();A.useEffect(()=>{var P,J,ee,oe;if(N==="all_tenant_users"){const le=(J=(P=w==null?void 0:w.shares)==null?void 0:P.tenantWide)==null?void 0:J[0];le&&le.role!==void 0&&D.setTenantWideRole(le.role)}else if(N==="all_tenants"){const le=(oe=(ee=w==null?void 0:w.shares)==null?void 0:ee.allTenantsOnly)==null?void 0:oe[0];le&&le.role!==void 0&&D.setAllTenantsRole(le.role)}},[N,w,D]);const Z=I.filter(P=>m.some(J=>J.id===P.id)),ne=P=>{const J=g.some(le=>le.id===P),ee=b.includes(P),oe=re==null?void 0:re.some(le=>le.groupId===P);J?D.removeSelectedGroup(P):ee?D.removeGroupFromRemove(P):oe||D.addSelectedGroup({id:P,role:"VIEWER"})},he=(P,J)=>{D.updateSelectedGroupRole(P,J)},ge=P=>{D.addGroupToRemove(P),D.removeSelectedGroup(P)},V=(P,J,ee)=>{D.addGroupToUpdate({id:P,currentRole:J,newRole:ee})},se=v.filter(P=>g.some(J=>J.id===P.id)),te=A.useMemo(()=>N!=="groups"?[]:v.filter(P=>P.type!=="TENANT_GROUP"?!1:P.name.toLowerCase().includes(i.toLowerCase())||P.description&&P.description.toLowerCase().includes(i.toLowerCase())),[v,N,i]),re=A.useMemo(()=>{var J,ee;const P=((J=w==null?void 0:w.shares)==null?void 0:J.specificGroups)||((ee=w==null?void 0:w.shares)==null?void 0:ee.groups)||[];return!P||P.length===0?[]:P.filter(oe=>{const le=v.find(ue=>ue.id===oe.groupId);return(le==null?void 0:le.type)==="TENANT_GROUP"})},[w,v]),ie=M||O||N==="groups"&&k,de=L||R,xe=()=>(a==null?void 0:a.type)==="tenant"||N==="all_tenants"||N==="groups"?!0:E&&(N==="specific_tenant_users"||N==="all_tenant_users");return e.jsxs(e.Fragment,{children:[de&&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"})]})}),!de&&a&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(Is,{shareType:N,onShareTypeChange:T,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(Gs,{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"&&(N==="specific_tenant_users"||N==="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:E||"",onValueChange:B,disabled:S,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:S?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(H=C==null?void 0:C.tenants)==null?void 0:H.map(P=>e.jsx(s.SelectItem,{value:P.id,children:P.name},P.id))})]})]}),xe()?e.jsx(e.Fragment,{children:N==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(cs,{value:i,onChange:u}),e.jsx(ut,{selectedUsers:m,selectedUserObjects:Z,onRemove:P=>z(P),onRoleChange:G,getRoleOptions:Ce}),e.jsx(mt,{usersToRemove:h,allUsers:I,onRemove:_}),e.jsx(ht,{usersToUpdate:x,allUsers:I,onRemove:W,getRoleOptions:Ce}),e.jsx(ft,{existingShares:w,isInitialLoading:!!ie,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:Ce,allUsers:I,currentUser:a,handleUserToggle:z,handleUserRoleChange:G,handleRemoveAccess:Q,handleUpdateAccess:$})]}):N==="groups"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(cs,{value:i,onChange:u,placeholder:"Search groups..."}),e.jsx(bt,{selectedGroups:g,groupObjects:se,onRemove:ne,onRoleChange:he,getRoleOptions:Ce}),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(jt,{groups:te,existingGroupShares:re,isLoading:k,resource:t,getRoleOptions:Ce,currentUser:a,handleGroupToggle:ne,handleGroupRoleChange:he,handleRemoveAccess:ge,handleUpdateAccess:V})]}):N==="all_tenant_users"||N==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(gt,{currentUser:a,currentShare:U,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:X,onRemoveAccess:Y,allUsersToUpdate:j==="allTenantUsers"&&((U==null?void 0:U.role)===void 0||f!==U.role)||j==="allTenants"&&((U==null?void 0:U.role)===void 0||y!==U.role)?{currentRole:(U==null?void 0:U.role)||"VIEWER",newRole:j==="allTenantUsers"?f:y}:null,allUsersToRemove:j==="allTenantUsers"&&(U==null?void 0:U.role)===void 0||j==="allTenants"&&(U==null?void 0:U.role)===void 0})}):null}):(a==null?void 0:a.type)==="organization"&&(N==="specific_tenant_users"||N==="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(Gs,{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 gn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var L,O;const{searchQuery:i,setSearchQuery:d}=s.useShareSearchWithDebounce(),u=s.useShareSelectedGroups(),m=s.useShareGroupsToRemove(),h=s.useShareGroupsToUpdate(),x=s.useShareManagementActions(),[g,b]=A.useState("org_groups"),[p,j]=A.useState(""),{data:f,isLoading:y}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"&&g==="tenant_groups"}),E=Array.isArray(f)?f:(f==null?void 0:f.tenants)||[],D=()=>{if((a==null?void 0:a.type)==="organization")return"organization";if((a==null?void 0:a.type)==="tenant")return"tenant"},{groups:C,isLoading:S}=s.useShareableGroups(D(),g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"?p:a==null?void 0:a.tenantId),{existingShares:v}=He({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n}),k=C.filter(R=>g==="org_groups"&&R.type!=="ORG_GROUP"||g==="tenant_groups"&&R.type!=="TENANT_GROUP"||g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&(!p||R.tenantId&&R.tenantId!==p)?!1:R.name.toLowerCase().includes(i.toLowerCase())||R.description&&R.description.toLowerCase().includes(i.toLowerCase())),N=((L=v==null?void 0:v.shares)==null?void 0:L.specificGroups)||((O=v==null?void 0:v.shares)==null?void 0:O.groups)||[];A.useEffect(()=>{x.setCurrentContext("group-share"),x.setCurrentMode("specificGroups")},[x]);const F=R=>{const z=R;b(z),z==="org_groups"&&j(""),r==null||r(z==="org_groups"?"specific_groups":"all_groups"),x.setCurrentContext("group-share"),x.setCurrentMode("specificGroups")},T=C.filter(R=>u.some(z=>z.id===R.id)),B=R=>{const z=u.some(_=>_.id===R),G=m.includes(R),Q=N==null?void 0:N.some(_=>_.groupId===R);z?x.removeSelectedGroup(R):G?x.removeGroupFromRemove(R):Q||x.addSelectedGroup({id:R,role:"VIEWER"})},I=(R,z)=>{x.updateSelectedGroupRole(R,z)},w=R=>{x.addGroupToRemove(R),x.removeSelectedGroup(R)},M=(R,z,G)=>{x.addGroupToUpdate({id:R,currentRole:z,newRole:G})};return a?e.jsxs(e.Fragment,{children:[e.jsx(Is,{shareType:g,onShareTypeChange:F,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:y,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:y?"Loading tenants...":"Select a tenant to view its groups"})}),e.jsx(s.SelectContent,{className:"z-[51]",children:E.map(R=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:R.id,children:R.name},R.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(cs,{value:i,onChange:d,placeholder:"Search groups..."}),e.jsx(bt,{selectedGroups:u,groupObjects:T,onRemove:B,onRoleChange:I,getRoleOptions:Ce}),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(jt,{groups:k,existingGroupShares:N,isLoading:S,resource:t,getRoleOptions:Ce,currentUser:a,handleGroupToggle:B,handleGroupRoleChange:I,handleRemoveAccess:w,handleUpdateAccess:M})]})})]}):null}const vt=()=>{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=A.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=A.useMemo(()=>j=>s.validateShareData(j),[]),p=A.useMemo(()=>{if(!t||!n)return!1;switch(t){case"org-tab":return n==="specificOrgUsers"?a.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(n==="allTenantUsers"){if(!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 Hs({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:y,isCurrentStateValid:E}=vt(),D=a||r||l,C=()=>{var F,T,B,I;if(D)return"Updating...";if(i==="specific_users"){if(m.length===0&&h.length===0&&x.length===0)return"Select users to share with";const w=m.length+h.length+x.length;return w===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${w} user${w!==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 ${w} user${w!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const w=d.role;return b===w?"Remove Access":"Update Access"}else if(i==="all_tenants"){const w=(T=(F=n==null?void 0:n.shares)==null?void 0:F.allTenantsOnly)==null?void 0:T[0];if(!w||w.role===void 0)return"Share with All Tenants";const M=w.role;return p===M?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const w=(I=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:I[0];if(!w||w.role===void 0)return"Share with All Tenant Users";const M=w.role;return j===M?"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 w=m.length+h.length+x.length;return w===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${w} user${w!==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 ${w} user${w!==1?"s":""}`}return"Share"},S=()=>D||!t||i==="all_tenant_users"&&!g||i==="specific_tenant_users"&&!g?!0:!E,v=()=>{const F=f();F&&y(F)&&o(F)},k=()=>{var F,T,B,I;if(i==="all_users")if(!d||d.role===void 0){const w=f();w&&y(w)&&o(w)}else{const w=d.role;if(b===w)u==null||u();else{const L=f();if(L&&y(L)){const O={...L,updateAccess:!0};o(O)}}}else if(i==="all_tenants"){const w=(T=(F=n==null?void 0:n.shares)==null?void 0:F.allTenantsOnly)==null?void 0:T[0];if(!w||w.role===void 0){const M=f();M&&y(M)&&o(M)}else{const M=w.role;if(p===M)u==null||u();else{const O=f();if(O&&y(O)){const R={...O,updateAccess:!0};o(R)}}}}else if(i==="all_tenant_users"){const w=(I=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:I[0];if(!w||w.role===void 0){const M=f();M&&y(M)&&o(M)}else{const M=w.role;if(j===M)u==null||u();else{const O=f();if(O&&y(O)){const R={...O,updateAccess:!0};o(R)}}}}},N=()=>{var F,T,B,I;if(i==="all_users"){if(!d||d.role===void 0)return"default";const w=d.role;return b===w?"destructive":"default"}else if(i==="all_tenants"){const w=(T=(F=n==null?void 0:n.shares)==null?void 0:F.allTenantsOnly)==null?void 0:T[0];if(!w||w.role===void 0)return"default";const M=w.role;return p===M?"destructive":"default"}else if(i==="all_tenant_users"){const w=(I=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:I[0];if(!w||w.role===void 0)return"default";const M=w.role;return j===M?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:D,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||D,variant:"default",children:[D?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!D&&C()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:k,disabled:S(),variant:N(),children:[D?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"}),!D&&C()]})]})}function jn({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}=vt(),y=n||a||r,E=()=>{if(y)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&m.length===0)return"Select users to share with";const N=d.length+u.length+m.length;return N===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${N} user${N!==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 ${N} user${N!==1?"s":""}`}else if(c==="groups"){if(h.length===0&&x.length===0&&g.length===0)return"Select groups to share with";const N=h.length+x.length+g.length;return N===0?"Select groups to share with":h.length>0&&x.length>0?`Update access for ${N} group${N!==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 ${N} group${N!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const N=i.role;return b===N?"Remove Access":"Update Access"}return"Share"},D=()=>y||!t?!0:!f,C=()=>{const N=p();N&&j(N)&&l(N)},S=()=>{const N=p();N&&j(N)&&l(N)},v=()=>{if(!i||i.role==="NONE"){const N=p();N&&j(N)&&l(N)}else{const N=i.role;if(b===N){const T=p();if(T&&j(T)){const B={...T,removeAccess:!0};l(B)}}else{const T=p();if(T&&j(T)){const B={...T,updateAccess:!0};l(B)}}}},k=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:o,disabled:y,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:C,disabled:!t||y,variant:"default",children:[y?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!y&&E()]})}),c==="groups"&&e.jsx(e.Fragment,{children:(h.length>0||x.length>0||g.length>0)&&e.jsxs(s.Button,{onClick:S,disabled:!t||y,variant:"default",children:[y?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!y&&E()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:v,disabled:D(),variant:k(),children:[y?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!y&&E()]})]})}function bn({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 ye(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function ke(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function vn(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=ye(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=ye(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=ke(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=ye(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=ye(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="allTenantUsers"){const u=ye(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=ke(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(y=>y.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=ye(r,l,[{scope:"specific_tenant_user",tenantUserId:g.id,tenantId:x,role:g.newRole}]);o(b,{onSuccess:()=>{d()}})}),u&&u.length>0){const g=ye(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=ke(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);c(u,{onSuccess:()=>{d()}})}else if(t.updateAccess){const u=ye(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else{const u=ye(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=ye(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=ke(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=ye(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=ye(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=ke(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=ye(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 yn(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=ke(l,o,t.map(j=>{var y,E;const f=(E=(y=i==null?void 0:i.shares)==null?void 0:y.specificTenantUsers)==null?void 0:E.find(D=>D.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 y=ke(l,o,[{scope:"all_tenants_only",role:f.role}]);c(y,{onSuccess:()=>{d()},onError:E=>{console.error("Remove all-tenants access failed:",E)}})}}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 y=ke(l,o,[{scope:"all_tenant_users",role:f.role}]);c(y,{onSuccess:()=>{d()},onError:E=>{console.error("Remove all-tenant-users access failed:",E)}})}}else{const f=(b=(g=i==null?void 0:i.shares)==null?void 0:g.orgUsersOnly)==null?void 0:b[0];if(f){const y=ke(l,o,[{scope:"org_users_only",role:f.role}]);c(y,{onSuccess:()=>{d()},onError:E=>{console.error("Remove org-wide access failed:",E)}})}}}}function Nn(t,n,a){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=s.useCurrentUserInfo(),{existingShares:d}=He({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),u=A.useCallback(()=>{r.resetUserSelections()},[r]),m=A.useCallback(()=>{r.resetGroupSelections()},[r]),h=A.useCallback(g=>{if(!t)return;const b={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:n,removeMutation:a,existingShares:d,resetUserSelections:u,resetGroupSelections:m};vn(g,b,i)},[t,n,a,d,u,m,i]),x=A.useCallback(()=>{if(!t)return;const g={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:a,existingShares:d,resetUserSelections:u};yn(l,o||"",c||"",g)},[t,n,a,d,u,m,l,o,c]);return{handleShareSubmit:h,handleRemoveAccess:x}}function hs({resource:t,resourceType:n,onClose:a,onShareSuccess:r,onRemoveSuccess:l}){var I,w,M,L,O,R,z,G;const{currentUser:o}=s.useCurrentUserInfo(),[c,i]=A.useState("specific_users"),[d,u]=A.useState("specific_users"),[m,h]=A.useState("specific_groups"),x=s.useShareManagementActions(),g=s.useShareSelectedTab(),b=s.useShareCurrentMode(),p=s.useShareResource(),j=s.useRemoveResourceShares(),{handleShareSubmit:f,handleRemoveAccess:y}=Nn(t.id,(Q,_)=>{p.mutate(Q,{..._,onSuccess:()=>{var W;(W=_==null?void 0:_.onSuccess)==null||W.call(_),r==null||r()}})},(Q,_)=>{j.mutate(Q,{..._,onSuccess:()=>{var W;(W=_==null?void 0:_.onSuccess)==null||W.call(_),l==null||l()}})}),E=p.isPending,D=j.isPending,C=p.isPending,{existingShares:S}=He({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant"}),{existingShares:v}=He({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"organization"}),k=(w=(I=S==null?void 0:S.shares)==null?void 0:I.tenantWide)==null?void 0:w[0],N=(L=(M=v==null?void 0:v.shares)==null?void 0:M.orgUsersOnly)==null?void 0:L[0],F=()=>{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"}},T=A.useCallback(()=>{x.resetShareState(),a()},[x,a]),B=(o==null?void 0:o.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:T,children:e.jsxs(s.DialogContent,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ye,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:B?"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."})]}),B?e.jsxs(s.Tabs,{value:g,onValueChange:Q=>{const _=Q;x.setSelectedTab(_),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(xn,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:u,isSharing:E,isUpdating:C,isRemoving:D})})}),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(qs,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:Q=>i(Q),isSharing:E,isUpdating:C,isRemoving:D})})}),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(gn,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:h,isSharing:E,isUpdating:C,isRemoving:D})})})]}):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(qs,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:Q=>i(Q),isSharing:E,isUpdating:C,isRemoving:D})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:B?g==="org"?e.jsx(Hs,{resource:t,existingShares:v,isSharing:E,isRemoving:D,isUpdating:C,onShare:f,onClose:a,shareTabType:d,currentAllUsersShare:N,onRemoveAccess:y}):g==="tenant"?e.jsx(Hs,{resource:t,existingShares:S,isSharing:E,isRemoving:D,isUpdating:C,onShare:f,onClose:a,shareTabType:F(),currentAllUsersShare:k,onRemoveAccess:y}):e.jsx(bn,{resource:t,existingShares:v,isSharing:E,isRemoving:D,isUpdating:C,onShare:f,onClose:a,shareTabType:m,currentAllGroupsShare:(o==null?void 0:o.type)==="organization"?(R=(O=v==null?void 0:v.shares)==null?void 0:O.allOrgGroups)==null?void 0:R[0]:(G=(z=S==null?void 0:S.shares)==null?void 0:z.allTenantGroups)==null?void 0:G[0],onRemoveAccess:y}):e.jsx(jn,{resource:t,isSharing:E,isRemoving:D,isUpdating:C,onShare:f,onClose:a,shareTabType:c,currentAllUsersShare:k,onRemoveAccess:y})})]})})}function yt({type:t,isLinked:n,className:a}){const r=s.useDashboardStore(u=>u.selectedFrameId),l=s.useManagementStore(u=>u.selectedVisual),o=s.useEditorStore(u=>u.frame);let c;if(t)c=t;else if(n!==void 0)c=n?"linked":"library";else if(!!!(o!=null&&o.visualId||l!=null&&l.id)&&r)c="local";else if(l&&!r)c="library";else if(o!=null&&o.visualId&&r)c="linked";else if(l!=null&&l.id&&r)c="library";else return null;const i={local:"bg-gray-100 text-gray-700",linked:"bg-purple-100 text-purple-700",library:"bg-blue-100 text-blue-700"},d={local:"Local Visual",linked:"Linked Visual",library:"Library Visual"};return e.jsx("span",{className:s.cn("rounded-full px-2.5 py-0.5 text-xs font-medium",i[c],a),children:d[c]})}const Cn=async(t,n,a)=>{const r=`${t}/management/v1/groups`;return await s.postRequestRegular(r,n,a)},Sn=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")}},wn=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`;return await s.postRequestRegular(l,n,r)},Dn=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 Tn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>Cn(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 kn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>Sn(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["groups"]}),a.removeQueries({queryKey:["group",l]}),s.ue.success("Group deleted successfully")},onError:r=>{console.error("Failed to delete group:",r),s.ue.error("Failed to delete group",{description:r.message})}})}function En(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>wn(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 In(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>Dn(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 An({onSuccess:t,tenantId:n,isTenantUser:a}){const[r,l]=A.useState(""),[o,c]=A.useState(""),[i,d]=A.useState({}),u=Tn(),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 Mn({open:t,onOpenChange:n,group:a,onUpdate:r}){const[l,o]=A.useState("members"),[c,i]=A.useState(""),[d,u]=A.useState([]),[m,h]=A.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}),y=En(),E=In(),D=(x==null?void 0:x.members)||[],C=A.useMemo(()=>new Set(D.map(I=>I.userId)),[D]),S=A.useMemo(()=>j.filter(I=>!C.has(I.id)),[j,C]),v=A.useMemo(()=>{if(!c)return S;const I=c.toLowerCase();return S.filter(w=>{var M,L;return((M=w.name)==null?void 0:M.toLowerCase().includes(I))||((L=w.email)==null?void 0:L.toLowerCase().includes(I))})},[S,c]),k=A.useMemo(()=>{if(!c)return D;const I=c.toLowerCase();return D.filter(w=>{var M,L,O,R;return((L=(M=w.user)==null?void 0:M.name)==null?void 0:L.toLowerCase().includes(I))||((R=(O=w.user)==null?void 0:O.email)==null?void 0:R.toLowerCase().includes(I))})},[D,c]),N=async()=>{if(d.length!==0)try{await y.mutateAsync({groupId:a.id,data:{userIds:d,userType:p==="tenant"?"tenant":"org"}}),u([]),o("members"),b(),r==null||r()}catch(I){console.error("Failed to add members:",I)}},F=async()=>{if(m.length!==0)try{await E.mutateAsync({groupId:a.id,data:{userIds:m}}),h([]),b(),r==null||r()}catch(I){console.error("Failed to remove members:",I)}},T=I=>{u(w=>w.includes(I)?w.filter(M=>M!==I):[...w,I])},B=I=>{h(w=>w.includes(I)?w.filter(M=>M!==I):[...w,I])};return e.jsx(e.Fragment,{children:e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-3xl max-h-[80vh]","aria-describedby":"group-members-description",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:a.name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[D.length," ",D.length===1?"member":"members"]})}),e.jsxs("p",{id:"group-members-description",className:"sr-only",children:["Add or remove members from the ",a.name," group"]})]}),e.jsxs(s.Tabs,{value:l,onValueChange:I=>{o(I),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:I=>i(I.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(I=>e.jsx(s.Skeleton,{className:"h-16 w-full"},I))}):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(I=>e.jsx(Ln,{member:I,selected:m.includes(I.userId),onToggle:()=>B(I.userId)},I.id))})}),m.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[m.length," member",m.length!==1?"s":""," selected"]}),e.jsx(s.Button,{variant:"destructive",size:"sm",onClick:F,disabled:E.isPending,children:E.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:I=>i(I.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(I=>e.jsx(s.Skeleton,{className:"h-16 w-full"},I))}):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(I=>e.jsx(Rn,{user:I,selected:d.includes(I.id),onToggle:()=>T(I.id)},I.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:N,disabled:y.isPending,children:y.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 Ln({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 Rn({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 On({open:t,onOpenChange:n}){const[a,r]=A.useState("groups"),[l,o]=A.useState(""),[c,i]=A.useState(null),[d,u]=A.useState(!1),[m,h]=A.useState(null),{tokenProps:x}=s.useSemaphorContext(),{currentUser:g}=s.useCurrentUserInfo(),b=kn(),p=(g==null?void 0:g.type)==="tenant",j=x==null?void 0:x.tenantId,{groups:f,isLoading:y,refetch:E}=s.useGroups({type:p?"TENANT_GROUP":"all",tenantId:p?j:void 0,includeMembers:!1}),D=f.filter(k=>{var N;return k.name.toLowerCase().includes(l.toLowerCase())||((N=k.description)==null?void 0:N.toLowerCase().includes(l.toLowerCase()))}),C=async()=>{if(m)try{await b.mutateAsync(m.id),h(null),E()}catch(k){console.error("Failed to delete group:",k)}},S=k=>{i(k),u(!0)},v=()=>{r("groups"),E()};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:y?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(k=>e.jsx(s.Skeleton,{className:"h-24 w-full"},k))}):D.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:D.map(k=>e.jsx(Fn,{group:k,onManageMembers:()=>S(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(An,{onSuccess:v,tenantId:j,isTenantUser:p})})]})]})}),c&&e.jsx(Mn,{open:d,onOpenChange:u,group:c,onUpdate:()=>E()}),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:C,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 Fn({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 As(t){const[n,a]=A.useState(null),[r,l]=A.useState(null);return A.useEffect(()=>{if(!t||t.trim()===""){a(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const 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 Bn(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 Pn(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 Ws(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 Nt(t){if(typeof t=="string")return JSON.parse(t);if(typeof t=="object")return t;throw new Error("Invalid frame object format")}function zn(t,n){var o,c;const a=(t==null?void 0:t.frameObject)??((o=t==null?void 0:t.visual)==null?void 0:o.frameObject);if(!a)return!1;const r=Nt(a);if(!(r!=null&&r.cards)||r.cards.length===0)return!1;const l=(c=r.cards)==null?void 0:c.find(i=>i.id===r.activeCardId);return l?(s.setupEditorWithCard({...n,frame:r,card:l,visualId:(t==null?void 0:t.id)||r.visualId}),!0):!1}function Vn(){var x;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(g=>g.frame),a=s.useEditorStore(g=>g.card),r=As(((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:A.useCallback(()=>{var f;let g=m;m&&!m.includes("{{")&&(g=Bn(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(y=>y.id===a.id?p:y);return{...n,cards:j,activeCardId:Pn(j,n.activeCardId)}},[a,n,u,l,o,c,i,d,t,r,m])}}function Ve(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient(),r=s.useSelectedVisual(),{selectVisual:l}=s.useManagementActions(),{setFrame:o,setCard:c,setIsDevMode:i,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:h,setSelectedDatabaseName:x,setSelectedSchemaName:g,setSelectedTableName:b,setSelectedDatamodelId:p,setFilterValues:j,setApplyFilters:f}=s.useEditorActions(),{setIsDashboardEditing:y,setIsVisualEditing:E,setSelectedFrameId:D,clearSelectedFrameId:C,addFrame:S,setIsDashboardPanelOpen:v}=s.useDashboardActions(),k=s.useDashboardStore(M=>M.selectedSheetId),N=s.useDashboardStore(M=>M.selectedFrameId),F=s.useDashboardStore(M=>M.dashboard),T=s.useDashboardStore(M=>M.filterValues),B=s.useVisualById((r==null?void 0:r.id)||"",{enabled:!!(r!=null&&r.id)&&!!(t!=null&&t.accessToken)}),I=A.useCallback(async M=>{try{l(M),C();const{data:L,fromCache:O}=await Ws(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",M.id,a);if(!zn(L,{setFrame:o,setCard:c,setIsDevMode:i,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:h,setSelectedDatabaseName:x,setSelectedSchemaName:g,setSelectedTableName:b,setSelectedDatamodelId:p,setFilterValues:j,setApplyFilters:f,setIsDashboardEditing:y,setIsVisualEditing:E,dashboard:F,selectedSheetId:k,selectedFrameId:N,filterValues:T}))throw new Error("Failed to setup editor with visual data");return{success:!0,fromCache:O}}catch(L){return console.error("Error editing visual:",L),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,o,c,y,E,i,d,u,m,h,x,g,b,p,j,f,C,F,k,N,T]),w=A.useCallback(async M=>{var L;try{if(l(M),!k)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:O,fromCache:R}=await Ws(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",M.id,a),z=(O==null?void 0:O.frameObject)??((L=O==null?void 0:O.visual)==null?void 0:L.frameObject);if(!z)return{success:!1,error:"Visual has no frame data"};const G=Nt(z);if(!(G!=null&&G.cards)||G.cards.length===0)return{success:!1,error:"Visual frame is malformed"};const Q={...G,id:s.v4(),visualId:M.id};return S(k,Q,"end"),y(!0),D(Q.id),v(!1),{success:!0,fromCache:R}}catch(O){return console.error("Error adding visual:",O),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,k,S,y,D,v]);return{visual:B.data,isLoading:B.isLoading,isError:B.isError,error:B.error,handleEditLibraryVisual:I,handleAddLibraryVisual:w,getUpdatedFrame:Vn().getUpdatedFrame,refetch:B.refetch}}function _n({open:t,onOpenChange:n,isLibraryVisual:a,currentVisualName:r,isSaving:l=!1,onConfirm:o}){const[c,i]=A.useState(a&&r?`Copy of ${r}`:r||""),[d,u]=A.useState(""),[m,h]=A.useState(!a),[x,g]=A.useState(!0);A.useEffect(()=>{t&&(i(a&&r?`Copy of ${r}`:r||""),u(""),h(!a),g(!0))},[t,a,r]);const b=()=>{c.trim()&&(!m&&!x||o({name:c.trim(),description:d.trim()||void 0,saveToLibrary:m,saveToCurrentDashboard:x}))},p=c.trim()&&(m||x);return e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Save Visual As"}),e.jsx(s.DialogDescription,{children:a?"Create a copy of this visual with a new name":"Save this visual to make it reusable"})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"name",children:"Name"}),e.jsx(s.Input$1,{id:"name",value:c,onChange:j=>i(j.target.value),placeholder:"Enter visual name",disabled:l})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"description",children:"Description (optional)"}),e.jsx(s.Textarea,{id:"description",value:d,onChange:j=>u(j.target.value),placeholder:"Enter visual description",rows:3,disabled:l})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Label,{children:"Save to:"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"save-to-dashboard",checked:x,onCheckedChange:j=>g(!!j),disabled:l}),e.jsxs("label",{htmlFor:"save-to-dashboard",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Current Dashboard",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:a?"(add copy to this dashboard)":"(keep as local visual)"})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"save-to-library",checked:m,onCheckedChange:j=>h(!!j),disabled:l}),e.jsxs("label",{htmlFor:"save-to-library",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Visual Library",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:a?"(save as new reusable visual)":"(make available to all dashboards)"})]})]})]}),!m&&!x&&e.jsx("p",{className:"text-sm text-destructive",children:"Please select at least one destination"})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),disabled:l,children:"Cancel"}),e.jsxs(s.Button,{onClick:b,disabled:!p||l,children:[l&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Saving...":"Save"]})]})]})})}function Ct({className:t,variant:n="outline"}){var i;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(d=>d.frame);const r=s.useEditorStore(d=>d.card);As(((i=r.customCardPreferences)==null?void 0:i.url)||""),s.useEditorStore(d=>d.selectedSchemaName),s.useEditorStore(d=>d.selectedDatamodelId),s.useEditorStore(d=>d.selectedDatabaseName),s.useEditorStore(d=>d.selectedTableName),s.useEditorStore(d=>d.selectedConnectionId),s.useEditorStore(d=>d.isShowingVisual),r.sql;const l=s.useEditorStore(d=>d.onSave),{getUpdatedFrame:o}=Ve();function c(){const d=o();l==null||l(d)}return e.jsxs(s.Button,{onClick:c,className:s.cn("h-8",t),size:"sm",variant:n,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Un({className:t,variant:n="default"}){const a=s.useQueryClient(),[r,l]=A.useState(!1),o=s.useDashboardStore(x=>x.actions.setIsDashboardPanelOpen),{setIsVisualEditing:c}=s.useDashboardActions(),{getUpdatedFrame:i}=Ve(),d=s.useSelectedVisual(),u=s.useEditorStore(x=>x.frame),m=s.useUpdateVisualMutation(),h=()=>{const x=i(),g=(u==null?void 0:u.visualId)||(d==null?void 0:d.id);if(!g){s.ue.error("No visual to save");return}l(!0),m.mutate({visualId:g,data:{frameObject:x}},{onSuccess:()=>{l(!1),o(!0),s.ue.success("Visual updated successfully"),a.invalidateQueries({queryKey:["resource-by-id","visual",g],exact:!0})},onError:()=>{l(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:h,className:s.cn("h-8",t),size:"sm",variant:n,children:[r&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!r&&e.jsxs(e.Fragment,{children:[e.jsx(qe,{className:"mr-2 size-4 font-bold"}),"Save to Library"]})]})}function Gn({className:t}){const n=s.useQueryClient(),[a,r]=A.useState(!1),l=s.useSelectedVisual(),o=s.useEditorStore(x=>x.frame),c=s.useDashboardStore(x=>x.selectedSheetId),{updateFrame:i,setIsVisualEditing:d}=s.useDashboardActions(),{getUpdatedFrame:u}=Ve(),m=s.useUpdateVisualMutation(),h=async()=>{if(!c){s.ue.error("No sheet selected");return}const x=(o==null?void 0:o.visualId)||(l==null?void 0:l.id);if(!x){s.ue.error("No visual to update");return}r(!0);try{const g=u();await m.mutateAsync({visualId:x,data:{frameObject:g}});const b={...g,visualId:x};i(c,b),n.invalidateQueries({queryKey:["visuals"]}),n.invalidateQueries({queryKey:["visual",x]}),s.ue.success("Saved to library and applied locally"),setTimeout(()=>{d(!1)},300)}catch(g){console.error("Failed to save and apply:",g),s.ue.error("Failed to save and apply changes")}finally{r(!1)}};return e.jsx(s.Button,{onClick:h,className:s.cn("h-8",t),size:"sm",variant:"default",disabled:a,children:a?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(qe,{className:"mr-2 size-4 font-bold"}),"Save & Apply"]})})}function Yn({className:t}){const{getUpdatedFrame:n}=Ve();s.useEditorStore(d=>d.frame);const a=s.useDashboardStore(d=>d.selectedSheetId),{updateFrame:r,setIsVisualEditing:l}=s.useDashboardActions(),[o,c]=A.useState(!1),i=()=>{if(!a){s.ue.error("No sheet selected");return}c(!0);const u={...n(),visualId:void 0};r(a,u),setTimeout(()=>{c(!1),s.ue.success("Changes applied. Visual is now local to this dashboard"),l(!1)},300)};return e.jsxs(s.Button,{onClick:i,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Applying"]}),!o&&e.jsxs(e.Fragment,{children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Apply Locally"]})]})}function St({className:t}){const{setTempQueryData:n,setSqlGen:a}=s.useEditorActions(),r=s.useQueryClient(),l=s.useEditorStore(u=>u.tempQueryData),o=s.useEditorStore(u=>u.onClose),c=s.useEditorStore(u=>u.card),{queryKey:i}=s.useDashboardCardQuery(c);function d(){if(l){const{queryKey:u,queryData:m}=l;u&&m&&r.setQueryData(u,m)}a({}),o==null||o()}return e.jsxs(s.Button,{onClick:d,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function xs(){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 $n(){const[t,n]=A.useState(!1),[a,r]=A.useState(!1),[l,o]=A.useState(null),c=s.useEditorStore(D=>D.frame),i=s.useEditorStore(D=>D.card),d=s.useSelectedVisual(),u=s.useDashboardStore(D=>D.selectedSheetId),m=s.useDashboardStore(D=>D.actions.setIsDashboardPanelOpen),{getUpdatedFrame:h}=Ve(),{selectVisual:x}=s.useManagementActions(),{addFrame:g,setSelectedFrameId:b,setIsVisualEditing:p}=s.useDashboardActions(),j=!!(c!=null&&c.visualId),f=(d==null?void 0:d.title)||(i==null?void 0:i.title)||"Untitled Visual",y=s.useCreateVisualWithFrame(D=>{if(D!=null&&D.id){if(x(D),a&&l&&u){const C={...l,id:s.v4(),visualId:D.id};g(u,C,"end"),b(C.id),r(!1),o(null),p(!1)}m(!0),n(!1)}});return{saveAsDialogOpen:t,setSaveAsDialogOpen:n,handleSaveAs:async D=>{if(!u){s.ue.error("No sheet selected");return}const C=h();if(D.saveToLibrary){r(D.saveToCurrentDashboard),o(C);const S={title:D.name,description:D.description,frameObject:C,isPrivate:!1};y.mutate(S)}else if(D.saveToCurrentDashboard){const S={...C,id:s.v4(),visualId:void 0,cards:C.cards.map(v=>({...v,title:v.id===i.id?D.name:v.title}))};g(u,S,"end"),b(S.id),s.ue.success("Visual saved to dashboard"),n(!1),p(!1)}},isLibraryVisual:j,currentVisualName:f,isSaving:y.isPending}}function wt({className:t}){const n=s.useEditorStore(y=>y.frame),a=s.useEditorStore(y=>y.card),r=s.useManagementStore(y=>y.selectedVisual),l=s.useDashboardStore(y=>y.selectedFrameId),o=s.useDashboardStore(y=>y.selectedSheetId),{setIsVisualEditing:c}=s.useDashboardActions(),i=!!(n!=null&&n.visualId||r!=null&&r.id),d=!!(n!=null&&n.visualId&&l),u=i&&!d,{saveAsDialogOpen:m,setSaveAsDialogOpen:h,handleSaveAs:x,isLibraryVisual:g,currentVisualName:b,isSaving:p}=$n(),{handleAddLibraryVisual:j}=Ve(),f=async()=>{if(!o){s.ue.error("No dashboard sheet selected");return}if(!r){s.ue.error("No visual selected");return}const y=await j(r);y.success?(s.ue.success("Visual added to dashboard"),c(!1)):s.ue.error(y.error||"Failed to add visual to dashboard")};return e.jsxs(e.Fragment,{children:[e.jsx(St,{className:t}),!i&&e.jsx(Ct,{className:t,variant:"default"}),i&&e.jsxs(e.Fragment,{children:[d&&e.jsx(Yn,{className:t}),u&&o&&a&&(a.sql||s.hasValidCardConfig(a.config))&&e.jsxs(s.Button,{onClick:f,className:s.cn(t),size:"sm",variant:"outline",children:[e.jsx(fa,{className:"mr-2 size-4 font-bold"}),"Add to Dashboard"]}),u&&e.jsx(Un,{className:t,variant:"outline"}),d&&e.jsx(Gn,{className:t}),e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:s.cn(t,"w-8 p-0"),children:e.jsx(s.EllipsisVertical,{className:"h-4 w-4"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),h(!0)},children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]})]}),!i&&e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:s.cn(t,"w-8 p-0"),children:e.jsx(s.EllipsisVertical,{className:"h-4 w-4"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:()=>h(!0),children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]}),e.jsx(_n,{open:m,onOpenChange:y=>{p||h(y)},isLibraryVisual:g,currentVisualName:b,isSaving:p,onConfirm:x})]})}function Dt({className:t,labelClassName:n,switchClassName:a}){const r=s.useEditorStore(d=>d.isDevMode),l=s.useDashboardStore(d=>d.isVisualEditing),{setIsDevMode:o}=s.useEditorActions(),{config:c}=A.useContext(s.SemaphorContext).tokenProps,i=(c==null?void 0:c.showAdvancedMode)!==!1;return!l||!i?null:e.jsxs("div",{className:s.cn("flex items-center space-x-2",t),children:[e.jsx(s.Switch,{className:s.cn("",a),checked:r,onCheckedChange:()=>o(!r),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:s.cn("text-sm font-medium",n),children:"Advanced Mode"})]})}function qn(){var ie,de,xe;const{authToken:t,tokenProps:n,id:a}=s.useSemaphorContext(),{isLocalDev:r,isConsoleMode:l}=s.useDashboardPreferences(),{permissions:o}=s.useRoleAwareDisplayPreferences(),c=s.useHasDashboardId();s.useDashboardStore(H=>H.theme);const i=s.useDashboardStore(H=>H.lenses),d=s.useDashboardStore(H=>H.selectedLensId),u=i==null?void 0:i.find(H=>H.id===d),m=s.useDashboardStore(H=>H.dashboard);s.useDashboardStore(H=>H.selectedSheetId);const h=s.useDashboardStore(H=>H.isDashboardEditing),[x,g]=A.useState(!1),[b,p]=A.useState(!1),[j,f]=A.useState(!1),y=s.useDashboardStore(H=>H.isDashboardPanelOpen),E=s.useDashboardStore(H=>H.actions.setIsDashboardPanelOpen),D=s.useDashboardStore(H=>H.filterValues),C=s.useDashboardStore(H=>H.isVisualEditing),S=s.useEditorStore(H=>H.card),v=s.useManagementStore(H=>H.selectedDashboard),k=s.useManagementStore(H=>H.initialDashboard),N=s.useManagementStore(H=>H.selectedVisual);s.useDashboardStore(H=>H.selectedFrameId),s.useEditorStore(H=>H.frame);const F=v?(de=v==null?void 0:v.permissions)==null?void 0:de.canEdit:(ie=k==null?void 0:k.permissions)==null?void 0:ie.canEdit,T=s.useDashboardStore(H=>H.showFilters),B=s.useDashboardStore(H=>H.showDashboardJSON),I=s.useDashboardStore(H=>H.onSaveFunction),w=s.useDashboardStore(H=>H.actions.setShowFilters),{setIsDashboardEditing:M,setShowDashboardJSON:L}=s.useDashboardStore(H=>H.actions),{setInitialDashboard:O,clearSelectedDashboard:R}=s.useManagementStore(H=>H.actions),{resources:z}=s.useResourceManagement(s.ResourceType.DASHBOARD),{currentUser:G}=s.useCurrentUserInfo(),Q=s.canUserManageGroups(G),_=v||k,W=_?{id:_.id,title:(m==null?void 0:m.title)||_.title||"Dashboard"}:null,{handleAddNewFrame:$}=s.useAddNewFrame(),[X,Y]=A.useState(!1),K=s.useUpdateResource(s.ResourceType.DASHBOARD);A.useEffect(()=>{if(z&&z.length>0){const H=m==null?void 0:m.id;if(H){const P=z.find(J=>J.id===H);P&&O(P)}}},[z,m==null?void 0:m.id,O]);const U=n.orgUserId||n.tenantId,Z=h&&!C&&U&&F,ne=()=>{M(!0)};async function he(){const H=is(m);Y(!0);const P={template:H};K.mutate({resourceId:H.id,data:P},{onSuccess:()=>{Y(!1),s.ue.success("Dashboard saved!")},onError:()=>{Y(!1),s.ue.error("Failed to save dashboard")}})}async function ge(){if(g(!0),!d||!u)return;const H=is(m),P=JSON.stringify(H),J={...u,template:P,filterValues:D};await Ds(n.apiServiceUrl,J,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),I==null||I(H),g(!1)}const V=(u==null?void 0:u.name)||m.title,te=z&&z.length>0&&(n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail),re=v&&!(n!=null&&n.dashboard_id)&&!a;return e.jsxs("div",{className:"flex h-11 items-center justify-between gap-2 border-b px-4 py-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[te&&e.jsxs(e.Fragment,{children:[re&&!C&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Back to Dashboard Hub",onClick:()=>R(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})}),e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:c?"Manage Dashboards":"Select a dashboard to continue",onClick:()=>{c&&E(!y)},className:"h-7 p-2",buttonProps:{disabled:!c},children:e.jsx(Ra,{className:"h-4 w-4"})})]}),!C&&c&&e.jsx(s.Label,{children:V}),C&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm font-medium",children:(N==null?void 0:N.title)||(S==null?void 0:S.title)||"Untitled Visual"}),e.jsx(yt,{})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[C&&e.jsxs(e.Fragment,{children:[e.jsx(Dt,{className:"mr-2"}),e.jsx(wt,{className:"h-7"})]}),r&&!C&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:()=>s.invalidateToken(n.apiServiceUrl),className:"h-7 p-2",children:e.jsx(Ga,{className:"h-4 w-4"})}),!C&&c&&e.jsx(tn,{}),!C&&c&&e.jsx(dt,{}),!C&&c&&Q&&e.jsx(s.IconButton,{tooltip:"Manage Groups",onClick:()=>f(!0),className:"h-7 p-2",children:e.jsx(s.Users,{className:"h-4 w-4"})}),!C&&c&&((xe=_==null?void 0:_.permissions)==null?void 0:xe.canShare)&&e.jsx(s.IconButton,{tooltip:"Share Dashboard",onClick:()=>p(!0),className:"h-7 p-2",children:e.jsx(s.UserPlus,{className:"h-4 w-4"})}),h&&!C&&U&&r&&c&&e.jsx(en,{}),!C&&U&&r&&c&&e.jsx(sn,{}),h&&!C&&U&&u&&r&&c&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:x,onClick:ge,size:"sm",children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),h&&!C&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!h,onClick:()=>$(),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Visual"]}),!C&&!h&&o.canEdit&&c&&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"]}),h&&!C&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{M(!1),L(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),Z&&c&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"outline",disabled:X,onClick:he,size:"sm",children:[X?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(qe,{className:"mr-2 h-4 w-4"}),X?"Saving...":"Save"]}),!T&&!C&&h&&o.canUseFilters&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>w(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!C&&h&&r&&c&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>L(!B),size:"sm",variant:"ghost",children:e.jsx($e,{className:"h-4 w-4"})})}),!C&&r&&e.jsx(Qa,{}),b&&W&&e.jsx(hs,{resource:W,resourceType:s.ResourceType.DASHBOARD,onClose:()=>p(!1)}),e.jsx(On,{open:j,onOpenChange:f})]})]})}function Hn({name:t,items:n,value:a,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:d,showNone:u=!1}){const m=Re.useRef(null),[h,x]=Re.useState(!1),[g,b]=Re.useState("100%"),p=u?[...n||[],{id:"none",name:"None"}]:n;Re.useLayoutEffect(()=>{m.current&&b(m.current.offsetWidth)},[]);function j(){var y;return l?"Loading...":o?"Error":a?(y=n==null?void 0:n.find(E=>E.id===a))==null?void 0:y.name:`Select ${t}`}function f(y,E){r(E),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(rt,{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(y=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:y.name,onSelect:E=>f(E,y.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",a===y.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:y.name,children:y.name})]})},y.id))})]})]})})]})}function Ge({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(Va,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Ba,{className:"size-4"});if(t==="Table")return e.jsx(s.Table2,{className:"size-4"});if(t==="Model")return e.jsx(xa,{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(rt,{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(Hn,{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 Wn({column:t}){const[n,a]=A.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 D;const f=s.createSqlGenConfig(p,i,j),y=(D=d==null?void 0:d.find(C=>C.id===c))==null?void 0:D.name;m(f);const E=s.getSql(f,s.fmt(l||""),s.fmt(r),y||"",u,o||"");E&&(h(E),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 Kn({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(Se,{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(Ie,{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(Pe,{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($e,{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(Xe,{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(ss,{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(Se,{className:"h-3 w-3"})})}function gs({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(Kn,{dataType:t.data_type}),e.jsx("span",{children:t.column_name})]})}function Qn({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 Jn({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(gs,{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(gs,{column:n})}),e.jsx(Qn,{id:n.column_name,type:"column",children:e.jsx(gs,{column:n})})]})}const js={id:"__placeholder__",role:"groupby",type:"string"},bs={id:"__placeholder__",role:"groupby",type:"string"},vs={id:"__placeholder__",role:"metric",type:"number"},ys={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},Tt={id:"__placeholder__"},Oe="droppable-group-by",Fe="droppable-metrics",Be="droppable-pivot-by",ds="sortable-group-by",Ts="sortable-metrics",us="sortable-pivot-by",ks="droppable-filters",Es="sortable-filters",Ms="sortable-order-by";function Xn(){const t=s.useDndStore(w=>w.insertIndex),n=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.groupByColumns)||[]}),a=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.metricColumns)||[]}),r=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.filterColumns)||[]}),l=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.orderBy)||[]}),o=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.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:y}=s.useEditorAside(),E=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),D=w=>{var O;const{active:M,over:L}=w;if(((O=M.data.current)==null?void 0:O.type)==="column"&&L){const R=L.id,z=f.find(W=>W.column_name===M.id);if(!z)return;const G=s.isNumberDataType(z.data_type),Q=s.isTextDataType(z.data_type),_=s.isDateDataType(z.data_type);if(Q||_){if(n.some($=>$.id===R)){const $=n.findIndex(Y=>Y.id===R);c($);const X=n.filter(Y=>Y.id!==js.id);X.splice($,0,js),d(X)}else if(L.id===Oe){c(n.length);const $=[...n,js];d($),u(a),m(r)}}if(Q||_){if(o.some($=>$.id===R)){const $=o.findIndex(Y=>Y.id===R);c($);const X=o.filter(Y=>Y.id!==bs.id);X.splice($,0,bs),h(X)}else if(L.id===Be){c(o.length);const $=[...o,bs];h($),d(n),u(a),m(r)}}if(G||Q){if(a.some($=>$.id===R)){console.log("isOverMetricSortable",R);const $=a.findIndex(Y=>Y.id===R);c($);const X=a.filter(Y=>Y.id!==vs.id);X.splice($,0,vs),u(X)}else if(L.id===Fe){c(a.length);const $=[...a,vs];u($),m(r),d(n),h(o)}}if(S(z)){if(r.some($=>$.id===R)){const $=r.findIndex(Y=>Y.id===R);c($);const X=r.filter(Y=>Y.id!==ys.id);X.splice($,0,ys),m(X)}else if(L.id===ks){c(r.length);const $=[...r,ys];m($),u(a),d(n),h(o)}}}else d(n),u(a),m(r),h(o)};function C(w){i(w.active.id),c(null),d(n),u(a),m(r),h(o)}function S(w){return!r.some(M=>M.name===w.column_name)}function v(w,M="SUM"){const{column_name:L,data_type:O}=w,R=[...a],z=t!==null?t:a.length,G={...w,id:De(L),name:L,label:es(L,M),type:O,role:"metric",aggregate:M};R.splice(z,0,G),g(R)}function k(w){const M=s.isTextDataType(w.data_type);s.isDateDataType(w.data_type);const L=[...o],O=t!==null?t:o.length;let R;M?R={...w,id:De(w.column_name),name:w.column_name,type:w.data_type,role:"groupby"}:R={...w,id:De(w.column_name),name:w.column_name,type:w.data_type,role:"groupby",label:We(w.column_name,"month"),granularity:"month"},L.splice(O,0,R),j(L)}function N(w){const M=s.isTextDataType(w.data_type);s.isDateDataType(w.data_type);const L=[...n],O=t!==null?t:n.length;let R;M?R={...w,id:De(w.column_name),name:w.column_name,type:w.data_type,role:"groupby"}:R={...w,id:De(w.column_name),name:w.column_name,type:w.data_type,role:"groupby",label:We(w.column_name,"month"),granularity:"month"},L.splice(O,0,R),x(L)}function F(w){const M=[...r],L=t!==null?t:r.length,O={...w,id:De(w.column_name),name:w.column_name,type:w.data_type,sql:s.getDefaultFilterSql(w.data_type,y,s.fmt(w.column_name)),role:"filter"};M.splice(L,0,O),b(M)}function T(w){var R,z,G,Q,_,W,$,X;const{active:M,over:L}=w,O=M.data.current;if((O==null?void 0:O.type)==="column"&&L){const Y=f.find(ne=>ne.column_name===M.id);if(!Y)return;const K=s.isNumberDataType(Y.data_type),U=s.isTextDataType(Y.data_type),Z=s.isDateDataType(Y.data_type);(U||Z)&&(L.id===Oe||((R=L.data.current)==null?void 0:R.type)===ds)&&N(Y),(U||Z)&&(L.id===Be||((z=L.data.current)==null?void 0:z.type)===us)?k(Y):(K||U)&&(L.id===Fe||((G=L.data.current)==null?void 0:G.type)===Ts)?(K&&v(Y),U&&v(Y,"COUNT")):S(Y)&&(L.id===ks||((Q=L.data.current)==null?void 0:Q.type)===Es)&&F(Y)}if(L&&((_=L.data.current)==null?void 0:_.type)===ds&&n.some(Y=>Y.id===M.id)){const Y=n.findIndex(U=>U.id===M.id),K=n.findIndex(U=>U.id===L.id);if(Y!==-1&&K!==-1&&Y!==K){const U=[...n],[Z]=U.splice(Y,1);U.splice(K,0,Z),x(U)}}if(L&&((W=L.data.current)==null?void 0:W.type)===us&&o.some(Y=>Y.id===M.id)){const Y=o.findIndex(U=>U.id===M.id),K=o.findIndex(U=>U.id===L.id);if(Y!==-1&&K!==-1&&Y!==K){const U=[...o],[Z]=U.splice(Y,1);U.splice(K,0,Z),j(U)}}if(L&&(($=L.data.current)==null?void 0:$.type)===Ts&&a.some(Y=>Y.id===M.id)){const Y=a.findIndex(U=>U.id===M.id),K=a.findIndex(U=>U.id===L.id);if(Y!==-1&&K!==-1&&Y!==K){const U=[...a],[Z]=U.splice(Y,1);U.splice(K,0,Z),g(U)}}if(L&&((X=L.data.current)==null?void 0:X.type)===Es&&r.some(Y=>Y.id===M.id)){const Y=r.findIndex(U=>U.id===M.id),K=r.findIndex(U=>U.id===L.id);if(Y!==-1&&K!==-1&&Y!==K){const U=[...r],[Z]=U.splice(Y,1);U.splice(K,0,Z),b(U)}}B(w),i(null),c(null),d(n),u(a),m(r),h(o)}function B(w){const{active:M,over:L}=w,O=M.data.current;if((O==null?void 0:O.type)===Ms&&L){const R=l.findIndex(G=>Je(G.columnId)===M.id),z=l.findIndex(G=>Je(G.columnId)===L.id);if(R!==-1&&z!==-1&&R!==z){const G=[...l],[Q]=G.splice(R,1);G.splice(z,0,Q),p(G)}}}function I(){i(null),c(null),d(n),u(a),m(r)}return{handleDragOver:D,handleDragEnd:T,handleDragStart:C,handleDragCancel:I,sensors:E}}function De(t){return`${t}-${s.v4()}`}function es(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 Je(t){return`${Ms}-${t}`}function We(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"day":return`Date of ${a}`;case"week":return`Week of ${a}`;case"month":return`Month of ${a}`;case"year":return`Year of ${a}`;default:return a}}function 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(Se,{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(Ie,{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(Pe,{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($e,{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(Xe,{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(ss,{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(Se,{className:"h-3 w-3"})})}function er({schemaName:t,tableName:n,columns:a,status:r}){const[l,o]=A.useState(""),[c,i]=A.useState("all"),d=s.useEditorStore(R=>R.sqlGen),u=s.useEditorStore(R=>R.isDevMode);s.useEditorStore(R=>R.selectedConnectionId);const m=s.useEditorStore(R=>{var z,G;return(G=(z=R.card)==null?void 0:z.queryConfig)==null?void 0:G.metricColumns});s.useEditorStore(R=>{var z,G;return(G=(z=R.card)==null?void 0:z.queryConfig)==null?void 0:G.groupByColumns});const h=s.useEditorStore(R=>R.selectedDatabaseName);s.useEditorStore(R=>R.selectedSchemaName),s.useEditorStore(R=>R.selectedTableName);const x=s.useEditorStore(R=>R.selectedDatamodelId);s.useDashboardStore(R=>R.dashboard.aiScopeTables);const{addToAIScope:g,removeFromAIScope:b}=s.useDashboardActions(),{addColumnToMetricColumns:p,addColumnToGroupBy:j,setCardSql:f,setRunSql:y,setSqlGen:E,setIsShowingVisual:D}=s.useEditorActions(),{connectionType:C,modelItems:S,selectedDatamodelName:v}=s.useEditorAside();function k(R){var z;if(u){const G=s.createSqlGenConfig(R,d);E(G);const Q=(z=S==null?void 0:S.find(W=>W.id===x))==null?void 0:z.name,_=s.getSql(G,s.fmt(t),s.fmt(n),Q||"",C,h||"");_&&(f(_),y(!0))}if(!u){if(s.isTextDataType(R.data_type))if(m&&m.length>0){const G={...R,role:"groupby",id:De(R.column_name),name:R.column_name,type:R.data_type};j(G)}else{const G={...R,role:"metric",id:De(R.column_name),name:R.column_name,label:es(R.column_name,"COUNT"),type:R.data_type,aggregate:"COUNT"};p(G)}if(s.isDateDataType(R.data_type)){const G={...R,role:"groupby",id:De(R.column_name),name:R.column_name,type:R.data_type,label:We(R.column_name,"month"),granularity:"month"};j(G)}if(s.isNumberDataType(R.data_type)){const G={...R,role:"metric",id:De(R.column_name),name:R.column_name,label:es(R.column_name,"SUM"),type:R.data_type,aggregate:"SUM"};p(G)}}}function N(){const R=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:C,databaseName:h||""});D(!1);const z=C==="MSSQL"?`SELECT top 10 * FROM ${R}`:`SELECT * FROM ${R} LIMIT 10`;f(z),y(!0)}function F(){const R=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:C,databaseName:h||""});f(`SELECT COUNT(*) as count FROM ${R}`),y(!0)}const T=(a==null?void 0:a.filter(R=>R.column_name.toLowerCase().includes(l.toLowerCase())))||[],B=R=>s.isNumberDataType(R.data_type)?"number":"text",I=c==="all"?T:T.filter(R=>B(R)===c),w=T.filter(R=>B(R)==="text").length,M=T.filter(R=>B(R)==="number").length;function L(R){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(R),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zn,{dataType:R.data_type}),e.jsx("span",{children:R.column_name})]}),e.jsx("div",{onClick:z=>z.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(R.data_type)&&e.jsx(Wn,{column:R})})]}):e.jsx(Jn,{onClick:k,column:R})}function O(){return e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:r!=="Success",onClick:N,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(La,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:F,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(lt,{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((R,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:O()}),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:R=>o(R.target.value)})]}),T.length>0&&e.jsx(s.Tabs,{defaultValue:"all",value:c,onValueChange:R=>i(R),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:T.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:w})]}),e.jsxs(s.TabsTrigger,{value:"number",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:M})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-4 pt-3",children:[I.length===0&&l&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',l,'"']}),I.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:I==null?void 0:I.map(R=>e.jsx("div",{children:L(R)},R.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function kt({ColumnsComponent:t,type:n}){var H;const[a,r]=A.useState(!1),{isConsoleMode:l}=s.useDashboardPreferences(),o=s.useEditorStore(P=>P.card),c=s.useEditorStore(P=>P.selectedConnectionId),i=s.useDashboardStore(P=>P.showFilters),d=s.useEditorStore(P=>P.selectedDatamodelId),u=s.useEditorStore(P=>P.selectedDatabaseName),m=s.useEditorStore(P=>P.selectedSchemaName),h=s.useEditorStore(P=>P.selectedTableName);s.useEditorStore(P=>P.isDevMode);const{setSelectedTableName:x,setIsDevMode:g,setCardSql:b}=s.useEditorActions(),{connectionItems:p,modelItems:j,schemaItems:f,databaseItems:y,tableItems:E,columns:D,isConnectionsLoading:C,isModelsLoading:S,isConnectionsError:v,isModelsError:k,isDatabasesLoadingOrFetching:N,isDatabaseError:F,isSchemaLoadingOrFetching:T,isSchemaError:B,isColumnsError:I,isColumnsLoadingOrFetching:w,isTableLoadingOrFetching:M,isTableError:L,connectionType:O,isNonDbConnection:R,refetchDatabases:z,refetchModels:G,refetchSchemas:Q,refetchTables:_,refetchColumns:W,refetchConnections:$,handleConnectionChange:X,handleDatabaseChange:Y,handleSchemaChange:K,handleDatamodelChange:U,handleTableChange:Z,tableName:ne,schemaName:he}=s.useEditorAside(),{data:ge,refetch:V}=s.useDashboardCardQuery(o);function se(){return t?t(he,ne,D):e.jsx(er,{schemaName:he,tableName:ne,columns:D,status:w?"Loading...":I?"Error":"Success"})}function te(){if(!c||O==="S3"||O==="API")return null;if(!d||d==="none")return e.jsx(Ge,{refetch:z,showNone:!0,onChange:Y,isError:F,isLoading:N,items:y,value:u||"",title:"Database",type:"combobox"})}function re(){if(c&&!R&&(!u||u==="none")&&(!d||d==="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 ie(){if(!c||O==="S3"||O==="API")return null;if(!u||u==="none")return e.jsx(Ge,{refetch:G,showNone:!0,onChange:U,isError:k,isLoading:S,items:j,value:d||"",title:"Model",type:"combobox"})}function de(){return!c||O==="S3"||O==="API"||!u||u==="none"?null:e.jsx(Ge,{refetch:Q,onChange:K,isError:B,isLoading:T,items:f,value:m||"",title:"Schema",type:"combobox"})}function xe(){function P(){let J=!1;return O==="API"?(J=!1,J):((O==="S3"||c&&u&&u!=="none"&&m)&&(J=!0),J)}return P()?e.jsx(Ge,{refetch:_,onChange:Z,isError:L,items:E,isLoading:M,value:h||"",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]":!i}),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(Ge,{refetch:$,items:p,title:"Connection",value:c||"",onChange:X,isLoading:C,isError:v,type:"combobox",connectionTooltip:((H=p==null?void 0:p.find(P=>P.id===c))==null?void 0:H.type)||""}),te(),re(),ie(),de(),xe()]})]}),se(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:n==="main"&&l&&e.jsx(e.Fragment,{})})]})}function Et({error:t,errorSql:n,onSendFeedback:a,className:r,showFeedbackButton:l=!0}){const[o,c]=A.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(s.MessageSquareWarning,{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 It({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(Et,{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(Na,{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(ka,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function At({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(ga,{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(It,{errorSql:a,sql:t,error:n,onDebugWithAssistant:r})})]})}function sr(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 Mt(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=A.useRef(),h=A.useRef({}),x=r.cards.find(p=>p.id===o),g=A.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]);A.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]),A.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]),A.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(),y=g();h.current[l.id]=f||(j==null?void 0:j.editor.createModel(y,t))||p.getModel()}p.setModel(h.current[l.id])}return{handleEditorDidMount:b}}function tr(){const t=s.useEditorStore(c=>c.card.sql),n=s.useEditorStore(c=>c.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=Mt("sql");function o(c){a(c),s.isObjectEmpty(n)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:o,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function ar(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=Mt("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 nr({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 rr(){const t=s.useQueryClient(),{isConsoleMode:n}=s.useDashboardPreferences(),[a,r]=A.useState(!1),[l,o]=A.useState(!1);s.useEditorStore(_=>_.frame);const c=s.useEditorStore(_=>_.card);s.useEditorStore(_=>_.isShowingVisual),s.useEditorStore(_=>_.selectedConnectionId),s.useEditorStore(_=>_.tempQueryData),s.useEditorStore(_=>_.selectedDatabaseName),s.useEditorStore(_=>_.selectedDatamodelId),s.useEditorStore(_=>_.selectedSchemaName);const i=s.useEditorStore(_=>_.showAIDialog);s.useEditorStore(_=>_.selectedTableName);const d=s.useEditorStore(_=>{var W;return(W=_==null?void 0:_.card)==null?void 0:W.sql}),u=s.useEditorStore(_=>{var W;return(W=_==null?void 0:_.card)==null?void 0:W.python}),{sheetFilterValues:m}=s.useSheetFilterValues(),{setCardCustomCfg:h,setQueryResultColumns:x,setCardSql:g,setTempQueryData:b,setPythonStdOut:p,setCardPreferences:j,setCardType:f,setCardPython:y,runAssistant:E,setShowAIDialog:D}=s.useEditorActions();s.useEditorStore(_=>_.onSave),s.useEditorStore(_=>_.onClose),s.useEditorStore(_=>_.actions.setSqlGen);const C=s.useEditorStore(_=>_.runSql),S=s.useEditorStore(_=>_.actions.setRunSql),v=s.useEditorStore(_=>_.actions.setIsSqlRunning),{data:k,isLoading:N,isFetching:F,isSuccess:T,isError:B,error:I,errorSql:w,queryKey:M,refetch:L,errorMessage:O}=s.useDashboardCardQuery(c);A.useEffect(()=>{if(k&&(k.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),p((k==null?void 0:k.output)||""),k.records.length>0)){const{dimensionKeys:_}=s.getKeys(k.records);x(_)}},[k,x,p]),A.useEffect(()=>{(N||F)&&v(!0),(B||T)&&v(!1),B&&(x([]),p(""))},[N,F,k,p,B,T,v,x,I]),A.useEffect(()=>{C&&(t.getQueryData(M)||L(),S(!1))},[C,L,S,M,t]);async function R(){const _=`Can you help me debug this query?
|
|
311
|
+
*/const Ka=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 Qa(){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(qa,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(Fa,{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 is(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=>ct(c))}})}})}}function ct(t){return{...t,customCfg:Ja(t.customCfg),data:[]}}function Ja(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 Xa(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 Ds(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 Za(t,n,a){if(!a)return null;const r=`${t}/v1/lens`;return await s.postRequest(r,a,{operation:"delete",lensId:n})}function en(){const[t,n]=A.useState(""),[a,r]=A.useState(!1),l=s.useDashboardStore(j=>j.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=A.useState(!1),[u,m]=A.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=is(h),f=await Xa(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 sn(){const[t,n]=A.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 Za(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 Ds(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 Ds(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(Ta,{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 tn({iconClassName:t}){const[n,a]=A.useState(!1),[r,l]=A.useState(""),[o,c]=A.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 dt({triggerButtonClassName:t}){const[n,a]=A.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 cs({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 ze({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 ut({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(ze,{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 mt({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 ht({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 xt(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,l=A.useRef(null);return A.useEffect(()=>{const o=c=>{const i=c.target;l.current&&l.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,a,r]),l}function we(t,n){var a;return((a=n.find(r=>r.value===t))==null?void 0:a.label)||t}function an(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function pt(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function nn(t,n,a){const r=pt(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 rn({user:t}){return pt(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 ln({user:t,userShare:n,usersToUpdate:a,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(n!=null&&n.role))return null;const c=an((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(ze,{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:we(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function on({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(Ye,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function cn({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 dn({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,y;const b=((f=n.find(E=>E.id===x.orgUserId))==null?void 0:f.name)||"Unknown User",p=((y=n.find(E=>E.id===x.orgUserId))==null?void 0:y.type)||"",j=we(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,y;const b=((f=n.find(E=>E.id===x.tenantUserId))==null?void 0:f.name)||"Unknown User",p=((y=n.find(E=>E.id===x.tenantUserId))==null?void 0:y.type)||"",j=we(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=we(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=we(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=we(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=we(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=we(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=we(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=we(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 un({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 mn({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(rn,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!a?e.jsx(ze,{currentRole:n==null?void 0:n.role,onRoleChange:b=>x(t.id,n.role,b),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(ln,{user:t,userShare:n,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:x}),o&&!l&&e.jsx("div",{onClick:b=>b.stopPropagation(),children:e.jsx(ze,{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(on,{hasAccess:r,isUserRemoving:a,isSelected:o,hasAccessFromAPI:l}),e.jsx(cn,{isUserRemoving:a,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function ft({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||(C=>{const S=m.some(k=>k.id===C),v=h.includes(C);S?b.removeSelectedUser(C):v?b.removeUserFromRemove(C):b.addSelectedUser({id:C,role:"VIEWER"})}),j=i||b.updateSelectedUserRole,f=d||b.addUserToRemove,y=u||((C,S,v)=>{b.addUserToUpdate({id:C,currentRole:S,newRole:v})}),E=l,D=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 (",(E??[]).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(dn,{existingShares:t,allUsers:l,getRoleOptions:r,currentUser:o})})]})})]}),(E==null?void 0:E.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===E.length?b.setSelectedUsers([]):b.setSelectedUsers(E.map(C=>({id:C.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:m.length===E.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(un,{isInitialLoading:n,isSearching:a,searchQuery:g,availableUsers:E||[]}),!n&&!a&&(E==null?void 0:E.length)>0&&E.map(C=>{const S=t?nn(C,t,o):void 0,v=D.includes(C.id),k=!!S,N=k&&!v,F=m.some(I=>I.id===C.id),T=m.find(I=>I.id===C.id),B=r(C.type);return e.jsx(mn,{user:C,userShare:S,isUserRemoving:v,hasAccess:N,hasAccessFromAPI:k,isSelected:F,selectedUser:T,roleOptions:B,currentUser:o,usersToUpdate:x,handleUserToggle:p,handleRemoveAccess:f,handleUpdateAccess:y,handleUserRoleChange:j},C.id)})]})]})}function Is({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 Ce=()=>[{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 hn({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=Ce().filter(y=>y.value==="VIEWER"||y.value==="EDITOR"||y.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=y=>{switch(y){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(Ua,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},f=y=>{r(m,y)};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(y=>e.jsxs(s.Button,{variant:h===y.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>f(y.value),disabled:a||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[j(y.value),e.jsx("span",{className:"font-medium",children:y.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:y.description})]},y.value))})]})})]})})}function gt({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(hn,{currentUser:t,currentShare:h,isSharing:a,isUpdating:r,isRemoving:l,onUpdateAccess:g,onRemoveAccess:b,allUsersToUpdate:x,allUsersToRemove:d})}function He(t){const{debouncedSearchQuery:n,resourceId:a,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:o}=t,c=A.useMemo(()=>({search:n,active:!0,...l?{type:l}:{},...l==="tenant"&&o?{tenantId:o}:{}}),[n,l,o]),{users:i,isLoading: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 xn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var _,W;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(),[y,E]=A.useState("specific_users"),D=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},C=()=>{if(i==="tenant"&&d)return d},{allUsers:S,existingShares:v,isLoadingUsers:k}=He({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:D(),tenantId:C()});A.useEffect(()=>{f.setCurrentContext("org-tab"),f.setCurrentMode(y==="all_users"?"allOrgUsers":"specificOrgUsers")},[f,y]);const N=$=>{var Y,K;const X=$;if(E(X),r==null||r(X),f.setCurrentContext("org-tab"),X==="specific_users")f.setCurrentMode("specificOrgUsers");else if(X==="all_users"){f.setCurrentMode("allOrgUsers");const U=(K=(Y=v==null?void 0:v.shares)==null?void 0:Y.orgUsersOnly)==null?void 0:K[0];U&&U.role!==void 0&&f.setOrgWideRole(U.role)}},F=S.filter($=>$.name.toLowerCase().includes(u.toLowerCase())||$.email.toLowerCase().includes(u.toLowerCase())),T=S.filter($=>x.some(X=>X.id===$.id)),B=$=>{var U,Z;const X=x.some(ne=>ne.id===$),Y=g.includes($),K=(Z=(U=v==null?void 0:v.shares)==null?void 0:U.specificOrgUsers)==null?void 0:Z.some(ne=>ne.orgUserId===$);X?f.removeSelectedUser($):Y?f.removeUserFromRemove($):K||f.addSelectedUser({id:$,role:"VIEWER"})},I=($,X)=>{f.updateSelectedUserRole($,X)},w=$=>{f.addUserToRemove($),f.removeSelectedUser($)},M=$=>{f.removeUserFromRemove($)},L=$=>{f.removeUserFromUpdate($)},O=($,X)=>{f.setOrgWideRole(X)},R=()=>{f.setOrgWideRole((z==null?void 0:z.role)||"NONE")},z=(W=(_=v==null?void 0:v.shares)==null?void 0:_.orgUsersOnly)==null?void 0:W[0];A.useEffect(()=>{y==="all_users"&&z&&z.role!==void 0&&f.setOrgWideRole(z.role)},[y,z,f]);const G=k,Q=!1;return a?e.jsxs(e.Fragment,{children:[e.jsx(Is,{shareType:y,onShareTypeChange:N,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??"")}]}),y==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(cs,{value:u,onChange:m}),e.jsx(ut,{selectedUsers:x,selectedUserObjects:T,onRemove:B,onRoleChange:I,getRoleOptions:Ce}),e.jsx(mt,{usersToRemove:g,allUsers:F,onRemove:M}),e.jsx(ht,{usersToUpdate:b,allUsers:F,onRemove:L,getRoleOptions:Ce}),e.jsx(ft,{existingShares:v,isInitialLoading:G,isSearching:Q,resource:t,onShare:()=>{},getRoleOptions:Ce,allUsers:F,currentUser:a,handleUserToggle:B,handleUserRoleChange:I,handleRemoveAccess:w,handleUpdateAccess:($,X,Y)=>{f.addUserToUpdate({id:$,currentRole:X,newRole:Y})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(gt,{currentUser:a,currentShare:z,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:O,onRemoveAccess:R,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 pn(t){switch(t){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function fn(t){switch(t){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function jt({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),y=h.includes(p.id),E=x.find(v=>v.id===p.id),D=!!j&&!y;let S=(j==null?void 0:j.role)||"VIEWER";if(f){const v=m.find(k=>k.id===p.id);S=(v==null?void 0:v.role)||"VIEWER"}else E&&(S=E.newRole);return e.jsxs("div",{className:s.cn("flex items-center justify-between rounded-lg p-2 transition-colors",D&&!y?"border border-green-200 bg-green-50":y?"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:D?!y:f,disabled:!1,onCheckedChange:()=>{D?y?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",fn(p.type)),children:pn(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:[D&&!y?e.jsx(ze,{currentRole:S,onRoleChange:v=>{j&&v!==j.role&&(u==null||u(p.id,j.role,v))},roleOptions:b,disabled:!1,allowDropdown:!0,className:E?"border-orange-300 bg-orange-100":""}):f&&!D&&e.jsx(ze,{currentRole:S,onRoleChange:v=>i==null?void 0:i(p.id,v),roleOptions:b,disabled:!1}),D&&!y&&!E&&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"})}),y&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromRemove(p.id),children:"Undo"}),E&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromUpdate(p.id),children:"Cancel"})]})]},p.id)})})]})}function bt({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(ze,{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 qs({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var H;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(),y=s.useShareAllTenantsRole(),E=s.useShareSelectedTenant(),D=s.useShareManagementActions(),{data:C,isLoading:S}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"}),{groups:v,isLoading:k}=s.useShareableGroups("tenant",(a==null?void 0:a.tenantId)||E),[N,F]=A.useState((a==null?void 0:a.type)==="organization"?"all_tenants":"specific_tenant_users");A.useEffect(()=>{(a==null?void 0:a.type)==="tenant"?(D.setCurrentContext("tenant-dialog"),D.setCurrentMode("specificTenantUsers")):(D.setCurrentContext("tenant-tab"),D.setCurrentMode("allTenants"))},[D,a==null?void 0:a.type]);const T=P=>{var ee,oe,le,ue;F(P);let J;if(P==="specific_tenant_users"?J="specific_users":P==="all_tenant_users"||P==="all_tenants"?J="all_users":P==="groups"?J="groups":J="specific_users",r==null||r(J),P==="groups"?(D.setCurrentContext("group-share"),D.setCurrentMode("specificGroups")):(a==null?void 0:a.type)==="tenant"?(D.setCurrentContext("tenant-dialog"),P==="specific_tenant_users"?D.setCurrentMode("specificTenantUsers"):P==="all_tenant_users"&&(D.setCurrentMode("allTenantUsers"),a!=null&&a.tenantId&&D.setSelectedTenant(a.tenantId))):(D.setCurrentContext("tenant-tab"),P==="specific_tenant_users"?D.setCurrentMode("specificTenantUsers"):P==="all_tenant_users"?D.setCurrentMode("allTenantUsers"):P==="all_tenants"&&D.setCurrentMode("allTenants")),P==="all_tenant_users"){const ce=(oe=(ee=w==null?void 0:w.shares)==null?void 0:ee.tenantWide)==null?void 0:oe[0];ce&&ce.role!==void 0&&D.setTenantWideRole(ce.role)}else if(P==="all_tenants"){const ce=(ue=(le=w==null?void 0:w.shares)==null?void 0:le.allTenantsOnly)==null?void 0:ue[0];ce&&ce.role!==void 0&&D.setAllTenantsRole(ce.role)}},B=P=>{D.setSelectedTenant(P)},{allUsers:I,existingShares:w,isLoadingUsers:M,isErrorLoadingUsers:L,isLoadingShares:O,isErrorLoadingShares:R}=He({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant",tenantId:(a==null?void 0:a.type)==="tenant"?a.tenantId:E}),z=P=>{var le,ue;const J=m.some(ce=>ce.id===P),ee=h.includes(P),oe=(ue=(le=w==null?void 0:w.shares)==null?void 0:le.specificTenantUsers)==null?void 0:ue.some(ce=>ce.tenantUserId===P);J?D.removeSelectedUser(P):ee?D.removeUserFromRemove(P):oe||D.addSelectedUser({id:P,role:"VIEWER"})},G=(P,J)=>{D.updateSelectedUserRole(P,J)},Q=P=>{D.addUserToRemove(P),D.removeSelectedUser(P)},_=P=>{D.removeUserFromRemove(P)},W=P=>{D.removeUserFromUpdate(P)},$=(P,J,ee)=>{D.addUserToUpdate({id:P,currentRole:J,newRole:ee})},X=(P,J)=>{N==="all_tenant_users"?D.setTenantWideRole(J):N==="all_tenants"&&D.setAllTenantsRole(J)},Y=()=>{N==="all_tenant_users"?D.setTenantWideRole("VIEWER"):N==="all_tenants"&&D.setAllTenantsRole("VIEWER")},U=(()=>{var P,J,ee,oe;return j==="allTenants"?(J=(P=w==null?void 0:w.shares)==null?void 0:P.allTenantsOnly)==null?void 0:J[0]:j==="allTenantUsers"?(oe=(ee=w==null?void 0:w.shares)==null?void 0:ee.tenantWide)==null?void 0:oe[0]:null})();A.useEffect(()=>{var P,J,ee,oe;if(N==="all_tenant_users"){const le=(J=(P=w==null?void 0:w.shares)==null?void 0:P.tenantWide)==null?void 0:J[0];le&&le.role!==void 0&&D.setTenantWideRole(le.role)}else if(N==="all_tenants"){const le=(oe=(ee=w==null?void 0:w.shares)==null?void 0:ee.allTenantsOnly)==null?void 0:oe[0];le&&le.role!==void 0&&D.setAllTenantsRole(le.role)}},[N,w,D]);const Z=I.filter(P=>m.some(J=>J.id===P.id)),ne=P=>{const J=g.some(le=>le.id===P),ee=b.includes(P),oe=re==null?void 0:re.some(le=>le.groupId===P);J?D.removeSelectedGroup(P):ee?D.removeGroupFromRemove(P):oe||D.addSelectedGroup({id:P,role:"VIEWER"})},he=(P,J)=>{D.updateSelectedGroupRole(P,J)},ge=P=>{D.addGroupToRemove(P),D.removeSelectedGroup(P)},V=(P,J,ee)=>{D.addGroupToUpdate({id:P,currentRole:J,newRole:ee})},se=v.filter(P=>g.some(J=>J.id===P.id)),te=A.useMemo(()=>N!=="groups"?[]:v.filter(P=>P.type!=="TENANT_GROUP"?!1:P.name.toLowerCase().includes(i.toLowerCase())||P.description&&P.description.toLowerCase().includes(i.toLowerCase())),[v,N,i]),re=A.useMemo(()=>{var J,ee;const P=((J=w==null?void 0:w.shares)==null?void 0:J.specificGroups)||((ee=w==null?void 0:w.shares)==null?void 0:ee.groups)||[];return!P||P.length===0?[]:P.filter(oe=>{const le=v.find(ue=>ue.id===oe.groupId);return(le==null?void 0:le.type)==="TENANT_GROUP"})},[w,v]),ie=M||O||N==="groups"&&k,de=L||R,xe=()=>(a==null?void 0:a.type)==="tenant"||N==="all_tenants"||N==="groups"?!0:E&&(N==="specific_tenant_users"||N==="all_tenant_users");return e.jsxs(e.Fragment,{children:[de&&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"})]})}),!de&&a&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(Is,{shareType:N,onShareTypeChange:T,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(Gs,{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"&&(N==="specific_tenant_users"||N==="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:E||"",onValueChange:B,disabled:S,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:S?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(H=C==null?void 0:C.tenants)==null?void 0:H.map(P=>e.jsx(s.SelectItem,{value:P.id,children:P.name},P.id))})]})]}),xe()?e.jsx(e.Fragment,{children:N==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(cs,{value:i,onChange:u}),e.jsx(ut,{selectedUsers:m,selectedUserObjects:Z,onRemove:P=>z(P),onRoleChange:G,getRoleOptions:Ce}),e.jsx(mt,{usersToRemove:h,allUsers:I,onRemove:_}),e.jsx(ht,{usersToUpdate:x,allUsers:I,onRemove:W,getRoleOptions:Ce}),e.jsx(ft,{existingShares:w,isInitialLoading:!!ie,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:Ce,allUsers:I,currentUser:a,handleUserToggle:z,handleUserRoleChange:G,handleRemoveAccess:Q,handleUpdateAccess:$})]}):N==="groups"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(cs,{value:i,onChange:u,placeholder:"Search groups..."}),e.jsx(bt,{selectedGroups:g,groupObjects:se,onRemove:ne,onRoleChange:he,getRoleOptions:Ce}),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(jt,{groups:te,existingGroupShares:re,isLoading:k,resource:t,getRoleOptions:Ce,currentUser:a,handleGroupToggle:ne,handleGroupRoleChange:he,handleRemoveAccess:ge,handleUpdateAccess:V})]}):N==="all_tenant_users"||N==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(gt,{currentUser:a,currentShare:U,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:X,onRemoveAccess:Y,allUsersToUpdate:j==="allTenantUsers"&&((U==null?void 0:U.role)===void 0||f!==U.role)||j==="allTenants"&&((U==null?void 0:U.role)===void 0||y!==U.role)?{currentRole:(U==null?void 0:U.role)||"VIEWER",newRole:j==="allTenantUsers"?f:y}:null,allUsersToRemove:j==="allTenantUsers"&&(U==null?void 0:U.role)===void 0||j==="allTenants"&&(U==null?void 0:U.role)===void 0})}):null}):(a==null?void 0:a.type)==="organization"&&(N==="specific_tenant_users"||N==="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(Gs,{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 gn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var L,O;const{searchQuery:i,setSearchQuery:d}=s.useShareSearchWithDebounce(),u=s.useShareSelectedGroups(),m=s.useShareGroupsToRemove(),h=s.useShareGroupsToUpdate(),x=s.useShareManagementActions(),[g,b]=A.useState("org_groups"),[p,j]=A.useState(""),{data:f,isLoading:y}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"&&g==="tenant_groups"}),E=Array.isArray(f)?f:(f==null?void 0:f.tenants)||[],D=()=>{if((a==null?void 0:a.type)==="organization")return"organization";if((a==null?void 0:a.type)==="tenant")return"tenant"},{groups:C,isLoading:S}=s.useShareableGroups(D(),g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"?p:a==null?void 0:a.tenantId),{existingShares:v}=He({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n}),k=C.filter(R=>g==="org_groups"&&R.type!=="ORG_GROUP"||g==="tenant_groups"&&R.type!=="TENANT_GROUP"||g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&(!p||R.tenantId&&R.tenantId!==p)?!1:R.name.toLowerCase().includes(i.toLowerCase())||R.description&&R.description.toLowerCase().includes(i.toLowerCase())),N=((L=v==null?void 0:v.shares)==null?void 0:L.specificGroups)||((O=v==null?void 0:v.shares)==null?void 0:O.groups)||[];A.useEffect(()=>{x.setCurrentContext("group-share"),x.setCurrentMode("specificGroups")},[x]);const F=R=>{const z=R;b(z),z==="org_groups"&&j(""),r==null||r(z==="org_groups"?"specific_groups":"all_groups"),x.setCurrentContext("group-share"),x.setCurrentMode("specificGroups")},T=C.filter(R=>u.some(z=>z.id===R.id)),B=R=>{const z=u.some(_=>_.id===R),G=m.includes(R),Q=N==null?void 0:N.some(_=>_.groupId===R);z?x.removeSelectedGroup(R):G?x.removeGroupFromRemove(R):Q||x.addSelectedGroup({id:R,role:"VIEWER"})},I=(R,z)=>{x.updateSelectedGroupRole(R,z)},w=R=>{x.addGroupToRemove(R),x.removeSelectedGroup(R)},M=(R,z,G)=>{x.addGroupToUpdate({id:R,currentRole:z,newRole:G})};return a?e.jsxs(e.Fragment,{children:[e.jsx(Is,{shareType:g,onShareTypeChange:F,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:y,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:y?"Loading tenants...":"Select a tenant to view its groups"})}),e.jsx(s.SelectContent,{className:"z-[51]",children:E.map(R=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:R.id,children:R.name},R.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(cs,{value:i,onChange:d,placeholder:"Search groups..."}),e.jsx(bt,{selectedGroups:u,groupObjects:T,onRemove:B,onRoleChange:I,getRoleOptions:Ce}),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(jt,{groups:k,existingGroupShares:N,isLoading:S,resource:t,getRoleOptions:Ce,currentUser:a,handleGroupToggle:B,handleGroupRoleChange:I,handleRemoveAccess:w,handleUpdateAccess:M})]})})]}):null}const vt=()=>{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=A.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=A.useMemo(()=>j=>s.validateShareData(j),[]),p=A.useMemo(()=>{if(!t||!n)return!1;switch(t){case"org-tab":return n==="specificOrgUsers"?a.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(n==="allTenantUsers"){if(!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 Hs({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:y,isCurrentStateValid:E}=vt(),D=a||r||l,C=()=>{var F,T,B,I;if(D)return"Updating...";if(i==="specific_users"){if(m.length===0&&h.length===0&&x.length===0)return"Select users to share with";const w=m.length+h.length+x.length;return w===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${w} user${w!==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 ${w} user${w!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const w=d.role;return b===w?"Remove Access":"Update Access"}else if(i==="all_tenants"){const w=(T=(F=n==null?void 0:n.shares)==null?void 0:F.allTenantsOnly)==null?void 0:T[0];if(!w||w.role===void 0)return"Share with All Tenants";const M=w.role;return p===M?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const w=(I=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:I[0];if(!w||w.role===void 0)return"Share with All Tenant Users";const M=w.role;return j===M?"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 w=m.length+h.length+x.length;return w===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${w} user${w!==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 ${w} user${w!==1?"s":""}`}return"Share"},S=()=>D||!t||i==="all_tenant_users"&&!g||i==="specific_tenant_users"&&!g?!0:!E,v=()=>{const F=f();F&&y(F)&&o(F)},k=()=>{var F,T,B,I;if(i==="all_users")if(!d||d.role===void 0){const w=f();w&&y(w)&&o(w)}else{const w=d.role;if(b===w)u==null||u();else{const L=f();if(L&&y(L)){const O={...L,updateAccess:!0};o(O)}}}else if(i==="all_tenants"){const w=(T=(F=n==null?void 0:n.shares)==null?void 0:F.allTenantsOnly)==null?void 0:T[0];if(!w||w.role===void 0){const M=f();M&&y(M)&&o(M)}else{const M=w.role;if(p===M)u==null||u();else{const O=f();if(O&&y(O)){const R={...O,updateAccess:!0};o(R)}}}}else if(i==="all_tenant_users"){const w=(I=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:I[0];if(!w||w.role===void 0){const M=f();M&&y(M)&&o(M)}else{const M=w.role;if(j===M)u==null||u();else{const O=f();if(O&&y(O)){const R={...O,updateAccess:!0};o(R)}}}}},N=()=>{var F,T,B,I;if(i==="all_users"){if(!d||d.role===void 0)return"default";const w=d.role;return b===w?"destructive":"default"}else if(i==="all_tenants"){const w=(T=(F=n==null?void 0:n.shares)==null?void 0:F.allTenantsOnly)==null?void 0:T[0];if(!w||w.role===void 0)return"default";const M=w.role;return p===M?"destructive":"default"}else if(i==="all_tenant_users"){const w=(I=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:I[0];if(!w||w.role===void 0)return"default";const M=w.role;return j===M?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:D,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||D,variant:"default",children:[D?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!D&&C()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:k,disabled:S(),variant:N(),children:[D?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"}),!D&&C()]})]})}function jn({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}=vt(),y=n||a||r,E=()=>{if(y)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&m.length===0)return"Select users to share with";const N=d.length+u.length+m.length;return N===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${N} user${N!==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 ${N} user${N!==1?"s":""}`}else if(c==="groups"){if(h.length===0&&x.length===0&&g.length===0)return"Select groups to share with";const N=h.length+x.length+g.length;return N===0?"Select groups to share with":h.length>0&&x.length>0?`Update access for ${N} group${N!==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 ${N} group${N!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const N=i.role;return b===N?"Remove Access":"Update Access"}return"Share"},D=()=>y||!t?!0:!f,C=()=>{const N=p();N&&j(N)&&l(N)},S=()=>{const N=p();N&&j(N)&&l(N)},v=()=>{if(!i||i.role==="NONE"){const N=p();N&&j(N)&&l(N)}else{const N=i.role;if(b===N){const T=p();if(T&&j(T)){const B={...T,removeAccess:!0};l(B)}}else{const T=p();if(T&&j(T)){const B={...T,updateAccess:!0};l(B)}}}},k=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:o,disabled:y,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:C,disabled:!t||y,variant:"default",children:[y?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!y&&E()]})}),c==="groups"&&e.jsx(e.Fragment,{children:(h.length>0||x.length>0||g.length>0)&&e.jsxs(s.Button,{onClick:S,disabled:!t||y,variant:"default",children:[y?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!y&&E()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:v,disabled:D(),variant:k(),children:[y?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!y&&E()]})]})}function bn({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 ye(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function ke(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function vn(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=ye(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=ye(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=ke(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=ye(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=ye(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="allTenantUsers"){const u=ye(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=ke(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(y=>y.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=ye(r,l,[{scope:"specific_tenant_user",tenantUserId:g.id,tenantId:x,role:g.newRole}]);o(b,{onSuccess:()=>{d()}})}),u&&u.length>0){const g=ye(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=ke(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);c(u,{onSuccess:()=>{d()}})}else if(t.updateAccess){const u=ye(r,l,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else{const u=ye(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=ye(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=ke(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=ye(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=ye(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=ke(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=ye(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 yn(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=ke(l,o,t.map(j=>{var y,E;const f=(E=(y=i==null?void 0:i.shares)==null?void 0:y.specificTenantUsers)==null?void 0:E.find(D=>D.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 y=ke(l,o,[{scope:"all_tenants_only",role:f.role}]);c(y,{onSuccess:()=>{d()},onError:E=>{console.error("Remove all-tenants access failed:",E)}})}}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 y=ke(l,o,[{scope:"all_tenant_users",role:f.role}]);c(y,{onSuccess:()=>{d()},onError:E=>{console.error("Remove all-tenant-users access failed:",E)}})}}else{const f=(b=(g=i==null?void 0:i.shares)==null?void 0:g.orgUsersOnly)==null?void 0:b[0];if(f){const y=ke(l,o,[{scope:"org_users_only",role:f.role}]);c(y,{onSuccess:()=>{d()},onError:E=>{console.error("Remove org-wide access failed:",E)}})}}}}function Nn(t,n,a){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=s.useCurrentUserInfo(),{existingShares:d}=He({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),u=A.useCallback(()=>{r.resetUserSelections()},[r]),m=A.useCallback(()=>{r.resetGroupSelections()},[r]),h=A.useCallback(g=>{if(!t)return;const b={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:n,removeMutation:a,existingShares:d,resetUserSelections:u,resetGroupSelections:m};vn(g,b,i)},[t,n,a,d,u,m,i]),x=A.useCallback(()=>{if(!t)return;const g={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:a,existingShares:d,resetUserSelections:u};yn(l,o||"",c||"",g)},[t,n,a,d,u,m,l,o,c]);return{handleShareSubmit:h,handleRemoveAccess:x}}function hs({resource:t,resourceType:n,onClose:a,onShareSuccess:r,onRemoveSuccess:l}){var I,w,M,L,O,R,z,G;const{currentUser:o}=s.useCurrentUserInfo(),[c,i]=A.useState("specific_users"),[d,u]=A.useState("specific_users"),[m,h]=A.useState("specific_groups"),x=s.useShareManagementActions(),g=s.useShareSelectedTab(),b=s.useShareCurrentMode(),p=s.useShareResource(),j=s.useRemoveResourceShares(),{handleShareSubmit:f,handleRemoveAccess:y}=Nn(t.id,(Q,_)=>{p.mutate(Q,{..._,onSuccess:()=>{var W;(W=_==null?void 0:_.onSuccess)==null||W.call(_),r==null||r()}})},(Q,_)=>{j.mutate(Q,{..._,onSuccess:()=>{var W;(W=_==null?void 0:_.onSuccess)==null||W.call(_),l==null||l()}})}),E=p.isPending,D=j.isPending,C=p.isPending,{existingShares:S}=He({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant"}),{existingShares:v}=He({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"organization"}),k=(w=(I=S==null?void 0:S.shares)==null?void 0:I.tenantWide)==null?void 0:w[0],N=(L=(M=v==null?void 0:v.shares)==null?void 0:M.orgUsersOnly)==null?void 0:L[0],F=()=>{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"}},T=A.useCallback(()=>{x.resetShareState(),a()},[x,a]),B=(o==null?void 0:o.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:T,children:e.jsxs(s.DialogContent,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ye,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:B?"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."})]}),B?e.jsxs(s.Tabs,{value:g,onValueChange:Q=>{const _=Q;x.setSelectedTab(_),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(xn,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:u,isSharing:E,isUpdating:C,isRemoving:D})})}),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(qs,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:Q=>i(Q),isSharing:E,isUpdating:C,isRemoving:D})})}),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(gn,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:h,isSharing:E,isUpdating:C,isRemoving:D})})})]}):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(qs,{resource:t,resourceType:n,currentUser:o,onShareTabTypeChange:Q=>i(Q),isSharing:E,isUpdating:C,isRemoving:D})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:B?g==="org"?e.jsx(Hs,{resource:t,existingShares:v,isSharing:E,isRemoving:D,isUpdating:C,onShare:f,onClose:a,shareTabType:d,currentAllUsersShare:N,onRemoveAccess:y}):g==="tenant"?e.jsx(Hs,{resource:t,existingShares:S,isSharing:E,isRemoving:D,isUpdating:C,onShare:f,onClose:a,shareTabType:F(),currentAllUsersShare:k,onRemoveAccess:y}):e.jsx(bn,{resource:t,existingShares:v,isSharing:E,isRemoving:D,isUpdating:C,onShare:f,onClose:a,shareTabType:m,currentAllGroupsShare:(o==null?void 0:o.type)==="organization"?(R=(O=v==null?void 0:v.shares)==null?void 0:O.allOrgGroups)==null?void 0:R[0]:(G=(z=S==null?void 0:S.shares)==null?void 0:z.allTenantGroups)==null?void 0:G[0],onRemoveAccess:y}):e.jsx(jn,{resource:t,isSharing:E,isRemoving:D,isUpdating:C,onShare:f,onClose:a,shareTabType:c,currentAllUsersShare:k,onRemoveAccess:y})})]})})}function yt({type:t,isLinked:n,className:a}){const r=s.useDashboardStore(u=>u.selectedFrameId),l=s.useManagementStore(u=>u.selectedVisual),o=s.useEditorStore(u=>u.frame);let c;if(t)c=t;else if(n!==void 0)c=n?"linked":"library";else if(!!!(o!=null&&o.visualId||l!=null&&l.id)&&r)c="local";else if(l&&!r)c="library";else if(o!=null&&o.visualId&&r)c="linked";else if(l!=null&&l.id&&r)c="library";else return null;const i={local:"bg-gray-100 text-gray-700",linked:"bg-purple-100 text-purple-700",library:"bg-blue-100 text-blue-700"},d={local:"Local Visual",linked:"Linked Visual",library:"Library Visual"};return e.jsx("span",{className:s.cn("rounded-full px-2.5 py-0.5 text-xs font-medium",i[c],a),children:d[c]})}const Cn=async(t,n,a)=>{const r=`${t}/management/v1/groups`;return await s.postRequestRegular(r,n,a)},Sn=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")}},wn=async(t,n,a,r)=>{const l=`${t}/management/v1/groups/${a}/members`;return await s.postRequestRegular(l,n,r)},Dn=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 Tn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>Cn(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 kn(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:r=>Sn(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",r),onSuccess:(r,l)=>{a.invalidateQueries({queryKey:["groups"]}),a.removeQueries({queryKey:["group",l]}),s.ue.success("Group deleted successfully")},onError:r=>{console.error("Failed to delete group:",r),s.ue.error("Failed to delete group",{description:r.message})}})}function En(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>wn(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 In(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient();return s.useMutation({mutationFn:({groupId:r,data:l})=>Dn(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 An({onSuccess:t,tenantId:n,isTenantUser:a}){const[r,l]=A.useState(""),[o,c]=A.useState(""),[i,d]=A.useState({}),u=Tn(),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 Mn({open:t,onOpenChange:n,group:a,onUpdate:r}){const[l,o]=A.useState("members"),[c,i]=A.useState(""),[d,u]=A.useState([]),[m,h]=A.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}),y=En(),E=In(),D=(x==null?void 0:x.members)||[],C=A.useMemo(()=>new Set(D.map(I=>I.userId)),[D]),S=A.useMemo(()=>j.filter(I=>!C.has(I.id)),[j,C]),v=A.useMemo(()=>{if(!c)return S;const I=c.toLowerCase();return S.filter(w=>{var M,L;return((M=w.name)==null?void 0:M.toLowerCase().includes(I))||((L=w.email)==null?void 0:L.toLowerCase().includes(I))})},[S,c]),k=A.useMemo(()=>{if(!c)return D;const I=c.toLowerCase();return D.filter(w=>{var M,L,O,R;return((L=(M=w.user)==null?void 0:M.name)==null?void 0:L.toLowerCase().includes(I))||((R=(O=w.user)==null?void 0:O.email)==null?void 0:R.toLowerCase().includes(I))})},[D,c]),N=async()=>{if(d.length!==0)try{await y.mutateAsync({groupId:a.id,data:{userIds:d,userType:p==="tenant"?"tenant":"org"}}),u([]),o("members"),b(),r==null||r()}catch(I){console.error("Failed to add members:",I)}},F=async()=>{if(m.length!==0)try{await E.mutateAsync({groupId:a.id,data:{userIds:m}}),h([]),b(),r==null||r()}catch(I){console.error("Failed to remove members:",I)}},T=I=>{u(w=>w.includes(I)?w.filter(M=>M!==I):[...w,I])},B=I=>{h(w=>w.includes(I)?w.filter(M=>M!==I):[...w,I])};return e.jsx(e.Fragment,{children:e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-3xl max-h-[80vh]","aria-describedby":"group-members-description",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:a.name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[D.length," ",D.length===1?"member":"members"]})}),e.jsxs("p",{id:"group-members-description",className:"sr-only",children:["Add or remove members from the ",a.name," group"]})]}),e.jsxs(s.Tabs,{value:l,onValueChange:I=>{o(I),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:I=>i(I.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(I=>e.jsx(s.Skeleton,{className:"h-16 w-full"},I))}):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(I=>e.jsx(Ln,{member:I,selected:m.includes(I.userId),onToggle:()=>B(I.userId)},I.id))})}),m.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[m.length," member",m.length!==1?"s":""," selected"]}),e.jsx(s.Button,{variant:"destructive",size:"sm",onClick:F,disabled:E.isPending,children:E.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:I=>i(I.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(I=>e.jsx(s.Skeleton,{className:"h-16 w-full"},I))}):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(I=>e.jsx(Rn,{user:I,selected:d.includes(I.id),onToggle:()=>T(I.id)},I.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:N,disabled:y.isPending,children:y.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 Ln({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 Rn({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 On({open:t,onOpenChange:n}){const[a,r]=A.useState("groups"),[l,o]=A.useState(""),[c,i]=A.useState(null),[d,u]=A.useState(!1),[m,h]=A.useState(null),{tokenProps:x}=s.useSemaphorContext(),{currentUser:g}=s.useCurrentUserInfo(),b=kn(),p=(g==null?void 0:g.type)==="tenant",j=x==null?void 0:x.tenantId,{groups:f,isLoading:y,refetch:E}=s.useGroups({type:p?"TENANT_GROUP":"all",tenantId:p?j:void 0,includeMembers:!1}),D=f.filter(k=>{var N;return k.name.toLowerCase().includes(l.toLowerCase())||((N=k.description)==null?void 0:N.toLowerCase().includes(l.toLowerCase()))}),C=async()=>{if(m)try{await b.mutateAsync(m.id),h(null),E()}catch(k){console.error("Failed to delete group:",k)}},S=k=>{i(k),u(!0)},v=()=>{r("groups"),E()};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:y?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(k=>e.jsx(s.Skeleton,{className:"h-24 w-full"},k))}):D.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:D.map(k=>e.jsx(Fn,{group:k,onManageMembers:()=>S(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(An,{onSuccess:v,tenantId:j,isTenantUser:p})})]})]})}),c&&e.jsx(Mn,{open:d,onOpenChange:u,group:c,onUpdate:()=>E()}),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:C,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 Fn({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 As(t){const[n,a]=A.useState(null),[r,l]=A.useState(null);return A.useEffect(()=>{if(!t||t.trim()===""){a(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const 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 Bn(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 Pn(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 Ws(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 Nt(t){if(typeof t=="string")return JSON.parse(t);if(typeof t=="object")return t;throw new Error("Invalid frame object format")}function zn(t,n){var o,c;const a=(t==null?void 0:t.frameObject)??((o=t==null?void 0:t.visual)==null?void 0:o.frameObject);if(!a)return!1;const r=Nt(a);if(!(r!=null&&r.cards)||r.cards.length===0)return!1;const l=(c=r.cards)==null?void 0:c.find(i=>i.id===r.activeCardId);return l?(s.setupEditorWithCard({...n,frame:r,card:l,visualId:(t==null?void 0:t.id)||r.visualId}),!0):!1}function Vn(){var x;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(g=>g.frame),a=s.useEditorStore(g=>g.card),r=As(((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:A.useCallback(()=>{var f;let g=m;m&&!m.includes("{{")&&(g=Bn(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(y=>y.id===a.id?p:y);return{...n,cards:j,activeCardId:Pn(j,n.activeCardId)}},[a,n,u,l,o,c,i,d,t,r,m])}}function Ve(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),a=s.useQueryClient(),r=s.useSelectedVisual(),{selectVisual:l}=s.useManagementActions(),{setFrame:o,setCard:c,setIsDevMode:i,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:h,setSelectedDatabaseName:x,setSelectedSchemaName:g,setSelectedTableName:b,setSelectedDatamodelId:p,setFilterValues:j,setApplyFilters:f}=s.useEditorActions(),{setIsDashboardEditing:y,setIsVisualEditing:E,setSelectedFrameId:D,clearSelectedFrameId:C,addFrame:S,setIsDashboardPanelOpen:v}=s.useDashboardActions(),k=s.useDashboardStore(M=>M.selectedSheetId),N=s.useDashboardStore(M=>M.selectedFrameId),F=s.useDashboardStore(M=>M.dashboard),T=s.useDashboardStore(M=>M.filterValues),B=s.useVisualById((r==null?void 0:r.id)||"",{enabled:!!(r!=null&&r.id)&&!!(t!=null&&t.accessToken)}),I=A.useCallback(async M=>{try{l(M),C();const{data:L,fromCache:O}=await Ws(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",M.id,a);if(!zn(L,{setFrame:o,setCard:c,setIsDevMode:i,setActiveTabCardId:d,updateDataSource:u,setQueryResultColumns:m,setSelectedConnectionId:h,setSelectedDatabaseName:x,setSelectedSchemaName:g,setSelectedTableName:b,setSelectedDatamodelId:p,setFilterValues:j,setApplyFilters:f,setIsDashboardEditing:y,setIsVisualEditing:E,dashboard:F,selectedSheetId:k,selectedFrameId:N,filterValues:T}))throw new Error("Failed to setup editor with visual data");return{success:!0,fromCache:O}}catch(L){return console.error("Error editing visual:",L),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,o,c,y,E,i,d,u,m,h,x,g,b,p,j,f,C,F,k,N,T]),w=A.useCallback(async M=>{var L;try{if(l(M),!k)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:O,fromCache:R}=await Ws(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",M.id,a),z=(O==null?void 0:O.frameObject)??((L=O==null?void 0:O.visual)==null?void 0:L.frameObject);if(!z)return{success:!1,error:"Visual has no frame data"};const G=Nt(z);if(!(G!=null&&G.cards)||G.cards.length===0)return{success:!1,error:"Visual frame is malformed"};const Q={...G,id:s.v4(),visualId:M.id};return S(k,Q,"end"),y(!0),D(Q.id),v(!1),{success:!0,fromCache:R}}catch(O){return console.error("Error adding visual:",O),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n.apiServiceUrl,a,l,k,S,y,D,v]);return{visual:B.data,isLoading:B.isLoading,isError:B.isError,error:B.error,handleEditLibraryVisual:I,handleAddLibraryVisual:w,getUpdatedFrame:Vn().getUpdatedFrame,refetch:B.refetch}}function _n({open:t,onOpenChange:n,isLibraryVisual:a,currentVisualName:r,isSaving:l=!1,onConfirm:o}){const[c,i]=A.useState(a&&r?`Copy of ${r}`:r||""),[d,u]=A.useState(""),[m,h]=A.useState(!a),[x,g]=A.useState(!0);A.useEffect(()=>{t&&(i(a&&r?`Copy of ${r}`:r||""),u(""),h(!a),g(!0))},[t,a,r]);const b=()=>{c.trim()&&(!m&&!x||o({name:c.trim(),description:d.trim()||void 0,saveToLibrary:m,saveToCurrentDashboard:x}))},p=c.trim()&&(m||x);return e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Save Visual As"}),e.jsx(s.DialogDescription,{children:a?"Create a copy of this visual with a new name":"Save this visual to make it reusable"})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"name",children:"Name"}),e.jsx(s.Input$1,{id:"name",value:c,onChange:j=>i(j.target.value),placeholder:"Enter visual name",disabled:l})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"description",children:"Description (optional)"}),e.jsx(s.Textarea,{id:"description",value:d,onChange:j=>u(j.target.value),placeholder:"Enter visual description",rows:3,disabled:l})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Label,{children:"Save to:"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"save-to-dashboard",checked:x,onCheckedChange:j=>g(!!j),disabled:l}),e.jsxs("label",{htmlFor:"save-to-dashboard",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Current Dashboard",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:a?"(add copy to this dashboard)":"(keep as local visual)"})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"save-to-library",checked:m,onCheckedChange:j=>h(!!j),disabled:l}),e.jsxs("label",{htmlFor:"save-to-library",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Visual Library",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:a?"(save as new reusable visual)":"(make available to all dashboards)"})]})]})]}),!m&&!x&&e.jsx("p",{className:"text-sm text-destructive",children:"Please select at least one destination"})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),disabled:l,children:"Cancel"}),e.jsxs(s.Button,{onClick:b,disabled:!p||l,children:[l&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Saving...":"Save"]})]})]})})}function Ct({className:t,variant:n="outline"}){var i;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(d=>d.frame);const r=s.useEditorStore(d=>d.card);As(((i=r.customCardPreferences)==null?void 0:i.url)||""),s.useEditorStore(d=>d.selectedSchemaName),s.useEditorStore(d=>d.selectedDatamodelId),s.useEditorStore(d=>d.selectedDatabaseName),s.useEditorStore(d=>d.selectedTableName),s.useEditorStore(d=>d.selectedConnectionId),s.useEditorStore(d=>d.isShowingVisual),r.sql;const l=s.useEditorStore(d=>d.onSave),{getUpdatedFrame:o}=Ve();function c(){const d=o();l==null||l(d)}return e.jsxs(s.Button,{onClick:c,className:s.cn("h-8",t),size:"sm",variant:n,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Un({className:t,variant:n="default"}){const a=s.useQueryClient(),[r,l]=A.useState(!1),o=s.useDashboardStore(x=>x.actions.setIsDashboardPanelOpen),{setIsVisualEditing:c}=s.useDashboardActions(),{getUpdatedFrame:i}=Ve(),d=s.useSelectedVisual(),u=s.useEditorStore(x=>x.frame),m=s.useUpdateVisualMutation(),h=()=>{const x=i(),g=(u==null?void 0:u.visualId)||(d==null?void 0:d.id);if(!g){s.ue.error("No visual to save");return}l(!0),m.mutate({visualId:g,data:{frameObject:x}},{onSuccess:()=>{l(!1),o(!0),s.ue.success("Visual updated successfully"),a.invalidateQueries({queryKey:["resource-by-id","visual",g],exact:!0})},onError:()=>{l(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:h,className:s.cn("h-8",t),size:"sm",variant:n,children:[r&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!r&&e.jsxs(e.Fragment,{children:[e.jsx(qe,{className:"mr-2 size-4 font-bold"}),"Save to Library"]})]})}function Gn({className:t}){const n=s.useQueryClient(),[a,r]=A.useState(!1),l=s.useSelectedVisual(),o=s.useEditorStore(x=>x.frame),c=s.useDashboardStore(x=>x.selectedSheetId),{updateFrame:i,setIsVisualEditing:d}=s.useDashboardActions(),{getUpdatedFrame:u}=Ve(),m=s.useUpdateVisualMutation(),h=async()=>{if(!c){s.ue.error("No sheet selected");return}const x=(o==null?void 0:o.visualId)||(l==null?void 0:l.id);if(!x){s.ue.error("No visual to update");return}r(!0);try{const g=u();await m.mutateAsync({visualId:x,data:{frameObject:g}});const b={...g,visualId:x};i(c,b),n.invalidateQueries({queryKey:["visuals"]}),n.invalidateQueries({queryKey:["visual",x]}),s.ue.success("Saved to library and applied locally"),setTimeout(()=>{d(!1)},300)}catch(g){console.error("Failed to save and apply:",g),s.ue.error("Failed to save and apply changes")}finally{r(!1)}};return e.jsx(s.Button,{onClick:h,className:s.cn("h-8",t),size:"sm",variant:"default",disabled:a,children:a?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(qe,{className:"mr-2 size-4 font-bold"}),"Save & Apply"]})})}function Yn({className:t}){const{getUpdatedFrame:n}=Ve();s.useEditorStore(d=>d.frame);const a=s.useDashboardStore(d=>d.selectedSheetId),{updateFrame:r,setIsVisualEditing:l}=s.useDashboardActions(),[o,c]=A.useState(!1),i=()=>{if(!a){s.ue.error("No sheet selected");return}c(!0);const u={...n(),visualId:void 0};r(a,u),setTimeout(()=>{c(!1),s.ue.success("Changes applied. Visual is now local to this dashboard"),l(!1)},300)};return e.jsxs(s.Button,{onClick:i,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Applying"]}),!o&&e.jsxs(e.Fragment,{children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Apply Locally"]})]})}function St({className:t}){const{setTempQueryData:n,setSqlGen:a}=s.useEditorActions(),r=s.useQueryClient(),l=s.useEditorStore(u=>u.tempQueryData),o=s.useEditorStore(u=>u.onClose),c=s.useEditorStore(u=>u.card),{queryKey:i}=s.useDashboardCardQuery(c);function d(){if(l){const{queryKey:u,queryData:m}=l;u&&m&&r.setQueryData(u,m)}a({}),o==null||o()}return e.jsxs(s.Button,{onClick:d,className:s.cn("h-8",t),size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function xs(){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 $n(){const[t,n]=A.useState(!1),[a,r]=A.useState(!1),[l,o]=A.useState(null),c=s.useEditorStore(D=>D.frame),i=s.useEditorStore(D=>D.card),d=s.useSelectedVisual(),u=s.useDashboardStore(D=>D.selectedSheetId),m=s.useDashboardStore(D=>D.actions.setIsDashboardPanelOpen),{getUpdatedFrame:h}=Ve(),{selectVisual:x}=s.useManagementActions(),{addFrame:g,setSelectedFrameId:b,setIsVisualEditing:p}=s.useDashboardActions(),j=!!(c!=null&&c.visualId),f=(d==null?void 0:d.title)||(i==null?void 0:i.title)||"Untitled Visual",y=s.useCreateVisualWithFrame(D=>{if(D!=null&&D.id){if(x(D),a&&l&&u){const C={...l,id:s.v4(),visualId:D.id};g(u,C,"end"),b(C.id),r(!1),o(null),p(!1)}m(!0),n(!1)}});return{saveAsDialogOpen:t,setSaveAsDialogOpen:n,handleSaveAs:async D=>{if(!u){s.ue.error("No sheet selected");return}const C=h();if(D.saveToLibrary){r(D.saveToCurrentDashboard),o(C);const S={title:D.name,description:D.description,frameObject:C,isPrivate:!1};y.mutate(S)}else if(D.saveToCurrentDashboard){const S={...C,id:s.v4(),visualId:void 0,cards:C.cards.map(v=>({...v,title:v.id===i.id?D.name:v.title}))};g(u,S,"end"),b(S.id),s.ue.success("Visual saved to dashboard"),n(!1),p(!1)}},isLibraryVisual:j,currentVisualName:f,isSaving:y.isPending}}function wt({className:t}){const n=s.useEditorStore(y=>y.frame),a=s.useEditorStore(y=>y.card),r=s.useManagementStore(y=>y.selectedVisual),l=s.useDashboardStore(y=>y.selectedFrameId),o=s.useDashboardStore(y=>y.selectedSheetId),{setIsVisualEditing:c}=s.useDashboardActions(),i=!!(n!=null&&n.visualId||r!=null&&r.id),d=!!(n!=null&&n.visualId&&l),u=i&&!d,{saveAsDialogOpen:m,setSaveAsDialogOpen:h,handleSaveAs:x,isLibraryVisual:g,currentVisualName:b,isSaving:p}=$n(),{handleAddLibraryVisual:j}=Ve(),f=async()=>{if(!o){s.ue.error("No dashboard sheet selected");return}if(!r){s.ue.error("No visual selected");return}const y=await j(r);y.success?(s.ue.success("Visual added to dashboard"),c(!1)):s.ue.error(y.error||"Failed to add visual to dashboard")};return e.jsxs(e.Fragment,{children:[e.jsx(St,{className:t}),!i&&e.jsx(Ct,{className:t,variant:"default"}),i&&e.jsxs(e.Fragment,{children:[d&&e.jsx(Yn,{className:t}),u&&o&&a&&(a.sql||s.hasValidCardConfig(a.config))&&e.jsxs(s.Button,{onClick:f,className:s.cn(t),size:"sm",variant:"outline",children:[e.jsx(fa,{className:"mr-2 size-4 font-bold"}),"Add to Dashboard"]}),u&&e.jsx(Un,{className:t,variant:"outline"}),d&&e.jsx(Gn,{className:t}),e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:s.cn(t,"w-8 p-0"),children:e.jsx(s.EllipsisVertical,{className:"h-4 w-4"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),h(!0)},children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]})]}),!i&&e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:s.cn(t,"w-8 p-0"),children:e.jsx(s.EllipsisVertical,{className:"h-4 w-4"})})}),e.jsx(s.DropdownMenuContent,{align:"end",children:e.jsxs(s.DropdownMenuItem,{onClick:()=>h(!0),children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]}),e.jsx(_n,{open:m,onOpenChange:y=>{p||h(y)},isLibraryVisual:g,currentVisualName:b,isSaving:p,onConfirm:x})]})}function Dt({className:t,labelClassName:n,switchClassName:a}){const r=s.useEditorStore(d=>d.isDevMode),l=s.useDashboardStore(d=>d.isVisualEditing),{setIsDevMode:o}=s.useEditorActions(),{config:c}=A.useContext(s.SemaphorContext).tokenProps,i=(c==null?void 0:c.showAdvancedMode)!==!1;return!l||!i?null:e.jsxs("div",{className:s.cn("flex items-center space-x-2",t),children:[e.jsx(s.Switch,{className:s.cn("",a),checked:r,onCheckedChange:()=>o(!r),id:"advanced-mode"}),e.jsx("label",{htmlFor:"advanced-mode",className:s.cn("text-sm font-medium",n),children:"Advanced Mode"})]})}function qn(){var ie,de,xe;const{authToken:t,tokenProps:n,id:a}=s.useSemaphorContext(),{isLocalDev:r,isConsoleMode:l}=s.useDashboardPreferences(),{permissions:o}=s.useRoleAwareDisplayPreferences(),c=s.useHasDashboardId();s.useDashboardStore(H=>H.theme);const i=s.useDashboardStore(H=>H.lenses),d=s.useDashboardStore(H=>H.selectedLensId),u=i==null?void 0:i.find(H=>H.id===d),m=s.useDashboardStore(H=>H.dashboard);s.useDashboardStore(H=>H.selectedSheetId);const h=s.useDashboardStore(H=>H.isDashboardEditing),[x,g]=A.useState(!1),[b,p]=A.useState(!1),[j,f]=A.useState(!1),y=s.useDashboardStore(H=>H.isDashboardPanelOpen),E=s.useDashboardStore(H=>H.actions.setIsDashboardPanelOpen),D=s.useDashboardStore(H=>H.filterValues),C=s.useDashboardStore(H=>H.isVisualEditing),S=s.useEditorStore(H=>H.card),v=s.useManagementStore(H=>H.selectedDashboard),k=s.useManagementStore(H=>H.initialDashboard),N=s.useManagementStore(H=>H.selectedVisual);s.useDashboardStore(H=>H.selectedFrameId),s.useEditorStore(H=>H.frame);const F=v?(de=v==null?void 0:v.permissions)==null?void 0:de.canEdit:(ie=k==null?void 0:k.permissions)==null?void 0:ie.canEdit,T=s.useDashboardStore(H=>H.showFilters),B=s.useDashboardStore(H=>H.showDashboardJSON),I=s.useDashboardStore(H=>H.onSaveFunction),w=s.useDashboardStore(H=>H.actions.setShowFilters),{setIsDashboardEditing:M,setShowDashboardJSON:L}=s.useDashboardStore(H=>H.actions),{setInitialDashboard:O,clearSelectedDashboard:R}=s.useManagementStore(H=>H.actions),{resources:z}=s.useResourceManagement(s.ResourceType.DASHBOARD),{currentUser:G}=s.useCurrentUserInfo(),Q=s.canUserManageGroups(G),_=v||k,W=_?{id:_.id,title:(m==null?void 0:m.title)||_.title||"Dashboard"}:null,{handleAddNewFrame:$}=s.useAddNewFrame(),[X,Y]=A.useState(!1),K=s.useUpdateResource(s.ResourceType.DASHBOARD);A.useEffect(()=>{if(z&&z.length>0){const H=m==null?void 0:m.id;if(H){const P=z.find(J=>J.id===H);P&&O(P)}}},[z,m==null?void 0:m.id,O]);const U=n.orgUserId||n.tenantId,Z=h&&!C&&U&&F,ne=()=>{M(!0)};async function he(){const H=is(m);Y(!0);const P={template:H};K.mutate({resourceId:H.id,data:P},{onSuccess:()=>{Y(!1),s.ue.success("Dashboard saved!")},onError:()=>{Y(!1),s.ue.error("Failed to save dashboard")}})}async function ge(){if(g(!0),!d||!u)return;const H=is(m),P=JSON.stringify(H),J={...u,template:P,filterValues:D};await Ds(n.apiServiceUrl,J,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),I==null||I(H),g(!1)}const V=(u==null?void 0:u.name)||m.title,te=z&&z.length>0&&(n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail),re=v&&!(n!=null&&n.dashboard_id)&&!a;return e.jsxs("div",{className:"flex h-11 items-center justify-between gap-2 border-b px-4 py-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[te&&e.jsxs(e.Fragment,{children:[re&&!C&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Back to Dashboard Hub",onClick:()=>R(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})}),e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:c?"Manage Dashboards":"Select a dashboard to continue",onClick:()=>{c&&E(!y)},className:"h-7 p-2",buttonProps:{disabled:!c},children:e.jsx(Ra,{className:"h-4 w-4"})})]}),!C&&c&&e.jsx(s.Label,{children:V}),C&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm font-medium",children:(N==null?void 0:N.title)||(S==null?void 0:S.title)||"Untitled Visual"}),e.jsx(yt,{})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[C&&e.jsxs(e.Fragment,{children:[e.jsx(Dt,{className:"mr-2"}),e.jsx(wt,{className:"h-7"})]}),r&&!C&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:()=>s.invalidateToken(n.apiServiceUrl),className:"h-7 p-2",children:e.jsx(Ga,{className:"h-4 w-4"})}),!C&&c&&e.jsx(tn,{}),!C&&c&&e.jsx(dt,{}),!C&&c&&Q&&e.jsx(s.IconButton,{tooltip:"Manage Groups",onClick:()=>f(!0),className:"h-7 p-2",children:e.jsx(s.Users,{className:"h-4 w-4"})}),!C&&c&&((xe=_==null?void 0:_.permissions)==null?void 0:xe.canShare)&&e.jsx(s.IconButton,{tooltip:"Share Dashboard",onClick:()=>p(!0),className:"h-7 p-2",children:e.jsx(s.UserPlus,{className:"h-4 w-4"})}),h&&!C&&U&&r&&c&&e.jsx(en,{}),!C&&U&&r&&c&&e.jsx(sn,{}),h&&!C&&U&&u&&r&&c&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:x,onClick:ge,size:"sm",children:[e.jsx(qe,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),h&&!C&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!h,onClick:()=>$(),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Visual"]}),!C&&!h&&o.canEdit&&c&&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"]}),h&&!C&&c&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{M(!1),L(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),Z&&c&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"outline",disabled:X,onClick:he,size:"sm",children:[X?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(qe,{className:"mr-2 h-4 w-4"}),X?"Saving...":"Save"]}),!T&&!C&&h&&o.canUseFilters&&c&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>w(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!C&&h&&r&&c&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>L(!B),size:"sm",variant:"ghost",children:e.jsx($e,{className:"h-4 w-4"})})}),!C&&r&&e.jsx(Qa,{}),b&&W&&e.jsx(hs,{resource:W,resourceType:s.ResourceType.DASHBOARD,onClose:()=>p(!1)}),e.jsx(On,{open:j,onOpenChange:f})]})]})}function Hn({name:t,items:n,value:a,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:d,showNone:u=!1}){const m=Re.useRef(null),[h,x]=Re.useState(!1),[g,b]=Re.useState("100%"),p=u?[...n||[],{id:"none",name:"None"}]:n;Re.useLayoutEffect(()=>{m.current&&b(m.current.offsetWidth)},[]);function j(){var y;return l?"Loading...":o?"Error":a?(y=n==null?void 0:n.find(E=>E.id===a))==null?void 0:y.name:`Select ${t}`}function f(y,E){r(E),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(rt,{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(y=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:y.name,onSelect:E=>f(E,y.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",a===y.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:y.name,children:y.name})]})},y.id))})]})]})})]})}function Ge({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(Va,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Ba,{className:"size-4"});if(t==="Table")return e.jsx(s.Table2,{className:"size-4"});if(t==="Model")return e.jsx(xa,{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(rt,{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(Hn,{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 Wn({column:t}){const[n,a]=A.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 D;const f=s.createSqlGenConfig(p,i,j),y=(D=d==null?void 0:d.find(C=>C.id===c))==null?void 0:D.name;m(f);const E=s.getSql(f,s.fmt(l||""),s.fmt(r),y||"",u,o||"");E&&(h(E),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 Kn({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(Se,{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(Ie,{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(Pe,{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($e,{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(Xe,{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(ss,{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(Se,{className:"h-3 w-3"})})}function gs({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(Kn,{dataType:t.data_type}),e.jsx("span",{children:t.column_name})]})}function Qn({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 Jn({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(gs,{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(gs,{column:n})}),e.jsx(Qn,{id:n.column_name,type:"column",children:e.jsx(gs,{column:n})})]})}const js={id:"__placeholder__",role:"groupby",type:"string"},bs={id:"__placeholder__",role:"groupby",type:"string"},vs={id:"__placeholder__",role:"metric",type:"number"},ys={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},Tt={id:"__placeholder__"},Oe="droppable-group-by",Fe="droppable-metrics",Be="droppable-pivot-by",ds="sortable-group-by",Ts="sortable-metrics",us="sortable-pivot-by",ks="droppable-filters",Es="sortable-filters",Ms="sortable-order-by";function Xn(){const t=s.useDndStore(w=>w.insertIndex),n=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.groupByColumns)||[]}),a=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.metricColumns)||[]}),r=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.filterColumns)||[]}),l=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.orderBy)||[]}),o=s.useEditorStore(w=>{var M;return((M=w.card.queryConfig)==null?void 0:M.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:y}=s.useEditorAside(),E=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),D=w=>{var O;const{active:M,over:L}=w;if(((O=M.data.current)==null?void 0:O.type)==="column"&&L){const R=L.id,z=f.find(W=>W.column_name===M.id);if(!z)return;const G=s.isNumberDataType(z.data_type),Q=s.isTextDataType(z.data_type),_=s.isDateDataType(z.data_type);if(Q||_){if(n.some($=>$.id===R)){const $=n.findIndex(Y=>Y.id===R);c($);const X=n.filter(Y=>Y.id!==js.id);X.splice($,0,js),d(X)}else if(L.id===Oe){c(n.length);const $=[...n,js];d($),u(a),m(r)}}if(Q||_){if(o.some($=>$.id===R)){const $=o.findIndex(Y=>Y.id===R);c($);const X=o.filter(Y=>Y.id!==bs.id);X.splice($,0,bs),h(X)}else if(L.id===Be){c(o.length);const $=[...o,bs];h($),d(n),u(a),m(r)}}if(G||Q){if(a.some($=>$.id===R)){console.log("isOverMetricSortable",R);const $=a.findIndex(Y=>Y.id===R);c($);const X=a.filter(Y=>Y.id!==vs.id);X.splice($,0,vs),u(X)}else if(L.id===Fe){c(a.length);const $=[...a,vs];u($),m(r),d(n),h(o)}}if(S(z)){if(r.some($=>$.id===R)){const $=r.findIndex(Y=>Y.id===R);c($);const X=r.filter(Y=>Y.id!==ys.id);X.splice($,0,ys),m(X)}else if(L.id===ks){c(r.length);const $=[...r,ys];m($),u(a),d(n),h(o)}}}else d(n),u(a),m(r),h(o)};function C(w){i(w.active.id),c(null),d(n),u(a),m(r),h(o)}function S(w){return!r.some(M=>M.name===w.column_name)}function v(w,M="SUM"){const{column_name:L,data_type:O}=w,R=[...a],z=t!==null?t:a.length,G={...w,id:De(L),name:L,label:es(L,M),type:O,role:"metric",aggregate:M};R.splice(z,0,G),g(R)}function k(w){const M=s.isTextDataType(w.data_type);s.isDateDataType(w.data_type);const L=[...o],O=t!==null?t:o.length;let R;M?R={...w,id:De(w.column_name),name:w.column_name,type:w.data_type,role:"groupby"}:R={...w,id:De(w.column_name),name:w.column_name,type:w.data_type,role:"groupby",label:We(w.column_name,"month"),granularity:"month"},L.splice(O,0,R),j(L)}function N(w){const M=s.isTextDataType(w.data_type);s.isDateDataType(w.data_type);const L=[...n],O=t!==null?t:n.length;let R;M?R={...w,id:De(w.column_name),name:w.column_name,type:w.data_type,role:"groupby"}:R={...w,id:De(w.column_name),name:w.column_name,type:w.data_type,role:"groupby",label:We(w.column_name,"month"),granularity:"month"},L.splice(O,0,R),x(L)}function F(w){const M=[...r],L=t!==null?t:r.length,O={...w,id:De(w.column_name),name:w.column_name,type:w.data_type,sql:s.getDefaultFilterSql(w.data_type,y,s.fmt(w.column_name)),role:"filter"};M.splice(L,0,O),b(M)}function T(w){var R,z,G,Q,_,W,$,X;const{active:M,over:L}=w,O=M.data.current;if((O==null?void 0:O.type)==="column"&&L){const Y=f.find(ne=>ne.column_name===M.id);if(!Y)return;const K=s.isNumberDataType(Y.data_type),U=s.isTextDataType(Y.data_type),Z=s.isDateDataType(Y.data_type);(U||Z)&&(L.id===Oe||((R=L.data.current)==null?void 0:R.type)===ds)&&N(Y),(U||Z)&&(L.id===Be||((z=L.data.current)==null?void 0:z.type)===us)?k(Y):(K||U)&&(L.id===Fe||((G=L.data.current)==null?void 0:G.type)===Ts)?(K&&v(Y),U&&v(Y,"COUNT")):S(Y)&&(L.id===ks||((Q=L.data.current)==null?void 0:Q.type)===Es)&&F(Y)}if(L&&((_=L.data.current)==null?void 0:_.type)===ds&&n.some(Y=>Y.id===M.id)){const Y=n.findIndex(U=>U.id===M.id),K=n.findIndex(U=>U.id===L.id);if(Y!==-1&&K!==-1&&Y!==K){const U=[...n],[Z]=U.splice(Y,1);U.splice(K,0,Z),x(U)}}if(L&&((W=L.data.current)==null?void 0:W.type)===us&&o.some(Y=>Y.id===M.id)){const Y=o.findIndex(U=>U.id===M.id),K=o.findIndex(U=>U.id===L.id);if(Y!==-1&&K!==-1&&Y!==K){const U=[...o],[Z]=U.splice(Y,1);U.splice(K,0,Z),j(U)}}if(L&&(($=L.data.current)==null?void 0:$.type)===Ts&&a.some(Y=>Y.id===M.id)){const Y=a.findIndex(U=>U.id===M.id),K=a.findIndex(U=>U.id===L.id);if(Y!==-1&&K!==-1&&Y!==K){const U=[...a],[Z]=U.splice(Y,1);U.splice(K,0,Z),g(U)}}if(L&&((X=L.data.current)==null?void 0:X.type)===Es&&r.some(Y=>Y.id===M.id)){const Y=r.findIndex(U=>U.id===M.id),K=r.findIndex(U=>U.id===L.id);if(Y!==-1&&K!==-1&&Y!==K){const U=[...r],[Z]=U.splice(Y,1);U.splice(K,0,Z),b(U)}}B(w),i(null),c(null),d(n),u(a),m(r),h(o)}function B(w){const{active:M,over:L}=w,O=M.data.current;if((O==null?void 0:O.type)===Ms&&L){const R=l.findIndex(G=>Je(G.columnId)===M.id),z=l.findIndex(G=>Je(G.columnId)===L.id);if(R!==-1&&z!==-1&&R!==z){const G=[...l],[Q]=G.splice(R,1);G.splice(z,0,Q),p(G)}}}function I(){i(null),c(null),d(n),u(a),m(r)}return{handleDragOver:D,handleDragEnd:T,handleDragStart:C,handleDragCancel:I,sensors:E}}function De(t){return`${t}-${s.v4()}`}function es(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 Je(t){return`${Ms}-${t}`}function We(t,n){const a=s.toTitleCase(t.replace(/_/g," "));switch(n){case"day":return`Date of ${a}`;case"week":return`Week of ${a}`;case"month":return`Month of ${a}`;case"year":return`Year of ${a}`;default:return a}}function 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(Se,{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(Ie,{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(Pe,{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($e,{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(Xe,{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(ss,{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(Se,{className:"h-3 w-3"})})}function er({schemaName:t,tableName:n,columns:a,status:r}){const[l,o]=A.useState(""),[c,i]=A.useState("all"),d=s.useEditorStore(R=>R.sqlGen),u=s.useEditorStore(R=>R.isDevMode);s.useEditorStore(R=>R.selectedConnectionId);const m=s.useEditorStore(R=>{var z,G;return(G=(z=R.card)==null?void 0:z.queryConfig)==null?void 0:G.metricColumns});s.useEditorStore(R=>{var z,G;return(G=(z=R.card)==null?void 0:z.queryConfig)==null?void 0:G.groupByColumns});const h=s.useEditorStore(R=>R.selectedDatabaseName);s.useEditorStore(R=>R.selectedSchemaName),s.useEditorStore(R=>R.selectedTableName);const x=s.useEditorStore(R=>R.selectedDatamodelId);s.useDashboardStore(R=>R.dashboard.aiScopeTables);const{addToAIScope:g,removeFromAIScope:b}=s.useDashboardActions(),{addColumnToMetricColumns:p,addColumnToGroupBy:j,setCardSql:f,setRunSql:y,setSqlGen:E,setIsShowingVisual:D}=s.useEditorActions(),{connectionType:C,modelItems:S,selectedDatamodelName:v}=s.useEditorAside();function k(R){var z;if(u){const G=s.createSqlGenConfig(R,d);E(G);const Q=(z=S==null?void 0:S.find(W=>W.id===x))==null?void 0:z.name,_=s.getSql(G,s.fmt(t),s.fmt(n),Q||"",C,h||"");_&&(f(_),y(!0))}if(!u){if(s.isTextDataType(R.data_type))if(m&&m.length>0){const G={...R,role:"groupby",id:De(R.column_name),name:R.column_name,type:R.data_type};j(G)}else{const G={...R,role:"metric",id:De(R.column_name),name:R.column_name,label:es(R.column_name,"COUNT"),type:R.data_type,aggregate:"COUNT"};p(G)}if(s.isDateDataType(R.data_type)){const G={...R,role:"groupby",id:De(R.column_name),name:R.column_name,type:R.data_type,label:We(R.column_name,"month"),granularity:"month"};j(G)}if(s.isNumberDataType(R.data_type)){const G={...R,role:"metric",id:De(R.column_name),name:R.column_name,label:es(R.column_name,"SUM"),type:R.data_type,aggregate:"SUM"};p(G)}}}function N(){const R=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:C,databaseName:h||""});D(!1);const z=C==="MSSQL"?`SELECT top 10 * FROM ${R}`:`SELECT * FROM ${R} LIMIT 10`;f(z),y(!0)}function F(){const R=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:C,databaseName:h||""});f(`SELECT COUNT(*) as count FROM ${R}`),y(!0)}const T=(a==null?void 0:a.filter(R=>R.column_name.toLowerCase().includes(l.toLowerCase())))||[],B=R=>s.isNumberDataType(R.data_type)?"number":"text",I=c==="all"?T:T.filter(R=>B(R)===c),w=T.filter(R=>B(R)==="text").length,M=T.filter(R=>B(R)==="number").length;function L(R){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(R),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zn,{dataType:R.data_type}),e.jsx("span",{children:R.column_name})]}),e.jsx("div",{onClick:z=>z.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(R.data_type)&&e.jsx(Wn,{column:R})})]}):e.jsx(Jn,{onClick:k,column:R})}function O(){return e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:r!=="Success",onClick:N,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(La,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:F,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(lt,{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((R,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:O()}),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:R=>o(R.target.value)})]}),T.length>0&&e.jsx(s.Tabs,{defaultValue:"all",value:c,onValueChange:R=>i(R),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:T.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:w})]}),e.jsxs(s.TabsTrigger,{value:"number",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:M})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-4 pt-3",children:[I.length===0&&l&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',l,'"']}),I.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:I==null?void 0:I.map(R=>e.jsx("div",{children:L(R)},R.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function kt({ColumnsComponent:t,type:n}){var H;const[a,r]=A.useState(!1),{isConsoleMode:l}=s.useDashboardPreferences(),o=s.useEditorStore(P=>P.card),c=s.useEditorStore(P=>P.selectedConnectionId),i=s.useDashboardStore(P=>P.showFilters),d=s.useEditorStore(P=>P.selectedDatamodelId),u=s.useEditorStore(P=>P.selectedDatabaseName),m=s.useEditorStore(P=>P.selectedSchemaName),h=s.useEditorStore(P=>P.selectedTableName);s.useEditorStore(P=>P.isDevMode);const{setSelectedTableName:x,setIsDevMode:g,setCardSql:b}=s.useEditorActions(),{connectionItems:p,modelItems:j,schemaItems:f,databaseItems:y,tableItems:E,columns:D,isConnectionsLoading:C,isModelsLoading:S,isConnectionsError:v,isModelsError:k,isDatabasesLoadingOrFetching:N,isDatabaseError:F,isSchemaLoadingOrFetching:T,isSchemaError:B,isColumnsError:I,isColumnsLoadingOrFetching:w,isTableLoadingOrFetching:M,isTableError:L,connectionType:O,isNonDbConnection:R,refetchDatabases:z,refetchModels:G,refetchSchemas:Q,refetchTables:_,refetchColumns:W,refetchConnections:$,handleConnectionChange:X,handleDatabaseChange:Y,handleSchemaChange:K,handleDatamodelChange:U,handleTableChange:Z,tableName:ne,schemaName:he}=s.useEditorAside(),{data:ge,refetch:V}=s.useDashboardCardQuery(o);function se(){return t?t(he,ne,D):e.jsx(er,{schemaName:he,tableName:ne,columns:D,status:w?"Loading...":I?"Error":"Success"})}function te(){if(!c||O==="S3"||O==="API")return null;if(!d||d==="none")return e.jsx(Ge,{refetch:z,showNone:!0,onChange:Y,isError:F,isLoading:N,items:y,value:u||"",title:"Database",type:"combobox"})}function re(){if(c&&!R&&(!u||u==="none")&&(!d||d==="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 ie(){if(!c||O==="S3"||O==="API")return null;if(!u||u==="none")return e.jsx(Ge,{refetch:G,showNone:!0,onChange:U,isError:k,isLoading:S,items:j,value:d||"",title:"Model",type:"combobox"})}function de(){return!c||O==="S3"||O==="API"||!u||u==="none"?null:e.jsx(Ge,{refetch:Q,onChange:K,isError:B,isLoading:T,items:f,value:m||"",title:"Schema",type:"combobox"})}function xe(){function P(){let J=!1;return O==="API"?(J=!1,J):((O==="S3"||c&&u&&u!=="none"&&m)&&(J=!0),J)}return P()?e.jsx(Ge,{refetch:_,onChange:Z,isError:L,items:E,isLoading:M,value:h||"",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]":!i}),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(Ge,{refetch:$,items:p,title:"Connection",value:c||"",onChange:X,isLoading:C,isError:v,type:"combobox",connectionTooltip:((H=p==null?void 0:p.find(P=>P.id===c))==null?void 0:H.type)||""}),te(),re(),ie(),de(),xe()]})]}),se(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:n==="main"&&l&&e.jsx(e.Fragment,{})})]})}function Et({error:t,errorSql:n,onSendFeedback:a,className:r,showFeedbackButton:l=!0}){const[o,c]=A.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(s.MessageSquareWarning,{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 It({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(Et,{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(Na,{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(ka,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function At({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(ga,{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(It,{errorSql:a,sql:t,error:n,onDebugWithAssistant:r})})]})}function sr(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 Mt(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=A.useRef(),h=A.useRef({}),x=r.cards.find(p=>p.id===o),g=A.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]);A.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]),A.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]),A.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(),y=g();h.current[l.id]=f||(j==null?void 0:j.editor.createModel(y,t))||p.getModel()}p.setModel(h.current[l.id])}return{handleEditorDidMount:b}}function tr(){const t=s.useEditorStore(c=>c.card.sql),n=s.useEditorStore(c=>c.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=Mt("sql");function o(c){a(c),s.isObjectEmpty(n)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:o,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function ar(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=Mt("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 nr({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 rr(){const t=s.useQueryClient(),{isConsoleMode:n}=s.useDashboardPreferences(),[a,r]=A.useState(!1),[l,o]=A.useState(!1);s.useEditorStore(_=>_.frame);const c=s.useEditorStore(_=>_.card);s.useEditorStore(_=>_.isShowingVisual),s.useEditorStore(_=>_.selectedConnectionId),s.useEditorStore(_=>_.tempQueryData),s.useEditorStore(_=>_.selectedDatabaseName),s.useEditorStore(_=>_.selectedDatamodelId),s.useEditorStore(_=>_.selectedSchemaName);const i=s.useEditorStore(_=>_.showAIDialog);s.useEditorStore(_=>_.selectedTableName);const d=s.useEditorStore(_=>{var W;return(W=_==null?void 0:_.card)==null?void 0:W.sql}),u=s.useEditorStore(_=>{var W;return(W=_==null?void 0:_.card)==null?void 0:W.python}),{cardFilterValues:m}=s.useCardFilterValues((c==null?void 0:c.id)??""),{setCardCustomCfg:h,setQueryResultColumns:x,setCardSql:g,setTempQueryData:b,setPythonStdOut:p,setCardPreferences:j,setCardType:f,setCardPython:y,runAssistant:E,setShowAIDialog:D}=s.useEditorActions();s.useEditorStore(_=>_.onSave),s.useEditorStore(_=>_.onClose),s.useEditorStore(_=>_.actions.setSqlGen);const C=s.useEditorStore(_=>_.runSql),S=s.useEditorStore(_=>_.actions.setRunSql),v=s.useEditorStore(_=>_.actions.setIsSqlRunning),{data:k,isLoading:N,isFetching:F,isSuccess:T,isError:B,error:I,errorSql:w,queryKey:M,refetch:L,errorMessage:O}=s.useDashboardCardQuery(c);A.useEffect(()=>{if(k&&(k.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),p((k==null?void 0:k.output)||""),k.records.length>0)){const{dimensionKeys:_}=s.getKeys(k.records);x(_)}},[k,x,p]),A.useEffect(()=>{(N||F)&&v(!0),(B||T)&&v(!1),B&&(x([]),p(""))},[N,F,k,p,B,T,v,x,I]),A.useEffect(()=>{C&&(t.getQueryData(M)||L(),S(!1))},[C,L,S,M,t]);async function R(){const _=`Can you help me debug this query?
|
|
312
312
|
|
|
313
313
|
Error:
|
|
314
314
|
|