react-semaphor 0.0.634 → 0.0.635
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-DtpE16QT.js → dashboard-plus-CyO19WYF.js} +103 -103
- package/dist/chunks/{dashboard-plus-Bxu_iTCc.js → dashboard-plus-DOywPQer.js} +2 -2
- package/dist/chunks/{index-CnqxbwDX.js → index-BIeRd2Q5.js} +1051 -1016
- package/dist/chunks/{index-285H1_10.js → index-Bh16H61W.js} +58 -58
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +3 -3
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";const e=require("react/jsx-runtime"),s=require("./index-
|
|
1
|
+
"use strict";const e=require("react/jsx-runtime"),s=require("./index-Bh16H61W.js"),A=require("react");require("react-dom");function ea(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 Ie=ea(A);/**
|
|
2
2
|
* @license lucide-react v0.453.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -328,7 +328,7 @@
|
|
|
328
328
|
*
|
|
329
329
|
* This source code is licensed under the ISC license.
|
|
330
330
|
* See the LICENSE file in the root directory of this source tree.
|
|
331
|
-
*/const Ha=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 Wa(){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(Ya,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(La,{strokeWidth:1.5,className:"absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),e.jsx("span",{className:"sr-only",children:"Toggle theme"})]})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuItem,{onClick:()=>{t("light"),n("light")},children:"Light"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("dark"),n("dark")},children:"Dark"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("system"),n("system")},children:"System"})]})]})}function ss(t){var n;return{...t,sheets:(n=t==null?void 0:t.sheets)==null?void 0:n.map(a=>{var r;return{...a,frames:(r=a.frames)==null?void 0:r.map(o=>{var l;return{...o,cards:(l=o.cards)==null?void 0:l.map(c=>lt(c))}})}})}}function lt(t){return{...t,customCfg:Ka(t.customCfg),data:[]}}function Ka(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 Qa(t,n,a,r){if(!r)return null;const o=JSON.stringify(n);return await s.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:t,template:o,filterValues:a,operation:"create"})}async function vs(t,n){if(!n)return null;const{id:a,template:r,filterValues:o,isDefault:l,shared:c}=t;return await s.postRequest("https://semaphor.cloud/api/v1/lens",n,{lensId:a,template:r,filterValues:o,isDefault:l,shared:c,operation:"update"})}async function Ja(t,n){return n?await s.postRequest("https://semaphor.cloud/api/v1/lens",n,{operation:"delete",lensId:t}):null}function Xa(){const[t,n]=A.useState(""),[a,r]=A.useState(!1),o=s.useDashboardStore(x=>x.lenses),{setLenses:l,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=A.useState(!1),[u,m]=A.useState(!1),h=s.useDashboardStore(x=>x.dashboard),p=s.useDashboardStore(x=>x.filterValues),{authToken:g}=s.useSemaphorContext();async function j(){d(!0);const x=ss(h),b=await Qa(t,x,p,g==null?void 0:g.accessToken);b&&(l([...o||[],b]),c(b.id),m(!1)),d(!1)}return e.jsxs(s.Dialog,{open:u,onOpenChange:m,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange:x=>{n(x.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:j,disabled:i,children:i?"Creating...":"Add"})})]})]})}function Za(){const[t,n]=A.useState(!1),a=s.useDashboardStore(m=>m.lenses),r=s.useDashboardStore(m=>m.selectedLensId),{setLenses:o,setSelectedLensId:l}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function i(m){l(m)}async function d(m){if(await Ja(m,c==null?void 0:c.accessToken)){const p=a==null?void 0:a.filter(g=>g.id!==m);o(p||[]),l("original")}}async function u(m){const h=a==null?void 0:a.map(j=>j.id===m.id?{...j,isDefault:!m.isDefault}:{...j,isDefault:!1});o(h||[]);const p={...m,isDefault:!m.isDefault};await vs(p,c==null?void 0:c.accessToken);const g=a==null?void 0:a.find(j=>j.isDefault);if(g&&g.id!==m.id){const j={...g,isDefault:!1};await vs(j,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(ya,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:i,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),a==null?void 0:a.map(m=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:m.id,children:[e.jsx("p",{children:m.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:h=>{h.preventDefault(),u(m)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!m.isDefault,"text-green-500":m.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:h=>{h.preventDefault(),d(m.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},m.id))]})]})]})}function en({iconClassName:t}){const[n,a]=A.useState(!1),[r,o]=A.useState(""),[l,c]=A.useState(!1),i=s.useDashboardStore(m=>m.isDownloadingPdf);async function d(){const m=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(),s.ue.dismiss(m),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(h){s.ue.dismiss(m),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",h)}}async function u(){if(!r)return;a(!1),o(""),c(!1);const m=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(r),s.ue.dismiss(m),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(h){s.ue.dismiss(m),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",h)}}return e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:i,children:e.jsx(s.Download,{className:s.cn("size-4",t)})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsxs(s.DropdownMenuItem,{onClick:d,children:[e.jsx(s.File,{className:"mr-2 h-4 w-4"}),"Download PDF"]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>a(!0),children:[e.jsx(Ta,{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:l?"text":"password",value:r,onChange:m=>o(m.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:m=>{m.key==="Enter"&&r&&u()}}),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(!l),children:l?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:u,disabled:!r,children:"Download"})]})]})})]})}function ot({triggerButtonClassName:t}){const[n,a]=A.useState(!1),[r,o]=A.useState("create"),[l,c]=A.useState("current"),i=s.useDashboardStore(S=>{var C;return(C=S.dashboard)==null?void 0:C.sheets}),d=s.useDashboardStore(S=>S.selectedSheetId),u=i==null?void 0:i.find(S=>S.id===d),m=i&&i.length>1,{schedules:h,isLoading:p,createSchedule:g,deleteSchedule:j,isSubmitting:x,submitError:b,deletingId:f,refetch:N}=s.useSchedule({reportType:"DASHBOARD",enabled:n}),k=async S=>{try{const C={format:"pdf",sheetSelection:l,pdfOptions:{pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0}};l==="current"&&u&&(C.currentSheetId=u.id,C.currentSheetName=u.title),await g({...S,reportParams:C}),o("active")}catch(C){console.error("Failed to create schedule:",C)}},I=async S=>{try{await j(S)}catch(C){console.error("Failed to delete schedule:",C)}};return e.jsxs(s.Popover,{open:n,onOpenChange:a,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),children:e.jsx(s.Clock,{className:"size-4"})})}),e.jsx(s.PopoverContent,{align:"end",className:"w-[520px] p-0",children:e.jsxs(s.Tabs,{value:r,onValueChange:S=>o(S),className:"w-full",children:[e.jsxs("div",{className:"border-b px-6 pb-3 pt-6",children:[e.jsxs("div",{className:"mb-4 space-y-1",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Dashboard"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage your dashboard and report schedules"})]}),e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsxs(s.TabsTrigger,{value:"create",className:"flex items-center gap-2",children:[e.jsx(s.Plus,{className:"h-4 w-4"}),"Create Schedule"]}),e.jsxs(s.TabsTrigger,{value:"active",className:"flex items-center gap-2",children:[e.jsx(tt,{className:"h-4 w-4"}),"Active Schedules",h&&h.length>0&&e.jsx(s.Badge,{variant:"secondary",className:"ml-1 h-5 px-1",children:h.length})]})]})]}),e.jsxs(s.TabsContent,{value:"create",className:"mt-0 max-h-[60vh] overflow-y-auto p-6",children:[m&&e.jsxs("div",{className:"mb-6 space-y-2",children:[e.jsx(s.Label,{children:"Sheet Selection"}),e.jsxs(s.RadioGroup,{value:l,onValueChange:S=>c(S),className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"current",id:"current-sheet"}),e.jsxs(s.Label,{htmlFor:"current-sheet",className:"flex cursor-pointer items-center font-normal",children:[e.jsx(s.FileText,{className:"mr-2 h-4 w-4"}),"Current sheet (",(u==null?void 0:u.title)||"Sheet",")"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"all",id:"all-sheets"}),e.jsxs(s.Label,{htmlFor:"all-sheets",className:"flex cursor-pointer items-center font-normal",children:[e.jsx(s.Files,{className:"mr-2 h-4 w-4"}),"All sheets (",i==null?void 0:i.length," sheets)"]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l==="current"?"Only the currently selected sheet will be included in the report":"All sheets in the dashboard will be included in the report"})]}),e.jsx(s.ScheduleForm,{reportType:"DASHBOARD",onSubmit:k,isSubmitting:x,submitError:b})]}),e.jsx(s.TabsContent,{value:"active",className:"mt-0 max-h-[60vh] overflow-y-auto p-6",children:h&&h.length>0?e.jsx(s.ScheduleManager,{schedules:h,onDelete:I,isDeleting:f,isLoading:p,onRefresh:N}):e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(s.Clock,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:"No active schedules"}),e.jsx("p",{className:"mt-1 text-xs",children:'Switch to the "Create Schedule" tab to add your first subscription'})]})})]})})]})}function it(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,n)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},n))})]})})}function sn({visual:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:o=!1,onAddVisual:l,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:u,onShareVisual:m,formatDate:h}){var C,v,T;const{selectVisual:p}=s.useManagementActions(),g=s.useIsVisualSelected(t.id),{isConsoleMode:j}=s.useDashboardPreferences(),x=s.useDashboardStore(y=>y.actions.setIsDashboardPanelOpen),[b,f]=A.useState(!1),[N,k]=A.useState(!1);A.useEffect(()=>{a?(f(!0),k(!0)):N&&(f(!1),k(!1))},[a,N]);const I=()=>e.jsx(rs,{className:"h-4 w-4"}),S=()=>{p(t),c==null||c(t)};return e.jsx(s.Card,{className:s.cn("group p-3 hover:bg-accent/50 transition-colors cursor-pointer border-border/50",g&&"ring-1 ring-primary"),onClick:S,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 p-1.5 rounded bg-muted",children:I()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-foreground",value:t.title,onSave:y=>i==null?void 0:i(t.id,{title:y}),isEditable:t.ownership.isOwner&&g,isPending:r,placeholder:"Untitled Visual",displayClassName:"font-medium text-sm text-foreground truncate"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"h-2.5 w-2.5 mr-1"}),"Shared"]})]}),e.jsx(s.EditableText,{inputClassName:"text-xs text-muted-foreground line-clamp-2",value:t.description||"",onSave:y=>i==null?void 0:i(t.id,{description:y}),isEditable:t.ownership.isOwner&&g,isPending:o,placeholder:"No description",displayClassName:"text-xs text-muted-foreground line-clamp-2 mb-2"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsxs("span",{children:["Updated ",h(t.lastModified)]})]})]}),e.jsxs("div",{className:s.cn("opacity-0 transition-opacity duration-150 group-hover:opacity-100","ml-2 flex-shrink-0 flex items-center gap-1"),onClick:y=>y.stopPropagation(),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:y=>{y.stopPropagation(),l(t)},title:"Add to dashboard",children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:b,onOpenChange:f,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),l(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.preventDefault(),y.stopPropagation(),u(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),c==null||c(t)},children:[e.jsx(Fa,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),m(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),d(t),x(!1)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((C=t.ownership.createdBy)==null?void 0:C.type)==="tenant"||((v=t.ownership.createdBy)==null?void 0:v.type)==="organization"&&j)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((T=t.ownership.createdBy)==null?void 0:T.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:h(t.lastModified)})]})]})]})]})]})]})},t.id)}function ts({value:t,onChange:n,placeholder:a="Search users by name, email, or department..."}){return e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:a,value:t,onChange:r=>n(r.target.value),className:"pl-9"})]})}function Oe({currentRole:t,onRoleChange:n,roleOptions:a,disabled:r=!1,className:o="",allowDropdown:l=!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 l?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${o}`,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 ${o}`,children:c})}function ct({selectedUsers:t,selectedUserObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:o}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(l=>a(l.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.map(l=>{const c=t.find(d=>d.id===l.id),i=o(l.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[l.name,e.jsx(Oe,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(l.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>a(l.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},l.id)})}),e.jsx(s.Separator,{})]})}function dt({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 ut({usersToUpdate:t,allUsers:n,onRemove:a,getRoleOptions:r}){if(t.length===0)return null;const o=r("tenant"),l=i=>{const d=n.find(u=>u.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=o.find(u=>u.value===i);return(d==null?void 0:d.label)||i};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(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:l(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>a(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function mt(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,o=A.useRef(null);return A.useEffect(()=>{const l=c=>{const i=c.target;o.current&&o.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,l),()=>{document.removeEventListener(r,l)}},[t,a,r]),o}function ye(t,n){var a;return((a=n.find(r=>r.value===t))==null?void 0:a.label)||t}function tn(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function ht(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function an(t,n,a){const r=ht(t),o=(a==null?void 0:a.type)||"organization";if(!(!n||!n.shares))if(o==="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 nn({user:t}){return ht(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 rn({user:t,userShare:n,usersToUpdate:a,currentUser:r,getRoleOptions:o,handleUpdateAccess:l}){if(!(n!=null&&n.role))return null;const c=tn((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=o(t.type);return n?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(Oe,{currentRole:u,onRoleChange:h=>{l(t.id,n.role,h)},roleOptions:m,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:ye(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function ln({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(ze,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function on({isUserRemoving:t,isSelected:n,hasAccess:a,isRemoving:r,isSharing:o}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),n&&!a&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:o?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Sharing..."]}):"Will share"})]})}function cn({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((p,g)=>{var f,N;const j=((f=n.find(k=>k.id===p.orgUserId))==null?void 0:f.name)||"Unknown User",x=((N=n.find(k=>k.id===p.orgUserId))==null?void 0:N.type)||"",b=ye(p.role,a(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:j}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},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((p,g)=>{var f,N;const j=((f=n.find(k=>k.id===p.tenantUserId))==null?void 0:f.name)||"Unknown User",x=((N=n.find(k=>k.id===p.tenantUserId))==null?void 0:N.type)||"",b=ye(p.role,a(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:j}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},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((p,g)=>{const j=ye(p.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:j})]},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((p,g)=>{const j=ye(p.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:j})]},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((p,g)=>{const j=ye(p.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:j})]},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,j;const m=((g=n.find(x=>x.id===d.tenantUserId))==null?void 0:g.name)||"Unknown User",h=((j=n.find(x=>x.id===d.tenantUserId))==null?void 0:j.type)||"",p=ye(d.role,a(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:p})]},u)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:i.map((d,u)=>{const m=ye(d.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},u)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const l=t.shares.specificTenantUsers||[],c=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[l.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",l.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[l.slice(0,3).map((i,d)=>{var p,g;const u=((p=n.find(j=>j.id===i.tenantUserId))==null?void 0:p.name)||"Unknown User",m=((g=n.find(j=>j.id===i.tenantUserId))==null?void 0:g.type)||"",h=ye(i.role,a(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),l.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",l.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,d)=>{const u=ye(i.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},d)})})]}),!l.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function dn({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 un({user:t,userShare:n,isUserRemoving:a,hasAccess:r,hasAccessFromAPI:o,isSelected:l,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:h,handleUpdateAccess:p,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":l?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:o?!a:l,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{o?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(nn,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!a?e.jsx(Oe,{currentRole:n==null?void 0:n.role,onRoleChange:j=>p(t.id,n.role,j),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(rn,{user:t,userShare:n,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:p}),l&&!o&&e.jsx("div",{onClick:j=>j.stopPropagation(),children:e.jsx(Oe,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:j=>g(t.id,j),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(ln,{hasAccess:r,isUserRemoving:a,isSelected:l,hasAccessFromAPI:o}),e.jsx(on,{isUserRemoving:a,isSelected:l,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function xt({existingShares:t,isInitialLoading:n,isSearching:a,getRoleOptions:r,allUsers:o=[],currentUser:l,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),g=s.useShareSearchQuery(),j=s.useShareManagementActions(),x=c||(S=>{const C=m.some(T=>T.id===S),v=h.includes(S);C?j.removeSelectedUser(S):v?j.removeUserFromRemove(S):j.addSelectedUser({id:S,role:"VIEWER"})}),b=i||j.updateSelectedUserRole,f=d||j.addUserToRemove,N=u||((S,C,v)=>{j.addUserToUpdate({id:S,currentRole:C,newRole:v})}),k=o,I=h;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["All Users (",(k??[]).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(cn,{existingShares:t,allUsers:o,getRoleOptions:r,currentUser:l})})]})})]}),(k==null?void 0:k.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===k.length?j.setSelectedUsers([]):j.setSelectedUsers(k.map(S=>({id:S.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:m.length===k.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(dn,{isInitialLoading:n,isSearching:a,searchQuery:g,availableUsers:k||[]}),!n&&!a&&(k==null?void 0:k.length)>0&&k.map(S=>{const C=t?an(S,t,l):void 0,v=I.includes(S.id),T=!!C,y=T&&!v,O=m.some(w=>w.id===S.id),E=m.find(w=>w.id===S.id),B=r(S.type);return e.jsx(un,{user:S,userShare:C,isUserRemoving:v,hasAccess:y,hasAccessFromAPI:T,isSelected:O,selectedUser:E,roleOptions:B,currentUser:l,usersToUpdate:p,handleUserToggle:x,handleRemoveAccess:f,handleUpdateAccess:N,handleUserRoleChange:b},S.id)})]})]})}function Ss({shareType:t,onShareTypeChange:n,currentUser:a,options:r}){const o=(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(l=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:l.value,id:l.value,className:"peer sr-only",disabled:l.disabled}),e.jsxs(s.Label,{htmlFor:l.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${l.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[l.icon||e.jsx(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:l.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l.description})]})]})]},l.value))}),!o&&r.some(l=>l.value==="all_users")&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only admins, authors, power users, and super admins can share with all users."})]})}const be=()=>[{value:"VIEWER",label:"Viewer",description:"Can view only"},{value:"EDITOR",label:"Editor",description:"Can view and edit"},{value:"CONTRIBUTOR",label:"Contributor",description:"Can view, edit, and share"},{value:"OWNER",label:"Owner",description:"Full access (view, edit, share, delete)"}];function mn({currentUser:t,currentShare:n,isSharing:a,onUpdateAccess:r,allUsersToUpdate:o=null,allUsersToRemove:l=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),u=be().filter(N=>N.value==="VIEWER"||N.value==="EDITOR"||N.value==="CONTRIBUTOR"),m=n.role!=="NONE"?n.role:"NONE",h=o?o.newRole:m,p=n.role!=="NONE"&&!l&&(!o||o.newRole===m),g=o!==null&&o.newRole!==m,j=l,x=m==="NONE"||!m,b=N=>{switch(N){case"VIEWER":return e.jsx(s.Eye,{className:"h-4 w-4"});case"EDITOR":return e.jsx(s.SquarePen,{className:"h-4 w-4"});case"CONTRIBUTOR":return e.jsx(za,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},f=N=>{r(m,N)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",g&&!j&&!x?"border-orange-300 bg-orange-50":p?"border-green-300 bg-green-50":j||x?"border-destructive bg-destructive/10":""),children:[e.jsxs(s.CardHeader,{children:[e.jsxs(s.CardTitle,{className:"flex items-center gap-2 text-base",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Share with All"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="specificOrgUsers"?"Org":"Tenant"," ","Users",p&&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"}),(j||x)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:j||x?"No access for all users.":"This will share the dashboard with all users in your "+((t==null?void 0:t.type)==="organization"?"organization":"tenant")+". Select an access level below."})]}),e.jsx(s.CardContent,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Select Access Level:"}),e.jsxs(s.HoverCard,{children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-4 w-4 p-0 text-muted-foreground hover:text-foreground",children:e.jsx(s.Info,{className:"h-3 w-3"})})}),e.jsx(s.HoverCardContent,{className:"w-80",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Share with All Users"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["This action will share the dashboard with all users in your"," ",(t==null?void 0:t.type)==="organization"?"organization":"tenant",". Users will receive the selected access level."]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Viewer:"})," Can view the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Editor:"})," Can view and edit the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Contributor:"})," Can view, edit, and share the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"None:"})," No access for all users"]})]})]})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:u.map(N=>e.jsxs(s.Button,{variant:h===N.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>f(N.value),disabled:a||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[b(N.value),e.jsx("span",{className:"font-medium",children:N.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:N.description})]},N.value))})]})})]})})}function pt({currentUser:t,currentShare:n,isSharing:a,isUpdating:r,isRemoving:o,onUpdateAccess:l,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const u=x=>x==="OWNER"?"CONTRIBUTOR":x,h=n?{role:u(n.role)}:{role:"NONE"},p=i?{currentRole:u(i.currentRole),newRole:u(i.newRole)}:null,g=(x,b)=>{l(x,b)},j=()=>{c()};return e.jsx(mn,{currentUser:t,currentShare:h,isSharing:a,isUpdating:r,isRemoving:o,onUpdateAccess:g,onRemoveAccess:j,allUsersToUpdate:p,allUsersToRemove:d})}function Ve(t){const{debouncedSearchQuery:n,resourceId:a,resourceType:r=s.ResourceType.DASHBOARD,userType:o,tenantId:l}=t,c=A.useMemo(()=>({search:n,active:!0,...o?{type:o}:{},...o==="tenant"&&l?{tenantId:l}:{}}),[n,o,l]),{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 hn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:l=!1,isRemoving:c=!1}){var X,te;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),p=s.useShareSelectedUsers(),g=s.useShareUsersToRemove(),j=s.useShareUsersToUpdate(),x=s.useShareCurrentMode(),b=s.useShareOrgWideRole(),f=s.useShareManagementActions(),[N,k]=A.useState("specific_users"),I=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},S=()=>{if(i==="tenant"&&d)return d},{allUsers:C,existingShares:v,isLoadingUsers:T}=Ve({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:I(),tenantId:S()});A.useEffect(()=>{f.setCurrentContext("org-tab"),f.setCurrentMode(N==="all_users"?"allOrgUsers":"specificOrgUsers")},[f,N]);const y=K=>{var U,ee;const H=K;if(k(H),r==null||r(H),f.setCurrentContext("org-tab"),H==="specific_users")f.setCurrentMode("specificOrgUsers");else if(H==="all_users"){f.setCurrentMode("allOrgUsers");const _=(ee=(U=v==null?void 0:v.shares)==null?void 0:U.orgUsersOnly)==null?void 0:ee[0];_&&_.role!==void 0&&f.setOrgWideRole(_.role)}},O=C.filter(K=>K.name.toLowerCase().includes(u.toLowerCase())||K.email.toLowerCase().includes(u.toLowerCase())),E=C.filter(K=>p.some(H=>H.id===K.id)),B=K=>{var _,V;const H=p.some(se=>se.id===K),U=g.includes(K),ee=(V=(_=v==null?void 0:v.shares)==null?void 0:_.specificOrgUsers)==null?void 0:V.some(se=>se.orgUserId===K);H?f.removeSelectedUser(K):U?f.removeUserFromRemove(K):ee||f.addSelectedUser({id:K,role:"VIEWER"})},w=(K,H)=>{f.updateSelectedUserRole(K,H)},D=K=>{f.addUserToRemove(K),f.removeSelectedUser(K)},L=K=>{f.removeUserFromRemove(K)},F=K=>{f.removeUserFromUpdate(K)},R=(K,H)=>{f.setOrgWideRole(H)},M=()=>{f.setOrgWideRole((P==null?void 0:P.role)||"NONE")},P=(te=(X=v==null?void 0:v.shares)==null?void 0:X.orgUsersOnly)==null?void 0:te[0];A.useEffect(()=>{N==="all_users"&&P&&P.role!==void 0&&f.setOrgWideRole(P.role)},[N,P,f]);const W=T,z=!1;return a?e.jsxs(e.Fragment,{children:[e.jsx(Ss,{shareType:N,onShareTypeChange:y,currentUser:a,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(a==null?void 0:a.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role??"")}]}),N==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(ts,{value:u,onChange:m}),e.jsx(ct,{selectedUsers:p,selectedUserObjects:E,onRemove:B,onRoleChange:w,getRoleOptions:be}),e.jsx(dt,{usersToRemove:g,allUsers:O,onRemove:L}),e.jsx(ut,{usersToUpdate:j,allUsers:O,onRemove:F,getRoleOptions:be}),e.jsx(xt,{existingShares:v,isInitialLoading:W,isSearching:z,resource:t,onShare:()=>{},getRoleOptions:be,allUsers:O,currentUser:a,handleUserToggle:B,handleUserRoleChange:w,handleRemoveAccess:D,handleUpdateAccess:(K,H,U)=>{f.addUserToUpdate({id:K,currentRole:H,newRole:U})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(pt,{currentUser:a,currentShare:P,isSharing:o,isUpdating:l,isRemoving:c,onUpdateAccess:R,onRemoveAccess:M,allUsersToUpdate:x==="allOrgUsers"&&b!==((P==null?void 0:P.role)||"NONE")?{currentRole:(P==null?void 0:P.role)||"NONE",newRole:b}:null,allUsersToRemove:x==="allOrgUsers"&&(P==null?void 0:P.role)===void 0})})]}):null}function xn(t){switch(t){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function pn(t){switch(t){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function ft({groups:t,existingGroupShares:n,isLoading:a,resource:r,getRoleOptions:o,currentUser:l,handleGroupToggle:c,handleGroupRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),p=s.useShareGroupsToUpdate(),g=s.useShareManagementActions(),j=o(l==null?void 0:l.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(x=>{const b=n==null?void 0:n.find(v=>v.groupId===x.id),f=m.some(v=>v.id===x.id),N=h.includes(x.id),k=p.find(v=>v.id===x.id),I=!!b&&!N;let C=(b==null?void 0:b.role)||"VIEWER";if(f){const v=m.find(T=>T.id===x.id);C=(v==null?void 0:v.role)||"VIEWER"}else k&&(C=k.newRole);return e.jsxs("div",{className:s.cn("flex items-center justify-between rounded-lg p-2 transition-colors",I&&!N?"border border-green-200 bg-green-50":N?"border border-red-200 bg-red-50":f?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(s.Checkbox,{id:`group-${x.id}`,checked:I?!N:f,disabled:!1,onCheckedChange:()=>{I?N?g.removeGroupFromRemove(x.id):d==null||d(x.id):c==null||c(x.id)}}),e.jsxs("label",{htmlFor:`group-${x.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:x.name}),x.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:[x.memberCount," members"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:s.cn("text-xs",pn(x.type)),children:xn(x.type)}),x.type==="TENANT_GROUP"&&x.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",x.tenantName]})]}),x.description&&e.jsx("span",{className:"text-xs text-muted-foreground",children:x.description})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[I&&!N?e.jsx(Oe,{currentRole:C,onRoleChange:v=>{b&&v!==b.role&&(u==null||u(x.id,b.role,v))},roleOptions:j,disabled:!1,allowDropdown:!0,className:k?"border-orange-300 bg-orange-100":""}):f&&!I&&e.jsx(Oe,{currentRole:C,onRoleChange:v=>i==null?void 0:i(x.id,v),roleOptions:j,disabled:!1}),I&&!N&&!k&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>d==null?void 0:d(x.id),children:e.jsx(s.X,{className:"h-4 w-4"})}),N&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromRemove(x.id),children:"Undo"}),k&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromUpdate(x.id),children:"Cancel"})]})]},x.id)})})]})}function gt({selectedGroups:t,groupObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:o}){if(t.length===0)return null;const l=o();return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:["Selected Groups (",t.length,")"]}),e.jsx("div",{className:"space-y-1",children:t.map(c=>{const i=n.find(d=>d.id===c.id);return i?e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted/50 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[i.type==="ORG_GROUP"?e.jsx(s.Building2,{className:"h-4 w-4 text-blue-600"}):e.jsx(s.Users,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{className:"text-sm font-medium",children:i.name}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[i.memberCount," members"]}),i.type==="TENANT_GROUP"&&i.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",i.tenantName]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oe,{currentRole:c.role,onRoleChange:d=>r(c.id,d),roleOptions:l}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>a(c.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})]},c.id):null})})]})}function Us({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:l=!1,isRemoving:c=!1}){var fe;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),g=s.useShareSelectedGroups(),j=s.useShareGroupsToRemove(),x=s.useShareGroupsToUpdate(),b=s.useShareCurrentMode(),f=s.useShareTenantWideRole(),N=s.useShareAllTenantsRole(),k=s.useShareSelectedTenant(),I=s.useShareManagementActions(),{data:S,isLoading:C}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"}),{groups:v,isLoading:T}=s.useShareableGroups("tenant",(a==null?void 0:a.tenantId)||k),[y,O]=A.useState((a==null?void 0:a.type)==="organization"?"all_tenants":"specific_tenant_users");A.useEffect(()=>{(a==null?void 0:a.type)==="tenant"?(I.setCurrentContext("tenant-dialog"),I.setCurrentMode("specificTenantUsers")):(I.setCurrentContext("tenant-tab"),I.setCurrentMode("allTenants"))},[I,a==null?void 0:a.type]);const E=$=>{var Z,q,ae,ie;O($);let J;if($==="specific_tenant_users"?J="specific_users":$==="all_tenant_users"||$==="all_tenants"?J="all_users":$==="groups"?J="groups":J="specific_users",r==null||r(J),$==="groups"?(I.setCurrentContext("group-share"),I.setCurrentMode("specificGroups")):(a==null?void 0:a.type)==="tenant"?(I.setCurrentContext("tenant-dialog"),$==="specific_tenant_users"?I.setCurrentMode("specificTenantUsers"):$==="all_tenant_users"&&(I.setCurrentMode("allTenantUsers"),a!=null&&a.tenantId&&I.setSelectedTenant(a.tenantId))):(I.setCurrentContext("tenant-tab"),$==="specific_tenant_users"?I.setCurrentMode("specificTenantUsers"):$==="all_tenant_users"?I.setCurrentMode("allTenantUsers"):$==="all_tenants"&&I.setCurrentMode("allTenants")),$==="all_tenant_users"){const ce=(q=(Z=D==null?void 0:D.shares)==null?void 0:Z.tenantWide)==null?void 0:q[0];ce&&ce.role!==void 0&&I.setTenantWideRole(ce.role)}else if($==="all_tenants"){const ce=(ie=(ae=D==null?void 0:D.shares)==null?void 0:ae.allTenantsOnly)==null?void 0:ie[0];ce&&ce.role!==void 0&&I.setAllTenantsRole(ce.role)}},B=$=>{I.setSelectedTenant($)},{allUsers:w,existingShares:D,isLoadingUsers:L,isErrorLoadingUsers:F,isLoadingShares:R,isErrorLoadingShares:M}=Ve({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant",tenantId:(a==null?void 0:a.type)==="tenant"?a.tenantId:k}),P=$=>{var ae,ie;const J=m.some(ce=>ce.id===$),Z=h.includes($),q=(ie=(ae=D==null?void 0:D.shares)==null?void 0:ae.specificTenantUsers)==null?void 0:ie.some(ce=>ce.tenantUserId===$);J?I.removeSelectedUser($):Z?I.removeUserFromRemove($):q||I.addSelectedUser({id:$,role:"VIEWER"})},W=($,J)=>{I.updateSelectedUserRole($,J)},z=$=>{I.addUserToRemove($),I.removeSelectedUser($)},X=$=>{I.removeUserFromRemove($)},te=$=>{I.removeUserFromUpdate($)},K=($,J,Z)=>{I.addUserToUpdate({id:$,currentRole:J,newRole:Z})},H=($,J)=>{y==="all_tenant_users"?I.setTenantWideRole(J):y==="all_tenants"&&I.setAllTenantsRole(J)},U=()=>{y==="all_tenant_users"?I.setTenantWideRole("VIEWER"):y==="all_tenants"&&I.setAllTenantsRole("VIEWER")},_=(()=>{var $,J,Z,q;return b==="allTenants"?(J=($=D==null?void 0:D.shares)==null?void 0:$.allTenantsOnly)==null?void 0:J[0]:b==="allTenantUsers"?(q=(Z=D==null?void 0:D.shares)==null?void 0:Z.tenantWide)==null?void 0:q[0]:null})();A.useEffect(()=>{var $,J,Z,q;if(y==="all_tenant_users"){const ae=(J=($=D==null?void 0:D.shares)==null?void 0:$.tenantWide)==null?void 0:J[0];ae&&ae.role!==void 0&&I.setTenantWideRole(ae.role)}else if(y==="all_tenants"){const ae=(q=(Z=D==null?void 0:D.shares)==null?void 0:Z.allTenantsOnly)==null?void 0:q[0];ae&&ae.role!==void 0&&I.setAllTenantsRole(ae.role)}},[y,D,I]);const V=w.filter($=>m.some(J=>J.id===$.id)),se=$=>{const J=g.some(ae=>ae.id===$),Z=j.includes($),q=le==null?void 0:le.some(ae=>ae.groupId===$);J?I.removeSelectedGroup($):Z?I.removeGroupFromRemove($):q||I.addSelectedGroup({id:$,role:"VIEWER"})},ne=($,J)=>{I.updateSelectedGroupRole($,J)},G=$=>{I.addGroupToRemove($),I.removeSelectedGroup($)},Y=($,J,Z)=>{I.addGroupToUpdate({id:$,currentRole:J,newRole:Z})},re=v.filter($=>g.some(J=>J.id===$.id)),oe=A.useMemo(()=>y!=="groups"?[]:v.filter($=>$.type!=="TENANT_GROUP"?!1:$.name.toLowerCase().includes(i.toLowerCase())||$.description&&$.description.toLowerCase().includes(i.toLowerCase())),[v,y,i]),le=A.useMemo(()=>{var J,Z;const $=((J=D==null?void 0:D.shares)==null?void 0:J.specificGroups)||((Z=D==null?void 0:D.shares)==null?void 0:Z.groups)||[];return!$||$.length===0?[]:$.filter(q=>{const ae=v.find(ie=>ie.id===q.groupId);return(ae==null?void 0:ae.type)==="TENANT_GROUP"})},[D,v]),xe=L||R||y==="groups"&&T,pe=F||M,me=()=>(a==null?void 0:a.type)==="tenant"||y==="all_tenants"||y==="groups"?!0:k&&(y==="specific_tenant_users"||y==="all_tenant_users");return e.jsxs(e.Fragment,{children:[pe&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(s.CircleAlert,{className:"mx-auto mb-2 h-8 w-8 text-destructive"}),e.jsx("p",{className:"mb-4 text-sm text-destructive",children:"Failed to load users or shares"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:()=>window.location.reload(),children:"Retry"})]})}),!pe&&a&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(Ss,{shareType:y,onShareTypeChange:E,currentUser:a,options:(a==null?void 0:a.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"specific_tenant_users",label:"Specific Users",description:"Share with specific tenant users",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"groups",label:"Groups",description:"Share with tenant groups",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-green-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:e.jsx(_s,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"all_tenant_users",label:"Specific Tenant",description:"Share with all users of a specific tenant",icon:e.jsx(s.House,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"specific_tenant_users",label:"Specific Tenant User",description:"Share with users of a specific tenant",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(a==null?void 0:a.type)==="organization"&&(y==="specific_tenant_users"||y==="all_tenant_users")&&e.jsxs("div",{className:"mt-4",children:[e.jsx(s.Label,{className:"mb-1 block text-sm font-medium",children:"Select Tenant"}),e.jsxs(s.Select,{value:k||"",onValueChange:B,disabled:C,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:C?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(fe=S==null?void 0:S.tenants)==null?void 0:fe.map($=>e.jsx(s.SelectItem,{value:$.id,children:$.name},$.id))})]})]}),me()?e.jsx(e.Fragment,{children:y==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(ts,{value:i,onChange:u}),e.jsx(ct,{selectedUsers:m,selectedUserObjects:V,onRemove:$=>P($),onRoleChange:W,getRoleOptions:be}),e.jsx(dt,{usersToRemove:h,allUsers:w,onRemove:X}),e.jsx(ut,{usersToUpdate:p,allUsers:w,onRemove:te,getRoleOptions:be}),e.jsx(xt,{existingShares:D,isInitialLoading:!!xe,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:be,allUsers:w,currentUser:a,handleUserToggle:P,handleUserRoleChange:W,handleRemoveAccess:z,handleUpdateAccess:K})]}):y==="groups"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(ts,{value:i,onChange:u,placeholder:"Search groups..."}),e.jsx(gt,{selectedGroups:g,groupObjects:re,onRemove:se,onRoleChange:ne,getRoleOptions:be}),j.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",j.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),x.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",x.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(ft,{groups:oe,existingGroupShares:le,isLoading:T,resource:t,getRoleOptions:be,currentUser:a,handleGroupToggle:se,handleGroupRoleChange:ne,handleRemoveAccess:G,handleUpdateAccess:Y})]}):y==="all_tenant_users"||y==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(pt,{currentUser:a,currentShare:_,isSharing:o,isUpdating:l,isRemoving:c,onUpdateAccess:H,onRemoveAccess:U,allUsersToUpdate:b==="allTenantUsers"&&((_==null?void 0:_.role)===void 0||f!==_.role)||b==="allTenants"&&((_==null?void 0:_.role)===void 0||N!==_.role)?{currentRole:(_==null?void 0:_.role)||"VIEWER",newRole:b==="allTenantUsers"?f:N}:null,allUsersToRemove:b==="allTenantUsers"&&(_==null?void 0:_.role)===void 0||b==="allTenants"&&(_==null?void 0:_.role)===void 0})}):null}):(a==null?void 0:a.type)==="organization"&&(y==="specific_tenant_users"||y==="all_tenant_users")&&e.jsx("div",{className:"mt-6 flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(_s,{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 fn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:l=!1,isRemoving:c=!1}){var F,R;const{searchQuery:i,setSearchQuery:d}=s.useShareSearchWithDebounce(),u=s.useShareSelectedGroups(),m=s.useShareGroupsToRemove(),h=s.useShareGroupsToUpdate(),p=s.useShareManagementActions(),[g,j]=A.useState("org_groups"),[x,b]=A.useState(""),{data:f,isLoading:N}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"&&g==="tenant_groups"}),k=Array.isArray(f)?f:(f==null?void 0:f.tenants)||[],I=()=>{if((a==null?void 0:a.type)==="organization")return"organization";if((a==null?void 0:a.type)==="tenant")return"tenant"},{groups:S,isLoading:C}=s.useShareableGroups(I(),g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"?x:a==null?void 0:a.tenantId),{existingShares:v}=Ve({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n}),T=S.filter(M=>g==="org_groups"&&M.type!=="ORG_GROUP"||g==="tenant_groups"&&M.type!=="TENANT_GROUP"||g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&(!x||M.tenantId&&M.tenantId!==x)?!1:M.name.toLowerCase().includes(i.toLowerCase())||M.description&&M.description.toLowerCase().includes(i.toLowerCase())),y=((F=v==null?void 0:v.shares)==null?void 0:F.specificGroups)||((R=v==null?void 0:v.shares)==null?void 0:R.groups)||[];A.useEffect(()=>{p.setCurrentContext("group-share"),p.setCurrentMode("specificGroups")},[p]);const O=M=>{const P=M;j(P),P==="org_groups"&&b(""),r==null||r(P==="org_groups"?"specific_groups":"all_groups"),p.setCurrentContext("group-share"),p.setCurrentMode("specificGroups")},E=S.filter(M=>u.some(P=>P.id===M.id)),B=M=>{const P=u.some(X=>X.id===M),W=m.includes(M),z=y==null?void 0:y.some(X=>X.groupId===M);P?p.removeSelectedGroup(M):W?p.removeGroupFromRemove(M):z||p.addSelectedGroup({id:M,role:"VIEWER"})},w=(M,P)=>{p.updateSelectedGroupRole(M,P)},D=M=>{p.addGroupToRemove(M),p.removeSelectedGroup(M)},L=(M,P,W)=>{p.addGroupToUpdate({id:M,currentRole:P,newRole:W})};return a?e.jsxs(e.Fragment,{children:[e.jsx(Ss,{shareType:g,onShareTypeChange:O,currentUser:a,options:[{value:"org_groups",label:"Organization Groups",description:"Share with organization-level groups",icon:e.jsx(s.Building2,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"tenant_groups",label:"Tenant Groups",description:"Share with tenant-level groups",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-green-500"})}]}),g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(s.Label,{children:"Select Tenant"}),e.jsxs(s.Select,{value:x,onValueChange:b,disabled:N,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:N?"Loading tenants...":"Select a tenant to view its groups"})}),e.jsx(s.SelectContent,{className:"z-[51]",children:k.map(M=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:M.id,children:M.name},M.id))})]})]}),e.jsx("div",{className:"mt-3 space-y-2",children:g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&!x?e.jsx("div",{className:"rounded-md border border-dashed p-6 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant above to view and share with its groups"})}):e.jsxs(e.Fragment,{children:[e.jsx(ts,{value:i,onChange:d,placeholder:"Search groups..."}),e.jsx(gt,{selectedGroups:u,groupObjects:E,onRemove:B,onRoleChange:w,getRoleOptions:be}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",m.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",h.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(ft,{groups:T,existingGroupShares:y,isLoading:C,resource:t,getRoleOptions:be,currentUser:a,handleGroupToggle:B,handleGroupRoleChange:w,handleRemoveAccess:D,handleUpdateAccess:L})]})})]}):null}const jt=()=>{const t=s.useShareCurrentContext(),n=s.useShareCurrentMode(),a=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),o=s.useShareUsersToUpdate(),l=s.useShareSelectedGroups(),c=s.useShareGroupsToRemove(),i=s.useShareGroupsToUpdate(),d=s.useShareSelectedTenant(),u=s.useShareOrgWideRole(),m=s.useShareAllTenantsRole(),h=s.useShareTenantWideRole(),p=s.useShareGroupWideRole(),g=A.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:o,selectedGroups:l,groupsToRemove:c,groupsToUpdate:i,selectedTenant:d,orgWideRole:u,allTenantsRole:m,tenantWideRole:h}),[t,n,a,r,o,l,c,i,d,u,m,h,p]),j=A.useMemo(()=>b=>s.validateShareData(b),[]),x=A.useMemo(()=>{if(!t||!n)return!1;switch(t){case"org-tab":return n==="specificOrgUsers"?a.length>0||r.length>0||o.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||o.length>0:!1;return!0;case"tenant-dialog":return n==="specificTenantUsers"?a.length>0||r.length>0||o.length>0:!0;case"group-share":return n==="specificGroups"?l.length>0||c.length>0||i.length>0:!0}return!1},[t,n,a,r,o,l,c,i,d]);return{buildShareData:g,validateShareData:j,isCurrentStateValid:x,currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:o,selectedTenant:d,orgWideRole:u,allTenantsRole:m,tenantWideRole:h}};function Ys({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:o,onShare:l,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),g=s.useShareSelectedTenant(),j=s.useShareOrgWideRole(),x=s.useShareAllTenantsRole(),b=s.useShareTenantWideRole(),{buildShareData:f,validateShareData:N,isCurrentStateValid:k}=jt(),I=a||r||o,S=()=>{var O,E,B,w;if(I)return"Updating...";if(i==="specific_users"){if(m.length===0&&h.length===0&&p.length===0)return"Select users to share with";const D=m.length+h.length+p.length;return D===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${D} user${D!==1?"s":""}`:h.length>0&&m.length===0&&p.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&p.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:p.length>0&&m.length===0&&h.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${D} user${D!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const D=d.role;return j===D?"Remove Access":"Update Access"}else if(i==="all_tenants"){const D=(E=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:E[0];if(!D||D.role===void 0)return"Share with All Tenants";const L=D.role;return x===L?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const D=(w=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:w[0];if(!D||D.role===void 0)return"Share with All Tenant Users";const L=D.role;return b===L?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(m.length===0&&h.length===0&&p.length===0)return"Select users to share with";const D=m.length+h.length+p.length;return D===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${D} user${D!==1?"s":""}`:h.length>0&&m.length===0&&p.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&p.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:p.length>0&&m.length===0&&h.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${D} user${D!==1?"s":""}`}return"Share"},C=()=>I||!t||i==="all_tenant_users"&&!g||i==="specific_tenant_users"&&!g?!0:!k,v=()=>{const O=f();O&&N(O)&&l(O)},T=()=>{var O,E,B,w;if(i==="all_users")if(!d||d.role===void 0){const D=f();D&&N(D)&&l(D)}else{const D=d.role;if(j===D)u==null||u();else{const F=f();if(F&&N(F)){const R={...F,updateAccess:!0};l(R)}}}else if(i==="all_tenants"){const D=(E=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:E[0];if(!D||D.role===void 0){const L=f();L&&N(L)&&l(L)}else{const L=D.role;if(x===L)u==null||u();else{const R=f();if(R&&N(R)){const M={...R,updateAccess:!0};l(M)}}}}else if(i==="all_tenant_users"){const D=(w=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:w[0];if(!D||D.role===void 0){const L=f();L&&N(L)&&l(L)}else{const L=D.role;if(b===L)u==null||u();else{const R=f();if(R&&N(R)){const M={...R,updateAccess:!0};l(M)}}}}},y=()=>{var O,E,B,w;if(i==="all_users"){if(!d||d.role===void 0)return"default";const D=d.role;return j===D?"destructive":"default"}else if(i==="all_tenants"){const D=(E=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:E[0];if(!D||D.role===void 0)return"default";const L=D.role;return x===L?"destructive":"default"}else if(i==="all_tenant_users"){const D=(w=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:w[0];if(!D||D.role===void 0)return"default";const L=D.role;return b===L?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:I,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||h.length>0||p.length>0)&&e.jsxs(s.Button,{onClick:v,disabled:!t||I,variant:"default",children:[I?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(ze,{className:"mr-2 h-4 w-4"}),!I&&S()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:T,disabled:C(),variant:y(),children:[I?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(s.Users,{className:"mr-2 h-4 w-4"}),!I&&S()]})]})}function gn({resource:t,isSharing:n,isRemoving:a,isUpdating:r,onShare:o,onClose:l,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate(),h=s.useShareSelectedGroups(),p=s.useShareGroupsToRemove(),g=s.useShareGroupsToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const j=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:x,validateShareData:b,isCurrentStateValid:f}=jt(),N=n||a||r,k=()=>{if(N)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&m.length===0)return"Select users to share with";const y=d.length+u.length+m.length;return y===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${y} user${y!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:d.length>0&&u.length===0&&m.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${y} user${y!==1?"s":""}`}else if(c==="groups"){if(h.length===0&&p.length===0&&g.length===0)return"Select groups to share with";const y=h.length+p.length+g.length;return y===0?"Select groups to share with":h.length>0&&p.length>0?`Update access for ${y} group${y!==1?"s":""}`:p.length>0&&h.length===0&&g.length===0?`Remove access for ${p.length} group${p.length!==1?"s":""}`:h.length>0&&p.length===0&&g.length===0?`Share with ${h.length} group${h.length!==1?"s":""}`:g.length>0&&h.length===0&&p.length===0?`Update access for ${g.length} group${g.length!==1?"s":""}`:`Update access for ${y} group${y!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const y=i.role;return j===y?"Remove Access":"Update Access"}return"Share"},I=()=>N||!t?!0:!f,S=()=>{const y=x();y&&b(y)&&o(y)},C=()=>{const y=x();y&&b(y)&&o(y)},v=()=>{if(!i||i.role==="NONE"){const y=x();y&&b(y)&&o(y)}else{const y=i.role;if(j===y){const E=x();if(E&&b(E)){const B={...E,removeAccess:!0};o(B)}}else{const E=x();if(E&&b(E)){const B={...E,updateAccess:!0};o(B)}}}},T=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:l,disabled:N,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:S,disabled:!t||N,variant:"default",children:[N?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(ze,{className:"mr-2 h-4 w-4"}),!N&&k()]})}),c==="groups"&&e.jsx(e.Fragment,{children:(h.length>0||p.length>0||g.length>0)&&e.jsxs(s.Button,{onClick:C,disabled:!t||N,variant:"default",children:[N?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(ze,{className:"mr-2 h-4 w-4"}),!N&&k()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:v,disabled:I(),variant:T(),children:[N?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(ze,{className:"mr-2 h-4 w-4"}),!N&&k()]})]})}function jn({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:o,onShare:l,onClose:c,shareTabType:i,currentAllGroupsShare:d,onRemoveAccess:u}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),p=s.useShareGroupsToUpdate();s.useShareGroupWideRole(),s.useShareCurrentMode();const g=()=>{l({context:"group-share",mode:"specificGroups",selectedGroups:m,groupsToRemove:h,groupsToUpdate:p})},j=()=>m.length>0||h.length>0||p.length>0,x=()=>h.length>0&&m.length===0&&p.length===0?"Remove Access":p.length>0&&m.length===0&&h.length===0?"Update Access":"Share with Groups",b=a||r||o;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"]}),p.length>0&&e.jsxs("span",{className:"ml-2 text-orange-600",children:["• ",p.length," to update"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:b,children:"Cancel"}),e.jsxs(s.Button,{onClick:g,disabled:!j()||b,children:[b&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),x()]})]})]})}function je(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Se(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function bn(t,n,a){const{resourceType:r,resourceId:o,shareMutation:l,removeMutation:c,existingShares:i,resetUserSelections:d}=n;if(o)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const u=je(r,o,[{scope:"org_users_only",role:t.orgWideRole}]);l(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const p=je(r,o,u.map(g=>({scope:"specific_org_user",orgUserId:g.id,role:g.role})));l(p,{onSuccess:()=>{d()}})}if(m&&m.length>0){const p=Se(r,o,m.map(g=>{var x,b;const j=(b=(x=i==null?void 0:i.shares)==null?void 0:x.specificOrgUsers)==null?void 0:b.find(f=>f.orgUserId===g);return{scope:"specific_org_user",orgUserId:g,role:(j==null?void 0:j.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(p=>{const g=je(r,o,[{scope:"specific_org_user",orgUserId:p.id,role:p.newRole}]);l(g,{onSuccess:()=>{d()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const u=je(r,o,[{scope:"all_tenants_only",role:t.allTenantsRole}]);l(u,{onSuccess:()=>{d()}})}else if(t.mode==="allTenantUsers"){const u=je(r,o,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);l(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h,tenantId:p}=t;if(m&&m.length>0){const g=Se(r,o,m.map(j=>{var b,f;const x=(f=(b=i==null?void 0:i.shares)==null?void 0:b.specificTenantUsers)==null?void 0:f.find(N=>N.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,tenantId:p,role:(x==null?void 0:x.role)||"VIEWER"}}));c(g,{onSuccess:()=>{d()}})}if(h&&h.length>0&&h.forEach(g=>{const j=je(r,o,[{scope:"specific_tenant_user",tenantUserId:g.id,tenantId:p,role:g.newRole}]);l(j,{onSuccess:()=>{d()}})}),u&&u.length>0){const g=je(r,o,u.map(j=>({scope:"specific_tenant_user",tenantUserId:j.id,tenantId:p,role:j.role})));l(g,{onSuccess:()=>{d()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const u=Se(r,o,[{scope:"all_tenant_users",role:"VIEWER"}]);c(u,{onSuccess:()=>{d()}})}else if(t.updateAccess){const u=je(r,o,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);l(u,{onSuccess:()=>{d()}})}else{const u=je(r,o,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);l(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const p=je(r,o,u.map(g=>({scope:"specific_tenant_user",tenantUserId:g.id,role:g.role})));l(p,{onSuccess:()=>{d()}})}if(m&&m.length>0){const p=Se(r,o,m.map(g=>{var x,b;const j=(b=(x=i==null?void 0:i.shares)==null?void 0:x.specificTenantUsers)==null?void 0:b.find(f=>f.tenantUserId===g);return{scope:"specific_tenant_user",tenantUserId:g,role:(j==null?void 0:j.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(p=>{const g=je(r,o,[{scope:"specific_tenant_user",tenantUserId:p.id,role:p.newRole}]);l(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 p=je(r,o,u.map(g=>({scope:"group",groupId:g.id,role:g.role})));l(p,{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 p=Se(r,o,m.map(g=>({scope:"group",groupId:g,role:"VIEWER"})));c(p,{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(p=>{const g=je(r,o,[{scope:"group",groupId:p.id,role:p.newRole}]);l(g,{onSuccess:()=>{var j;d(),(j=n.resetGroupSelections)==null||j.call(n),s.ue.success("Updated access for group")}})})}break}}function vn(t,n,a,r){var u,m,h,p,g,j;const{resourceType:o,resourceId:l,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(l)if(t.length>0){const x=Se(o,l,t.map(b=>{var N,k;const f=(k=(N=i==null?void 0:i.shares)==null?void 0:N.specificTenantUsers)==null?void 0:k.find(I=>I.tenantUserId===b);return{scope:"specific_tenant_user",tenantUserId:b,role:(f==null?void 0:f.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()},onError:b=>{console.error("Remove access failed:",b)}})}else{const x=n==="tenant"&&a==="allTenants",b=n==="tenant"&&a==="allTenantUsers";if(x){const f=(m=(u=i==null?void 0:i.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(f){const N=Se(o,l,[{scope:"all_tenants_only",role:f.role}]);c(N,{onSuccess:()=>{d()},onError:k=>{console.error("Remove all-tenants access failed:",k)}})}}else if(b){const f=(p=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:p[0];if(f){const N=Se(o,l,[{scope:"all_tenant_users",role:f.role}]);c(N,{onSuccess:()=>{d()},onError:k=>{console.error("Remove all-tenant-users access failed:",k)}})}}else{const f=(j=(g=i==null?void 0:i.shares)==null?void 0:g.orgUsersOnly)==null?void 0:j[0];if(f){const N=Se(o,l,[{scope:"org_users_only",role:f.role}]);c(N,{onSuccess:()=>{d()},onError:k=>{console.error("Remove org-wide access failed:",k)}})}}}}function yn(t,n,a){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),l=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=s.useCurrentUserInfo(),{existingShares:d}=Ve({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 j={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:n,removeMutation:a,existingShares:d,resetUserSelections:u,resetGroupSelections:m};bn(g,j,i)},[t,n,a,d,u,m,i]),p=A.useCallback(()=>{if(!t)return;const g={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:a,existingShares:d,resetUserSelections:u};vn(o,l||"",c||"",g)},[t,n,a,d,u,m,o,l,c]);return{handleShareSubmit:h,handleRemoveAccess:p}}function ls({resource:t,resourceType:n,onClose:a,onShareSuccess:r,onRemoveSuccess:o}){var w,D,L,F,R,M,P,W;const{currentUser:l}=s.useCurrentUserInfo(),[c,i]=A.useState("specific_users"),[d,u]=A.useState("specific_users"),[m,h]=A.useState("specific_groups"),p=s.useShareManagementActions(),g=s.useShareSelectedTab(),j=s.useShareCurrentMode(),x=s.useShareResource(),b=s.useRemoveResourceShares(),{handleShareSubmit:f,handleRemoveAccess:N}=yn(t.id,(z,X)=>{x.mutate(z,{...X,onSuccess:()=>{var te;(te=X==null?void 0:X.onSuccess)==null||te.call(X),r==null||r()}})},(z,X)=>{b.mutate(z,{...X,onSuccess:()=>{var te;(te=X==null?void 0:X.onSuccess)==null||te.call(X),o==null||o()}})}),k=x.isPending,I=b.isPending,S=x.isPending,{existingShares:C}=Ve({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant"}),{existingShares:v}=Ve({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"organization"}),T=(D=(w=C==null?void 0:C.shares)==null?void 0:w.tenantWide)==null?void 0:D[0],y=(F=(L=v==null?void 0:v.shares)==null?void 0:L.orgUsersOnly)==null?void 0:F[0],O=()=>{if(g==="org")return d;switch(j){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},E=A.useCallback(()=>{p.resetShareState(),a()},[p,a]),B=(l==null?void 0:l.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:E,children:e.jsxs(s.DialogContent,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(ze,{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:z=>{const X=z;p.setSelectedTab(X),p.resetUserSelections(),p.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(hn,{resource:t,resourceType:n,currentUser:l,onShareTabTypeChange:u,isSharing:k,isUpdating:S,isRemoving:I})})}),e.jsx(s.TabsContent,{value:"tenant",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(Us,{resource:t,resourceType:n,currentUser:l,onShareTabTypeChange:z=>i(z),isSharing:k,isUpdating:S,isRemoving:I})})}),e.jsx(s.TabsContent,{value:"groups",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(fn,{resource:t,resourceType:n,currentUser:l,onShareTabTypeChange:h,isSharing:k,isUpdating:S,isRemoving:I})})})]}):e.jsx("div",{className:"mb-4 min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(Us,{resource:t,resourceType:n,currentUser:l,onShareTabTypeChange:z=>i(z),isSharing:k,isUpdating:S,isRemoving:I})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:B?g==="org"?e.jsx(Ys,{resource:t,existingShares:v,isSharing:k,isRemoving:I,isUpdating:S,onShare:f,onClose:a,shareTabType:d,currentAllUsersShare:y,onRemoveAccess:N}):g==="tenant"?e.jsx(Ys,{resource:t,existingShares:C,isSharing:k,isRemoving:I,isUpdating:S,onShare:f,onClose:a,shareTabType:O(),currentAllUsersShare:T,onRemoveAccess:N}):e.jsx(jn,{resource:t,existingShares:v,isSharing:k,isRemoving:I,isUpdating:S,onShare:f,onClose:a,shareTabType:m,currentAllGroupsShare:(l==null?void 0:l.type)==="organization"?(M=(R=v==null?void 0:v.shares)==null?void 0:R.allOrgGroups)==null?void 0:M[0]:(W=(P=C==null?void 0:C.shares)==null?void 0:P.allTenantGroups)==null?void 0:W[0],onRemoveAccess:N}):e.jsx(gn,{resource:t,isSharing:k,isRemoving:I,isUpdating:S,onShare:f,onClose:a,shareTabType:c,currentAllUsersShare:T,onRemoveAccess:N})})]})})}function Nn(t){const n=t.toUpperCase().indexOf("WHERE"),a=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),o=t.toUpperCase().indexOf("ORDER BY");let l=t.length;if(o!==-1&&(l=o),r!==-1&&r<l&&(l=r),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,l),i=t.substring(l);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function ws(t){const[n,a]=A.useState(null),[r,o]=A.useState(null);return A.useEffect(()=>{if(!t||t.trim()===""){a(null),o(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");a(()=>d.useChartStore),o(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),o(i),a(null)}})()},[t]),n}function Cn(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 l=r.split("__")[0],c=t.find(i=>i.tabTitle===l);return c?c.id:t[0].id}return n}}return t[0].id}async function $s(t,n,a){if(!t||!n)throw new Error("Missing auth token or visual ID");const r=["resource-by-id","visual",n],o=a.getQueryData(r);if(o)return console.log("Using cached visual data for:",n),{data:o,fromCache:!0};console.log("Fetching visual data from network for:",n);const l=s.ue.loading("Loading visual...",{position:"top-center"});try{const c=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${n}`,{headers:{Authorization:`Bearer ${t}`}});if(!c.ok)throw new Error("Failed to load visual");const i=await c.json();return a.setQueryData(r,i),s.ue.dismiss(l),{data:i,fromCache:!1}}catch(c){throw s.ue.dismiss(l),c}}function Sn(t,n,a,r,o){const l=t.frameObject;n(l);const c=l.cards.find(i=>i.id===l.activeCardId);c&&a(c),r(!0),o(!0)}function wn(){var p;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(g=>g.frame),a=s.useEditorStore(g=>g.card),r=ws(((p=a.customCardPreferences)==null?void 0:p.url)||""),o=s.useEditorStore(g=>g.selectedSchemaName),l=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=Nn(m),t(g));const j=(f=r==null?void 0:r.getState())==null?void 0:f.settings,x={...a,dataSource:a.dataSource||{mode:"directSource"},lastSelectedSchema:o,lastSelectedDatamodelId:l,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:g,customCfg:u?a.customCfg:null,preferences:a.preferences,...j&&{customCardPreferences:{...a.customCardPreferences,settings:j}}},b=n.cards.map(N=>N.id===a.id?x:N);return{...n,cards:b,activeCardId:Cn(b,n.activeCardId)}},[a,n,u,o,l,c,i,d,t,r,m])}}function Ds(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient(),a=s.useSelectedVisual(),{selectVisual:r}=s.useManagementActions(),{setFrame:o,setCard:l}=s.useEditorActions(),{setIsDashboardEditing:c,setIsVisualEditing:i,setSelectedFrameId:d,addFrame:u,setIsDashboardPanelOpen:m}=s.useDashboardActions(),h=s.useDashboardStore(x=>x.selectedSheetId),p=s.useVisualById((a==null?void 0:a.id)||"",{enabled:!!(a!=null&&a.id)&&!!(t!=null&&t.accessToken)}),g=A.useCallback(async x=>{try{r(x);const{data:b,fromCache:f}=await $s((t==null?void 0:t.accessToken)||"",x.id,n);return Sn(b,o,l,c,i),{success:!0,fromCache:f}}catch(b){return console.error("Error editing visual:",b),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,n,r,o,l,c,i]),j=A.useCallback(async x=>{try{if(r(x),!h)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:b,fromCache:f}=await $s((t==null?void 0:t.accessToken)||"",x.id,n),N=b.frameObject;if(!N)return{success:!1,error:"Visual has no frame data"};const k={...N,id:s.v4()};return u(h,k,"end"),c(!0),d(k.id),m(!1),{success:!0,fromCache:f}}catch(b){return console.error("Error adding visual:",b),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n,r,h,u,c,d,m]);return{visual:p.data,isLoading:p.isLoading,isError:p.isError,error:p.error,handleEditLibraryVisual:g,handleAddLibraryVisual:j,getUpdatedFrame:wn().getUpdatedFrame,refetch:p.refetch}}function Dn(){const[t,n]=A.useState(""),[a,r]=A.useState(!1),[o,l]=A.useState(""),[c,i]=A.useState(""),[d,u]=A.useState(!1),[m,h]=A.useState(null),[p,g]=A.useState(!1),[j,x]=A.useState(null),[b,f]=A.useState(null),{setIsDashboardEditing:N,setIsVisualEditing:k}=s.useDashboardActions(),{handleEditLibraryVisual:I,handleAddLibraryVisual:S}=Ds(),{resources:C,isLoading:v,isError:T,createResource:y,updateResource:O,deleteResource:E,duplicateResource:B,isCreating:w,isDeleting:D}=s.useVisualManagement(()=>{g(!1),x(null)},()=>{r(!1),l(""),i("")});s.useCurrentUserInfo();const L=C.filter(V=>{var se,ne;return((se=V==null?void 0:V.title)==null?void 0:se.toLowerCase().includes(t.toLowerCase()))||((ne=V==null?void 0:V.description)==null?void 0:ne.toLowerCase().includes(t.toLowerCase()))}),F=V=>new Date(V).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),R=()=>{o.trim()&&y({title:o,description:c,isPrivate:!1})},M=V=>{x(V),g(!0)},P=()=>{j&&E(j.id)},{startUpdating:W,stopUpdating:z,isUpdating:X}=s.useResourceUpdateState(),te=(V,se)=>{const ne=se.title!==void 0?"title":"description";W(V,ne),O({resourceId:V,data:se},{onSuccess:()=>{z(V,ne)},onError:()=>{z(V,ne)}})},K=V=>{f(V),B(V,{onSettled:()=>f(null)})},H=V=>{I(V)},U=V=>{S(V)},ee=V=>{const se=C.find(ne=>ne.id===V);se&&O({resourceId:V,data:{isPrivate:!se.isPrivate}})},_=V=>{h(V),u(!0)};return v?e.jsx(it,{}):T?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:a?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:o,onChange:V=>l(V.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:V=>i(V.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:R,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||w,children:w?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),l(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:w,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",disabled:w,children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),w?"Creating...":"Create New Visual"]})}),C&&C.length>5&&e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:V=>n(V.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:L.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"mb-3",children:e.jsx(rs,{className:"h-12 w-12 mx-auto text-muted-foreground/50"})}),e.jsx("h3",{className:"font-medium text-foreground mb-1",children:t?"No visuals found":"No visuals yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:t?"Try adjusting your search":"Create your first visual component to get started"}),!t&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),"Create Visual"]})]}):L.map(V=>e.jsx(sn,{visual:V,onAddVisual:U,onEditVisual:H,onUpdateVisual:te,onDeleteClick:M,onDuplicateVisual:K,onTogglePrivacy:ee,onShareVisual:_,isDeleting:D,isDuplicating:b===V.id,isTitleUpdating:X(V.id,"title"),isDescriptionUpdating:X(V.id,"description"),formatDate:F},V.id))})}),d&&m&&e.jsx(ls,{resource:m,resourceType:s.ResourceType.VISUAL,onClose:()=>{u(!1),h(null)}}),e.jsx(s.AlertDialog,{open:p,onOpenChange:V=>{!V&&D||(g(V),V||x(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',j==null?void 0:j.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:D,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:V=>{V.preventDefault(),V.stopPropagation(),P()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:D,children:D?"Deleting...":"Delete"})]})]})})]})}function Tn({dashboard:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:o=!1,onLoadDashboard:l,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:u,formatDate:m,onDashboardItemClick:h}){var C,v,T;const{selectDashboard:p}=s.useManagementActions(),g=s.useIsDashboardSelected(t.id),{isConsoleMode:j}=s.useDashboardPreferences(),[x,b]=A.useState(!1),[f,N]=A.useState(!1),k=s.useDashboardStore(y=>y.actions.setIsDashboardPanelOpen);A.useEffect(()=>{a?(b(!0),N(!0)):f&&(b(!1),N(!1))},[a,f]);const I=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4"}),S=()=>{p(t),l(t.id),h==null||h(t.id)};return e.jsx(s.Card,{className:s.cn("group p-3 hover:bg-accent/50 transition-colors cursor-pointer border-border/50",g&&"ring-1 ring-primary"),onClick:S,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 p-1.5 rounded bg-muted",children:I()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-foreground",value:t.title,onSave:y=>c==null?void 0:c(t.id,{title:y}),isEditable:t.permissions.canEdit&&g,isPending:r,placeholder:"Untitled Dashboard",displayClassName:"font-medium text-sm text-foreground truncate"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"h-2.5 w-2.5 mr-1"}),"Shared"]})]}),e.jsx(s.EditableText,{inputClassName:"text-xs text-muted-foreground line-clamp-2",value:t.description||"",onSave:y=>c==null?void 0:c(t.id,{description:y}),isEditable:t.permissions.canEdit&&g,isPending:o,placeholder:"No description",displayClassName:"text-xs text-muted-foreground line-clamp-2 mb-2"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsxs("span",{children:["Updated ",m(t.lastModified)]})]})]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-150 group-hover:opacity-100","ml-2 flex-shrink-0"),onClick:y=>y.stopPropagation(),children:e.jsxs(s.DropdownMenu,{modal:!1,open:x,onOpenChange:b,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.preventDefault(),y.stopPropagation(),d(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),u(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),i(t),k(!1)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((C=t.ownership.createdBy)==null?void 0:C.type)==="tenant"||((v=t.ownership.createdBy)==null?void 0:v.type)==="organization"&&j)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((T=t.ownership.createdBy)==null?void 0:T.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:m(t.lastModified)})]})]})]})]})})]})},t.id)}function kn({onRetry:t}){return e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load dashboards"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:t,children:"Retry"})]})})}function En(t){const[n,a]=A.useState(""),[r,o]=A.useState(!1),[l,c]=A.useState(""),[i,d]=A.useState(""),[u,m]=A.useState(!1),[h,p]=A.useState(null),[g,j]=A.useState(!1),[x,b]=A.useState(null),[f,N]=A.useState(null),k=s.useManagementStore(Y=>Y.lastSelectedDashboard),I=s.useManagementStore(Y=>Y.selectedDashboard),S=s.useManagementStore(Y=>Y.actions.selectDashboard),C=s.useManagementStore(Y=>Y.actions.clearSelectedDashboard),{tokenProps:v,id:T}=s.useSemaphorContext(),{permissions:y}=s.useRoleAwareDisplayPreferences(),{resources:O,isLoading:E,isError:B,createResource:w,updateResource:D,deleteResource:L,duplicateResource:F,isCreating:R,isDeleting:M}=s.useDashboardManagement(()=>{j(!1);const Y=x==null?void 0:x.id;b(null),(I==null?void 0:I.id)===Y&&(!(v!=null&&v.dashboard_id)&&!T?C():k&&k.id!==Y&&S(k))},()=>{o(!1),c(""),d("")}),{currentUser:P}=s.useCurrentUserInfo(),W=O.filter(Y=>{var re,oe;return((re=Y==null?void 0:Y.title)==null?void 0:re.toLowerCase().includes(n.toLowerCase()))||((oe=Y==null?void 0:Y.description)==null?void 0:oe.toLowerCase().includes(n.toLowerCase()))}),z=Y=>new Date(Y).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),X=()=>{l.trim()&&w({title:l,description:i,isPrivate:!1})},te=Y=>{var re;(re=t.onLoadDashboard)==null||re.call(t,Y)},K=Y=>{b(Y),j(!0)},H=()=>{x&&L(x.id)},U=Y=>{N(Y),F(Y,{onSettled:()=>N(null)})},{startUpdating:ee,stopUpdating:_,isUpdating:V}=s.useResourceUpdateState(),se=(Y,re)=>{const oe=re.title!==void 0?"title":"description";ee(Y,oe),D({resourceId:Y,data:re},{onSuccess:()=>{_(Y,oe)},onError:()=>{_(Y,oe)}})},ne=Y=>{const re=O.find(oe=>oe.id===Y);re&&D({resourceId:Y,data:{isPrivate:!re.isPrivate}})},G=Y=>{p(Y),P==null||P.type,m(!0)};return E?e.jsx(it,{}):B?e.jsx(kn,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[y.canCreateDashboards&&e.jsx("div",{className:"px-1",children:r?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Dashboard"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter dashboard title...",value:l,onChange:Y=>c(Y.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter dashboard description...",value:i,onChange:Y=>d(Y.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:X,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||R,children:R?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{o(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:R,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>o(!0),className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",disabled:R,children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),R?"Creating...":"Create New Dashboard"]})}),O&&O.length>5&&e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:n,onChange:Y=>a(Y.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:W.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"mb-3",children:e.jsx(s.ChartColumn,{className:"h-12 w-12 mx-auto text-muted-foreground/50"})}),e.jsx("h3",{className:"font-medium text-foreground mb-1",children:n?"No dashboards found":"No dashboards yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:n?"Try adjusting your search":y.canCreateDashboards?"Create your first dashboard to get started":"No dashboards have been shared with you yet"}),y.canCreateDashboards&&!n&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>o(!0),children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),"Create Dashboard"]})]}):W.map(Y=>e.jsx(Tn,{dashboard:Y,isDeleting:M,isDuplicating:f===Y.id,isTitleUpdating:V(Y.id,"title"),isDescriptionUpdating:V(Y.id,"description"),onLoadDashboard:te,onEditDashboard:t.onEditDashboard,onUpdateDashboard:se,onDeleteClick:K,onDuplicateDashboard:U,onTogglePrivacy:ne,onShareDashboard:G,formatDate:z,onDashboardItemClick:t.onDashboardItemClick},Y.id))})}),u&&h&&e.jsx(ls,{resource:h,resourceType:s.ResourceType.DASHBOARD,onClose:()=>{m(!1),p(null)}}),e.jsx(s.AlertDialog,{open:g,onOpenChange:Y=>{!Y&&M||(j(Y),Y||b(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Dashboard"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',x==null?void 0:x.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:M,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:Y=>{Y.preventDefault(),Y.stopPropagation(),H()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:M,children:M?"Deleting...":"Delete"})]})]})})]})}function bt({isOpen:t,onClose:n,className:a,onDashboardItemClick:r}){s.useDashboardStore(b=>b.dashboard);const{setDashboard:o,addSheet:l}=s.useDashboardStore(b=>b.actions),{currentUser:c}=s.useCurrentUserInfo(),i=c,{permissions:d}=s.useRoleAwareDisplayPreferences(),u=(d.canAccessVisuals,"dashboards"),[m,h]=s.useLocalStorageState("resource-management-active-tab",u),p=d.canAccessVisuals?m:"dashboards",g=mt(n,{enabled:t}),j=b=>{},x=b=>{console.log("Editing dashboard:",b)};return e.jsx(s.TooltipProvider,{children:e.jsxs("div",{ref:g,className:s.cn("absolute inset-y-0 left-0 z-[51] flex w-96 flex-col border-r bg-background shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"hidden -translate-x-full",a),children:[e.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[e.jsx("div",{className:"flex items-center gap-2",children:i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx("span",{className:"text-sm font-medium text-primary",children:i.name.charAt(0).toUpperCase()})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:i.name}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:d.canCreateDashboards?"default":"secondary",className:"text-xs cursor-help",children:d.canCreateDashboards?e.jsxs(e.Fragment,{children:[e.jsx(s.Users,{className:"h-3 w-3 mr-1"}),"Power User"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Eye,{className:"h-3 w-3 mr-1"}),"Viewer"]})})}),e.jsx(s.TooltipContent,{side:"bottom",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:i.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:i.email}),i.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role: ",s.toTitleCase(i.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",i.id]})]})})]})})]})]})}),e.jsx(s.IconButton,{className:"h-8 w-8 p-0 text-muted-foreground hover:text-foreground",onClick:n,tooltip:"Close panel",children:e.jsx(s.X,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:p,onValueChange:d.canAccessVisuals?h:void 0,className:"flex h-9 grow flex-col",children:[d.canAccessVisuals?e.jsx("div",{className:"px-4 pt-4",children:e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"text-sm",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"text-sm",children:"Visuals"})]})}):e.jsx("div",{className:"px-4 pt-4 pb-0",children:e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Dashboards"})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1 mt-4",children:e.jsx(En,{onLoadDashboard:j,onEditDashboard:x,onDashboardItemClick:r})}),d.canAccessVisuals&&e.jsx(s.TabsContent,{value:"visuals",className:"flex-1 mt-4",children:e.jsx(Dn,{})})]})})]})})}const In=async(t,n)=>await s.postRequestRegular("https://semaphor.cloud/api/management/v1/groups",t,n),An=async(t,n)=>{const a=`https://semaphor.cloud/api/management/v1/groups/${n}`,r=await fetch(a,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}});if(!r.ok){const o=await r.text();throw new Error(o||"Failed to delete group")}},Mn=async(t,n,a)=>{const r=`https://semaphor.cloud/api/management/v1/groups/${n}/members`;return await s.postRequestRegular(r,t,a)},Ln=async(t,n,a)=>{const r=`https://semaphor.cloud/api/management/v1/groups/${n}/members`,o=await fetch(r,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a)});if(!o.ok){const l=await o.text();throw new Error(l||"Failed to remove group members")}};function Rn(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient();return s.useMutation({mutationFn:a=>In((t==null?void 0:t.accessToken)||"",a),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),s.ue.success("Group created successfully")},onError:a=>{console.error("Failed to create group:",a),s.ue.error("Failed to create group",{description:a.message})}})}function On(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient();return s.useMutation({mutationFn:a=>An((t==null?void 0:t.accessToken)||"",a),onSuccess:(a,r)=>{n.invalidateQueries({queryKey:["groups"]}),n.removeQueries({queryKey:["group",r]}),s.ue.success("Group deleted successfully")},onError:a=>{console.error("Failed to delete group:",a),s.ue.error("Failed to delete group",{description:a.message})}})}function Fn(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient();return s.useMutation({mutationFn:({groupId:a,data:r})=>Mn((t==null?void 0:t.accessToken)||"",a,r),onSuccess:(a,r)=>{n.invalidateQueries({queryKey:["group",r.groupId]}),n.invalidateQueries({queryKey:["group-members",r.groupId]}),n.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members added successfully")},onError:a=>{console.error("Failed to add group members:",a),s.ue.error("Failed to add members",{description:a.message})}})}function Bn(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient();return s.useMutation({mutationFn:({groupId:a,data:r})=>Ln((t==null?void 0:t.accessToken)||"",a,r),onSuccess:(a,r)=>{n.invalidateQueries({queryKey:["group",r.groupId]}),n.invalidateQueries({queryKey:["group-members",r.groupId]}),n.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members removed successfully")},onError:a=>{console.error("Failed to remove group members:",a),s.ue.error("Failed to remove members",{description:a.message})}})}function Pn({onSuccess:t,tenantId:n,isTenantUser:a}){const[r,o]=A.useState(""),[l,c]=A.useState(""),[i,d]=A.useState({}),u=Rn(),m=()=>{const p={};return r.trim()?r.length<3?p.name="Group name must be at least 3 characters":r.length>50&&(p.name="Group name must be less than 50 characters"):p.name="Group name is required",l&&l.length>200&&(p.description="Description must be less than 200 characters"),d(p),Object.keys(p).length===0},h=async p=>{if(p.preventDefault(),!m())return;const g={name:r.trim(),description:l.trim()||void 0,type:a?"TENANT_GROUP":"ORG_GROUP",...a&&n?{tenantId:n}:{}};try{await u.mutateAsync(g),o(""),c(""),d({}),t()}catch(j){console.error("Failed to create group:",j)}};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:p=>{o(p.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:l,onChange:p=>{c(p.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:[l.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:()=>{o(""),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 zn({open:t,onOpenChange:n,group:a,onUpdate:r}){const[o,l]=A.useState("members"),[c,i]=A.useState(""),[d,u]=A.useState([]),[m,h]=A.useState([]),{data:p,isLoading:g,refetch:j}=s.useGroupMembers(a.id),x=a.type==="TENANT_GROUP"?"tenant":"organization",{users:b,isLoading:f}=s.useUnifiedUsers({type:x,tenantId:a.tenantId||void 0,active:!0,limit:100}),N=Fn(),k=Bn(),I=(p==null?void 0:p.members)||[],S=A.useMemo(()=>new Set(I.map(w=>w.userId)),[I]),C=A.useMemo(()=>b.filter(w=>!S.has(w.id)),[b,S]),v=A.useMemo(()=>{if(!c)return C;const w=c.toLowerCase();return C.filter(D=>{var L,F;return((L=D.name)==null?void 0:L.toLowerCase().includes(w))||((F=D.email)==null?void 0:F.toLowerCase().includes(w))})},[C,c]),T=A.useMemo(()=>{if(!c)return I;const w=c.toLowerCase();return I.filter(D=>{var L,F,R,M;return((F=(L=D.user)==null?void 0:L.name)==null?void 0:F.toLowerCase().includes(w))||((M=(R=D.user)==null?void 0:R.email)==null?void 0:M.toLowerCase().includes(w))})},[I,c]),y=async()=>{if(d.length!==0)try{await N.mutateAsync({groupId:a.id,data:{userIds:d,userType:x==="tenant"?"tenant":"org"}}),u([]),l("members"),j(),r==null||r()}catch(w){console.error("Failed to add members:",w)}},O=async()=>{if(m.length!==0)try{await k.mutateAsync({groupId:a.id,data:{userIds:m}}),h([]),j(),r==null||r()}catch(w){console.error("Failed to remove members:",w)}},E=w=>{u(D=>D.includes(w)?D.filter(L=>L!==w):[...D,w])},B=w=>{h(D=>D.includes(w)?D.filter(L=>L!==w):[...D,w])};return e.jsx(e.Fragment,{children:e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-3xl max-h-[80vh]","aria-describedby":"group-members-description",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:a.name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[I.length," ",I.length===1?"member":"members"]})}),e.jsxs("p",{id:"group-members-description",className:"sr-only",children:["Add or remove members from the ",a.name," group"]})]}),e.jsxs(s.Tabs,{value:o,onValueChange:w=>{l(w),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:w=>i(w.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(w=>e.jsx(s.Skeleton,{className:"h-16 w-full"},w))}):T.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:T.map(w=>e.jsx(_n,{member:w,selected:m.includes(w.userId),onToggle:()=>B(w.userId)},w.id))})}),m.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[m.length," member",m.length!==1?"s":""," selected"]}),e.jsx(s.Button,{variant:"destructive",size:"sm",onClick:O,disabled:k.isPending,children:k.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:w=>i(w.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(w=>e.jsx(s.Skeleton,{className:"h-16 w-full"},w))}):v.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(es,{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(w=>e.jsx(Vn,{user:w,selected:d.includes(w.id),onToggle:()=>E(w.id)},w.id))})}),d.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[d.length," user",d.length!==1?"s":""," selected"]}),e.jsx(s.Button,{onClick:y,disabled:N.isPending,children:N.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Adding..."]}):e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"mr-2 h-4 w-4"}),"Add Members"]})})]})]})]})]})})})}function _n({member:t,selected:n,onToggle:a}){var o,l,c,i;const r=((l=(o=t.user)==null?void 0:o.name)==null?void 0:l.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 Vn({user:t,selected:n,onToggle:a}){var o;const r=((o=t.name)==null?void 0:o.split(" ").map(l=>l[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 Gn({open:t,onOpenChange:n}){const[a,r]=A.useState("groups"),[o,l]=A.useState(""),[c,i]=A.useState(null),[d,u]=A.useState(!1),[m,h]=A.useState(null),{tokenProps:p}=s.useSemaphorContext(),{currentUser:g}=s.useCurrentUserInfo(),j=On(),x=(g==null?void 0:g.type)==="tenant",b=p==null?void 0:p.tenantId,{groups:f,isLoading:N,refetch:k}=s.useGroups({type:x?"TENANT_GROUP":"all",tenantId:x?b:void 0,includeMembers:!1}),I=f.filter(T=>{var y;return T.name.toLowerCase().includes(o.toLowerCase())||((y=T.description)==null?void 0:y.toLowerCase().includes(o.toLowerCase()))}),S=async()=>{if(m)try{await j.mutateAsync(m.id),h(null),k()}catch(T){console.error("Failed to delete group:",T)}},C=T=>{i(T),u(!0)},v=()=>{r("groups"),k()};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]","aria-describedby":"group-management-description",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("p",{id:"group-management-description",className:"sr-only",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:o,onChange:T=>l(T.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[400px]",children:N?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(T=>e.jsx(s.Skeleton,{className:"h-24 w-full"},T))}):I.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.Users,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:"No groups found"}),e.jsx("p",{className:"text-xs mt-1",children:o?"Try a different search":"Create your first group to get started"})]}):e.jsx("div",{className:"space-y-3",children:I.map(T=>e.jsx(Un,{group:T,onManageMembers:()=>C(T),onDelete:()=>h(T),currentUserId:g==null?void 0:g.id},T.id))})})]})}),e.jsx(s.TabsContent,{value:"create",className:"mt-4",children:e.jsx(Pn,{onSuccess:v,tenantId:b,isTenantUser:x})})]})]})}),c&&e.jsx(zn,{open:d,onOpenChange:u,group:c,onUpdate:()=>k()}),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:S,disabled:j.isPending,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:j.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Deleting..."]}):"Delete Group"})]})]})})]})}function Un({group:t,onManageMembers:n,onDelete:a,currentUserId:r}){const o=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(es,{className:"h-4 w-4"})}),o&&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 Yn(){var $,J,Z;const{authToken:t,tokenProps:n,id:a}=s.useSemaphorContext(),{isLocalDev:r}=s.useDashboardPreferences(),{permissions:o}=s.useRoleAwareDisplayPreferences(),l=s.useHasDashboardId();s.useDashboardStore(q=>q.theme);const c=s.useDashboardStore(q=>q.lenses),i=s.useDashboardStore(q=>q.selectedLensId),d=c==null?void 0:c.find(q=>q.id===i),u=s.useDashboardStore(q=>q.dashboard);s.useDashboardStore(q=>q.selectedSheetId);const m=s.useDashboardStore(q=>q.isDashboardEditing),h=s.useEditorStore(q=>q.card),p=s.useEditorStore(q=>q.selectedConnectionId),[g,j]=A.useState(!1),[x,b]=A.useState(!1),[f,N]=A.useState(!1),k=s.useDashboardStore(q=>q.isDashboardPanelOpen),I=s.useDashboardStore(q=>q.actions.setIsDashboardPanelOpen),S=s.useDashboardStore(q=>q.filterValues),C=s.useDashboardStore(q=>q.isVisualEditing),v=s.useManagementStore(q=>q.selectedDashboard),T=s.useManagementStore(q=>q.initialDashboard),y=v?(J=v==null?void 0:v.permissions)==null?void 0:J.canEdit:($=T==null?void 0:T.permissions)==null?void 0:$.canEdit,O=s.useDashboardStore(q=>q.showFilters),E=s.useDashboardStore(q=>q.showDashboardJSON),B=s.useDashboardStore(q=>q.onSaveFunction),w=s.useDashboardStore(q=>q.actions.setShowFilters),{addFrame:D,setSelectedFrameId:L}=s.useDashboardStore(q=>q.actions),{getSelectedSheet:F,setIsDashboardEditing:R,setShowDashboardJSON:M}=s.useDashboardStore(q=>q.actions),P=F(),{setInitialDashboard:W,clearSelectedDashboard:z}=s.useManagementStore(q=>q.actions),{resources:X}=s.useResourceManagement(s.ResourceType.DASHBOARD),{currentUser:te}=s.useCurrentUserInfo(),K=s.canUserManageGroups(te),H=v||T,U=H?{id:H.id,title:(u==null?void 0:u.title)||H.title||"Dashboard"}:null;A.useEffect(()=>{if(X&&X.length>0){const q=u==null?void 0:u.id;if(q){const ae=X.find(ie=>ie.id===q);ae&&W(ae)}}},[X,u==null?void 0:u.id,W]);const ee=n.orgUserId||n.tenantId,_=m&&!C&&ee&&y;function V(){var ce,Ee;const q=h.dataSource;if(q)return q;const ae=(Ee=(ce=u.aiContext)==null?void 0:ce.selectedEntities)==null?void 0:Ee[0],ie=ae==null?void 0:ae.type;if(ae)return{connectionId:ae.connectionId,connectionType:ae.connectionType,type:ie,selectedEntities:[ae]}}const se=()=>{if(!m||!P)return;const ae={dataSource:V(),mode:"explorer",connectionId:p,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},ie={id:s.v4(),cards:[ae],activeCardId:ae.id};D(P.id,ie),L(ie.id)},ne=()=>{R(!0)},[G,Y]=A.useState(!1),re=s.useUpdateResource(s.ResourceType.DASHBOARD);async function oe(){const q=ss(u);Y(!0);const ae={template:q};re.mutate({resourceId:q.id,data:ae},{onSuccess:()=>{Y(!1),s.ue.success("Dashboard saved!")},onError:()=>{Y(!1),s.ue.error("Failed to save dashboard")}})}async function le(){if(j(!0),!i||!d)return;const q=ss(u),ae=JSON.stringify(q),ie={...d,template:ae,filterValues:S};await vs(ie,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),B==null||B(q),j(!1)}if(C)return null;const xe=(d==null?void 0:d.name)||u.title,me=X&&X.length>0&&(n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail),fe=v&&!(n!=null&&n.dashboard_id)&&!a;return e.jsxs("div",{className:"flex h-10 items-center justify-between gap-2 border-b py-2 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[me&&e.jsxs(e.Fragment,{children:[fe&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Back to Dashboard Hub",onClick:()=>z(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})}),e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:l?"Manage Dashboards":"Select a dashboard to continue",onClick:()=>I(!0),className:"h-7 p-2",buttonProps:{disabled:!l},children:e.jsx(Ea,{className:"h-4 w-4"})})]}),!C&&l&&e.jsx(s.Label,{children:xe})]}),e.jsxs("div",{className:"flex gap-2",children:[r&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:s.invalidateToken,className:"h-7 p-2",children:e.jsx(_a,{className:"h-4 w-4"})}),!C&&l&&e.jsx(en,{}),!C&&l&&e.jsx(ot,{}),!C&&l&&K&&e.jsx(s.IconButton,{tooltip:"Manage Groups",onClick:()=>N(!0),className:"h-7 p-2",children:e.jsx(s.Users,{className:"h-4 w-4"})}),!C&&l&&((Z=H==null?void 0:H.permissions)==null?void 0:Z.canShare)&&e.jsx(s.IconButton,{tooltip:"Share Dashboard",onClick:()=>b(!0),className:"h-7 p-2",children:e.jsx(es,{className:"h-4 w-4"})}),m&&!C&&ee&&r&&l&&e.jsx(Xa,{}),!C&&ee&&r&&l&&e.jsx(Za,{}),m&&!C&&ee&&d&&r&&l&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:g,onClick:le,size:"sm",children:[e.jsx(bs,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),m&&!C&&l&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!m,onClick:se,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!C&&!m&&o.canEdit&&l&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:ne,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),m&&!C&&l&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{R(!1),M(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),_&&l&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"outline",disabled:G,onClick:oe,size:"sm",children:[G?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(bs,{className:"mr-2 h-4 w-4"}),G?"Saving...":"Save"]}),!O&&!C&&m&&o.canUseFilters&&l&&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&&m&&r&&l&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>M(!E),size:"sm",variant:"ghost",children:e.jsx(_e,{className:"h-4 w-4"})})}),!C&&r&&e.jsx(Wa,{}),!C&&e.jsx(bt,{isOpen:k,onClose:()=>I(!1)}),x&&U&&e.jsx(ls,{resource:U,resourceType:s.ResourceType.DASHBOARD,onClose:()=>b(!1)}),e.jsx(Gn,{open:f,onOpenChange:N})]})]})}function $n({name:t,items:n,value:a,onChange:r,isLoading:o,isError:l,refetch:c,className:i,icon:d,showNone:u=!1}){const m=Ie.useRef(null),[h,p]=Ie.useState(!1),[g,j]=Ie.useState("100%"),x=u?[...n||[],{id:"none",name:"None"}]:n;Ie.useLayoutEffect(()=>{m.current&&j(m.current.offsetWidth)},[]);function b(){var N;return o?"Loading...":l?"Error":a?(N=n==null?void 0:n.find(k=>k.id===a))==null?void 0:N.name:`Select ${t}`}function f(N,k){r(k),p(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:p,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:b()})]}),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(at,{className:s.cn("size-3.5 opacity-50",o&&"animate-spin")})})]}),e.jsxs(s.CommandList,{children:[e.jsxs(s.CommandEmpty,{children:["No ",t==null?void 0:t.toLowerCase()," found."]}),e.jsx(s.CommandGroup,{children:x==null?void 0:x.map(N=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:N.name,onSelect:k=>f(k,N.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",a===N.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:N.name,children:N.name})]})},N.id))})]})]})})]})}function Pe({title:t,items:n,value:a,isLoading:r,isError:o,refetch:l,onChange:c,showNone:i=!1,className:d,disabled:u=!1,type:m="combobox"}){const h=r?"Loading...":o?"Error":a;function p(){if(t==="Connection")return e.jsx(Ba,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Ra,{className:"size-4"});if(t==="Table")return e.jsx(s.Table2,{className:"size-4"});if(t==="Model")return e.jsx(ia,{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...":o?"Error":`Select ${t}`})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[r?e.jsx(s.SelectLabel,{children:"Loading..."}):e.jsxs(s.SelectLabel,{className:"flex items-center justify-between gap-2",children:[t,e.jsx(at,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:l})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),n&&n.map((x,b)=>e.jsx(s.SelectItem,{value:x.id,children:x.name},b))]}),(r||o)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function j(){return e.jsx($n,{icon:p(),items:n,value:h,onChange:c||(()=>{}),isLoading:r,isError:o,refetch:l,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():j()})})}function qn({column:t}){const[n,a]=A.useState(!1),r=s.useEditorStore(x=>x.selectedTableName),o=s.useEditorStore(x=>x.selectedSchemaName),l=s.useEditorStore(x=>x.selectedDatabaseName),c=s.useEditorStore(x=>x.selectedDatamodelId),i=s.useEditorStore(x=>x.sqlGen),{modelItems:d,connectionType:u}=s.useEditorAside(),m=s.useEditorStore(x=>x.actions.setSqlGen),h=s.useEditorStore(x=>x.actions.setCardSql),p=s.useEditorStore(x=>x.actions.setRunSql);function g(x,b){var I;const f=s.createSqlGenConfig(x,i,b),N=(I=d==null?void 0:d.find(S=>S.id===c))==null?void 0:I.name;m(f);const k=s.getSql(f,s.fmt(o||""),s.fmt(r),N||"",u,l||"");k&&(h(k),p(!0)),a(!1)}function j(){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:j()})]})}function Hn({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Re,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(_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($e,{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(We,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})}function ds({column:t,className:n}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center gap-2 px-3 py-[6px] text-sm",n),children:[e.jsx(Hn,{dataType:t.data_type}),e.jsx("span",{children:t.column_name})]})}function Wn({id:t,children:n,type:a="column"}){const{attributes:r,listeners:o,setNodeRef:l,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:l,style:i,...o,...r,children:n})}function Kn({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}),o=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.metricColumns}),l=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.filterColumns});function c(m){return i(m)||d(m)||u(m)}function i(m){return r==null?void 0:r.some(h=>h.name===m.column_name)}function d(m){return o==null?void 0:o.some(h=>h.name===m.column_name)}function u(m){return l==null?void 0:l.some(h=>h.name===m.column_name)}return e.jsxs("div",{onClick:()=>t(n),className:s.cn("group relative grow cursor-pointer overflow-x-hidden overflow-y-hidden border border-dashed border-background transition-colors hover:bg-muted/50",{"bg-muted":c(n)}),children:[a===n.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(ds,{column:n,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),a===n.column_name&&e.jsx("div",{className:"absolute inset-0",children:a===n.column_name&&e.jsx(ds,{column:n})}),e.jsx(Wn,{id:n.column_name,type:"column",children:e.jsx(ds,{column:n})})]})}const us={id:"__placeholder__",role:"groupby",type:"string"},ms={id:"__placeholder__",role:"groupby",type:"string"},hs={id:"__placeholder__",role:"metric",type:"number"},xs={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},vt={id:"__placeholder__"},Ae="droppable-group-by",Me="droppable-metrics",Le="droppable-pivot-by",as="sortable-group-by",ys="sortable-metrics",ns="sortable-pivot-by",Ns="droppable-filters",Cs="sortable-filters",Ts="sortable-order-by";function Qn(){const t=s.useDndStore(D=>D.insertIndex),n=s.useEditorStore(D=>{var L;return((L=D.card.queryConfig)==null?void 0:L.groupByColumns)||[]}),a=s.useEditorStore(D=>{var L;return((L=D.card.queryConfig)==null?void 0:L.metricColumns)||[]}),r=s.useEditorStore(D=>{var L;return((L=D.card.queryConfig)==null?void 0:L.filterColumns)||[]}),o=s.useEditorStore(D=>{var L;return((L=D.card.queryConfig)==null?void 0:L.orderBy)||[]}),l=s.useEditorStore(D=>{var L;return((L=D.card.queryConfig)==null?void 0:L.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:u,setPreviewFilterColumns:m,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:p,setMetricColumns:g,setFilterColumns:j,setOrderByColumns:x,setPivotByColumns:b}=s.useEditorActions(),{columns:f}=s.useDataColumns(),{formattedTableName:N}=s.useEditorAside(),k=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),I=D=>{var R;const{active:L,over:F}=D;if(((R=L.data.current)==null?void 0:R.type)==="column"&&F){const M=F.id,P=f.find(te=>te.column_name===L.id);if(!P)return;const W=s.isNumberDataType(P.data_type),z=s.isTextDataType(P.data_type),X=s.isDateDataType(P.data_type);if(z||X){if(n.some(K=>K.id===M)){const K=n.findIndex(U=>U.id===M);c(K);const H=n.filter(U=>U.id!==us.id);H.splice(K,0,us),d(H)}else if(F.id===Ae){c(n.length);const K=[...n,us];d(K),u(a),m(r)}}if(z||X){if(l.some(K=>K.id===M)){const K=l.findIndex(U=>U.id===M);c(K);const H=l.filter(U=>U.id!==ms.id);H.splice(K,0,ms),h(H)}else if(F.id===Le){c(l.length);const K=[...l,ms];h(K),d(n),u(a),m(r)}}if(W||z){if(a.some(K=>K.id===M)){console.log("isOverMetricSortable",M);const K=a.findIndex(U=>U.id===M);c(K);const H=a.filter(U=>U.id!==hs.id);H.splice(K,0,hs),u(H)}else if(F.id===Me){c(a.length);const K=[...a,hs];u(K),m(r),d(n),h(l)}}if(C(P)){if(r.some(K=>K.id===M)){const K=r.findIndex(U=>U.id===M);c(K);const H=r.filter(U=>U.id!==xs.id);H.splice(K,0,xs),m(H)}else if(F.id===Ns){c(r.length);const K=[...r,xs];m(K),u(a),d(n),h(l)}}}else d(n),u(a),m(r),h(l)};function S(D){i(D.active.id),c(null),d(n),u(a),m(r),h(l)}function C(D){return!r.some(L=>L.name===D.column_name)}function v(D,L="SUM"){const{column_name:F,data_type:R}=D,M=[...a],P=t!==null?t:a.length,W={...D,id:Ne(F),name:F,label:He(F,L),type:R,role:"metric",aggregate:L};M.splice(P,0,W),g(M)}function T(D){const L=s.isTextDataType(D.data_type);s.isDateDataType(D.data_type);const F=[...l],R=t!==null?t:l.length;let M;L?M={...D,id:Ne(D.column_name),name:D.column_name,type:D.data_type,role:"groupby"}:M={...D,id:Ne(D.column_name),name:D.column_name,type:D.data_type,role:"groupby",label:Ge(D.column_name,"month"),granularity:"month"},F.splice(R,0,M),b(F)}function y(D){const L=s.isTextDataType(D.data_type);s.isDateDataType(D.data_type);const F=[...n],R=t!==null?t:n.length;let M;L?M={...D,id:Ne(D.column_name),name:D.column_name,type:D.data_type,role:"groupby"}:M={...D,id:Ne(D.column_name),name:D.column_name,type:D.data_type,role:"groupby",label:Ge(D.column_name,"month"),granularity:"month"},F.splice(R,0,M),p(F)}function O(D){const L=[...r],F=t!==null?t:r.length,R={...D,id:Ne(D.column_name),name:D.column_name,type:D.data_type,sql:s.getDefaultFilterSql(D.data_type,N,s.fmt(D.column_name)),role:"filter"};L.splice(F,0,R),j(L)}function E(D){var M,P,W,z,X,te,K,H;const{active:L,over:F}=D,R=L.data.current;if((R==null?void 0:R.type)==="column"&&F){const U=f.find(se=>se.column_name===L.id);if(!U)return;const ee=s.isNumberDataType(U.data_type),_=s.isTextDataType(U.data_type),V=s.isDateDataType(U.data_type);(_||V)&&(F.id===Ae||((M=F.data.current)==null?void 0:M.type)===as)&&y(U),(_||V)&&(F.id===Le||((P=F.data.current)==null?void 0:P.type)===ns)?T(U):(ee||_)&&(F.id===Me||((W=F.data.current)==null?void 0:W.type)===ys)?(ee&&v(U),_&&v(U,"COUNT")):C(U)&&(F.id===Ns||((z=F.data.current)==null?void 0:z.type)===Cs)&&O(U)}if(F&&((X=F.data.current)==null?void 0:X.type)===as&&n.some(U=>U.id===L.id)){const U=n.findIndex(_=>_.id===L.id),ee=n.findIndex(_=>_.id===F.id);if(U!==-1&&ee!==-1&&U!==ee){const _=[...n],[V]=_.splice(U,1);_.splice(ee,0,V),p(_)}}if(F&&((te=F.data.current)==null?void 0:te.type)===ns&&l.some(U=>U.id===L.id)){const U=l.findIndex(_=>_.id===L.id),ee=l.findIndex(_=>_.id===F.id);if(U!==-1&&ee!==-1&&U!==ee){const _=[...l],[V]=_.splice(U,1);_.splice(ee,0,V),b(_)}}if(F&&((K=F.data.current)==null?void 0:K.type)===ys&&a.some(U=>U.id===L.id)){const U=a.findIndex(_=>_.id===L.id),ee=a.findIndex(_=>_.id===F.id);if(U!==-1&&ee!==-1&&U!==ee){const _=[...a],[V]=_.splice(U,1);_.splice(ee,0,V),g(_)}}if(F&&((H=F.data.current)==null?void 0:H.type)===Cs&&r.some(U=>U.id===L.id)){const U=r.findIndex(_=>_.id===L.id),ee=r.findIndex(_=>_.id===F.id);if(U!==-1&&ee!==-1&&U!==ee){const _=[...r],[V]=_.splice(U,1);_.splice(ee,0,V),j(_)}}B(D),i(null),c(null),d(n),u(a),m(r),h(l)}function B(D){const{active:L,over:F}=D,R=L.data.current;if((R==null?void 0:R.type)===Ts&&F){const M=o.findIndex(W=>Ye(W.columnId)===L.id),P=o.findIndex(W=>Ye(W.columnId)===F.id);if(M!==-1&&P!==-1&&M!==P){const W=[...o],[z]=W.splice(M,1);W.splice(P,0,z),x(W)}}}function w(){i(null),c(null),d(n),u(a),m(r)}return{handleDragOver:I,handleDragEnd:E,handleDragStart:S,handleDragCancel:w,sensors:k}}function Ne(t){return`${t}-${s.v4()}`}function He(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 Ye(t){return`${Ts}-${t}`}function Ge(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 Jn({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Re,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(_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($e,{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(We,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})}function Xn({schemaName:t,tableName:n,columns:a,status:r}){const[o,l]=A.useState(""),[c,i]=A.useState("all"),d=s.useEditorStore(M=>M.sqlGen),u=s.useEditorStore(M=>M.isDevMode);s.useEditorStore(M=>M.selectedConnectionId);const m=s.useEditorStore(M=>{var P,W;return(W=(P=M.card)==null?void 0:P.queryConfig)==null?void 0:W.metricColumns});s.useEditorStore(M=>{var P,W;return(W=(P=M.card)==null?void 0:P.queryConfig)==null?void 0:W.groupByColumns});const h=s.useEditorStore(M=>M.selectedDatabaseName);s.useEditorStore(M=>M.selectedSchemaName),s.useEditorStore(M=>M.selectedTableName);const p=s.useEditorStore(M=>M.selectedDatamodelId);s.useDashboardStore(M=>M.dashboard.aiScopeTables);const{addToAIScope:g,removeFromAIScope:j}=s.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:b,setCardSql:f,setRunSql:N,setSqlGen:k,setIsShowingVisual:I}=s.useEditorActions(),{connectionType:S,modelItems:C,selectedDatamodelName:v}=s.useEditorAside();function T(M){var P;if(u){const W=s.createSqlGenConfig(M,d);k(W);const z=(P=C==null?void 0:C.find(te=>te.id===p))==null?void 0:P.name,X=s.getSql(W,s.fmt(t),s.fmt(n),z||"",S,h||"");X&&(f(X),N(!0))}if(!u){if(s.isTextDataType(M.data_type))if(m&&m.length>0){const W={...M,role:"groupby",id:Ne(M.column_name),name:M.column_name,type:M.data_type};b(W)}else{const W={...M,role:"metric",id:Ne(M.column_name),name:M.column_name,label:He(M.column_name,"COUNT"),type:M.data_type,aggregate:"COUNT"};x(W)}if(s.isDateDataType(M.data_type)){const W={...M,role:"groupby",id:Ne(M.column_name),name:M.column_name,type:M.data_type,label:Ge(M.column_name,"month"),granularity:"month"};b(W)}if(s.isNumberDataType(M.data_type)){const W={...M,role:"metric",id:Ne(M.column_name),name:M.column_name,label:He(M.column_name,"SUM"),type:M.data_type,aggregate:"SUM"};x(W)}}}function y(){const M=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:S,databaseName:h||""});I(!1);const P=S==="MSSQL"?`SELECT top 10 * FROM ${M}`:`SELECT * FROM ${M} LIMIT 10`;f(P),N(!0)}function O(){const M=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:S,databaseName:h||""});f(`SELECT COUNT(*) as count FROM ${M}`),N(!0)}const E=(a==null?void 0:a.filter(M=>M.column_name.toLowerCase().includes(o.toLowerCase())))||[],B=M=>s.isNumberDataType(M.data_type)?"number":"text",w=c==="all"?E:E.filter(M=>B(M)===c),D=E.filter(M=>B(M)==="text").length,L=E.filter(M=>B(M)==="number").length;function F(M){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:()=>T(M),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Jn,{dataType:M.data_type}),e.jsx("span",{children:M.column_name})]}),e.jsx("div",{onClick:P=>P.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(M.data_type)&&e.jsx(qn,{column:M})})]}):e.jsx(Kn,{onClick:T,column:M})}function R(){return e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:r!=="Success",onClick:y,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(ka,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:O,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(nt,{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((M,P)=>e.jsx(s.Skeleton,{className:"h-8 w-full"},P))}):e.jsxs("div",{className:"flex grow flex-col",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-4",children:[u&&e.jsx("div",{className:"flex items-center justify-center gap-2",children:R()}),a&&a.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:o,onChange:M=>l(M.target.value)})]}),E.length>0&&e.jsx(s.Tabs,{defaultValue:"all",value:c,onValueChange:M=>i(M),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:E.length})]}),e.jsxs(s.TabsTrigger,{value:"text",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:D})]}),e.jsxs(s.TabsTrigger,{value:"number",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:L})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-4 pt-3",children:[w.length===0&&o&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',o,'"']}),w.length===0&&!o&&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:w==null?void 0:w.map(M=>e.jsx("div",{children:F(M)},M.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function yt({ColumnsComponent:t,type:n}){var J;const[a,r]=A.useState(!1),o=s.useEditorStore(Z=>Z.card),l=s.useEditorStore(Z=>Z.selectedConnectionId),c=s.useDashboardStore(Z=>Z.showFilters),i=s.useEditorStore(Z=>Z.selectedDatamodelId),d=s.useEditorStore(Z=>Z.selectedDatabaseName),u=s.useEditorStore(Z=>Z.selectedSchemaName),m=s.useEditorStore(Z=>Z.selectedTableName),h=s.useEditorStore(Z=>Z.isDevMode),{setSelectedTableName:p,setIsDevMode:g,setCardSql:j}=s.useEditorActions(),{connectionItems:x,modelItems:b,schemaItems:f,databaseItems:N,tableItems:k,columns:I,isConnectionsLoading:S,isModelsLoading:C,isConnectionsError:v,isModelsError:T,isDatabasesLoadingOrFetching:y,isDatabaseError:O,isSchemaLoadingOrFetching:E,isSchemaError:B,isColumnsError:w,isColumnsLoadingOrFetching:D,isTableLoadingOrFetching:L,isTableError:F,connectionType:R,isNonDbConnection:M,refetchDatabases:P,refetchModels:W,refetchSchemas:z,refetchTables:X,refetchColumns:te,refetchConnections:K,handleConnectionChange:H,handleDatabaseChange:U,handleSchemaChange:ee,handleDatamodelChange:_,handleTableChange:V,tableName:se,schemaName:ne}=s.useEditorAside(),{data:G,refetch:Y}=s.useDashboardCardQuery(o);function re(){return t?t(ne,se,I):e.jsx(Xn,{schemaName:ne,tableName:se,columns:I,status:D?"Loading...":w?"Error":"Success"})}function oe(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function le(Z){Z===!0?G&&(j(G.userSql),setTimeout(()=>{Y()},100)):j(""),g(Z)}function xe(){if(!l||R==="S3"||R==="API")return null;if(!i||i==="none")return e.jsx(Pe,{refetch:P,showNone:!0,onChange:U,isError:O,isLoading:y,items:N,value:d||"",title:"Database",type:"combobox"})}function pe(){if(l&&!M&&(!d||d==="none")&&(!i||i==="none"))return e.jsxs("div",{className:"grid grid-cols-3",children:[e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})})]})}function me(){if(!l||R==="S3"||R==="API")return null;if(!d||d==="none")return e.jsx(Pe,{refetch:W,showNone:!0,onChange:_,isError:T,isLoading:C,items:b,value:i||"",title:"Model",type:"combobox"})}function fe(){return!l||R==="S3"||R==="API"||!d||d==="none"?null:e.jsx(Pe,{refetch:z,onChange:ee,isError:B,isLoading:E,items:f,value:u||"",title:"Schema",type:"combobox"})}function $(){function Z(){let q=!1;return R==="API"?(q=!1,q):((R==="S3"||l&&d&&d!=="none"&&u)&&(q=!0),q)}return Z()?e.jsx(Pe,{refetch:X,onChange:V,isError:F,items:k,isLoading:L,value:m||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:s.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!c}),children:[e.jsxs("section",{className:s.cn("px-4",{"px-4 pb-0 pt-4":a,"px-4 py-4":!a}),children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Direct Source"}),e.jsx(s.Button,{onClick:()=>r(!a),size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:a?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),!a&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Pe,{refetch:K,items:x,title:"Connection",value:l||"",onChange:H,isLoading:S,isError:v,type:"combobox",connectionTooltip:((J=x==null?void 0:x.find(Z=>Z.id===l))==null?void 0:J.type)||""}),xe(),pe(),me(),fe(),$()]})]}),re(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:n==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:h,onCheckedChange:le,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:oe,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(Ia,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function Nt({error:t,errorSql:n,onSendFeedback:a,className:r,showFeedbackButton:o=!0}){const[l,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:l,onOpenChange:c,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:l?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"]})})})}),o&&a&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:a,children:[e.jsx(Ma,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),n&&e.jsx(s.Collapsible,{open:l,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 Ct({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){const o=s.useEditorStore(u=>u.isDevMode),{setIsDevMode:l,setCardSql:c,setRunSql:i}=s.useEditorActions();function d(){l(!o),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(Nt,{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"})})})]}),!o&&t&&!n&&e.jsxs(s.Button,{onClick:d,variant:"secondary",size:"sm",children:[e.jsx(ga,{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(Na,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function St({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(ua,{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(Ct,{errorSql:a,sql:t,error:n,onDebugWithAssistant:r})})]})}function Zn(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 wt(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(x=>x.theme),r=s.useEditorStore(x=>x.frame),o=s.useEditorStore(x=>x.card),l=s.useEditorStore(x=>x.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(o),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),m=A.useRef(),h=A.useRef({}),p=r.cards.find(x=>x.id===l),g=A.useCallback(()=>{let x="";return t==="python"&&(x=(p==null?void 0:p.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(x=(p==null?void 0:p.sql)||""),x},[t,p]);A.useEffect(()=>{if(l&&o.id&&o.id!==l){if(m.current&&c){const x=m.current.getModel();x&&(h.current[o.id]=x);let b=h.current[l];if(!b){const f=g();b=c.editor.createModel(f,t),h.current[l]=b}m.current.setModel(b)}d(l,o),u(!0)}},[l,o,d,c,u,t,g]),A.useEffect(()=>{if(!c)return;const x=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",b=a==="system"?x:a;c.editor.defineTheme("default",{base:b==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":b==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[n,a,c]),A.useEffect(()=>{const x=m.current;x&&c&&o&&x.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,o]);function j(x,b){if(m.current=x,!h.current[o.id]){const f=x.getModel(),N=g();h.current[o.id]=f||(b==null?void 0:b.editor.createModel(N,t))||x.getModel()}x.setModel(h.current[o.id])}return{handleEditorDidMount:j}}function er(){const t=s.useEditorStore(c=>c.card.sql),n=s.useEditorStore(c=>c.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:o}=wt("sql");function l(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:l,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:o})]})}function sr(){const t=s.useEditorStore(o=>o.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=wt("python");function r(o){n(o)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:a})}function tr({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 ks({variant:t="outline"}){var c;const{setCardSql:n}=s.useEditorActions();s.useEditorStore(i=>i.frame);const a=s.useEditorStore(i=>i.card);ws(((c=a.customCardPreferences)==null?void 0:c.url)||""),s.useEditorStore(i=>i.selectedSchemaName),s.useEditorStore(i=>i.selectedDatamodelId),s.useEditorStore(i=>i.selectedDatabaseName),s.useEditorStore(i=>i.selectedTableName),s.useEditorStore(i=>i.selectedConnectionId),s.useEditorStore(i=>i.isShowingVisual),a.sql;const r=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:o}=Ds();function l(){const i=o();r==null||r(i)}return e.jsxs(s.Button,{onClick:l,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function ar(){const t=s.useQueryClient(),[n,a]=A.useState(!1),r=s.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{setIsVisualEditing:o}=s.useDashboardActions(),{getUpdatedFrame:l}=Ds(),c=s.useSelectedVisual(),i=s.useUpdateVisualMutation(),d=()=>{const u=l();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}a(!0),i.mutate({visualId:c.id,data:{frameObject:u}},{onSuccess:()=>{a(!1),o(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{a(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:d,className:"h-8",size:"sm",children:[n&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!n&&e.jsxs(e.Fragment,{children:[e.jsx(bs,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function Es(){const{setTempQueryData:t,setSqlGen:n}=s.useEditorActions(),a=s.useQueryClient(),r=s.useEditorStore(d=>d.tempQueryData),o=s.useEditorStore(d=>d.onClose),l=s.useEditorStore(d=>d.card),{queryKey:c}=s.useDashboardCardQuery(l);function i(){if(r){const{queryKey:d,queryData:u}=r;d&&u&&a.setQueryData(d,u)}n({}),o==null||o()}return e.jsxs(s.Button,{onClick:i,className:"h-8",size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function os(){const{setTempQueryData:t}=s.useEditorActions(),n=s.useQueryClient(),a=s.useEditorStore(b=>b.isDevMode),r=s.useEditorStore(b=>b.tempQueryData),o=s.useEditorStore(b=>b.card),{queryKey:l}=s.useDashboardCardQuery(o),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:u,setCardPreferences:m,updateDataSource:h,clearQueryConfig:p,setCardConfig:g,setCardType:j}=s.useEditorActions();function x(){const b=n.getQueryData(l);r!=null&&r.queryData||t({queryKey:l,queryData:b}),n.setQueryData(l,null),n.removeQueries({queryKey:l,exact:!0}),a&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),p(),g(void 0),d(""),u(""),m({}),j("bar")}return e.jsxs(s.Button,{onClick:x,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function nr(){const t=s.useQueryClient(),[n,a]=A.useState(!1),[r,o]=A.useState(!1);s.useEditorStore(z=>z.frame);const l=s.useEditorStore(z=>z.card);s.useEditorStore(z=>z.isShowingVisual),s.useEditorStore(z=>z.selectedConnectionId),s.useEditorStore(z=>z.tempQueryData),s.useEditorStore(z=>z.selectedDatabaseName),s.useEditorStore(z=>z.selectedDatamodelId),s.useEditorStore(z=>z.selectedSchemaName);const c=s.useEditorStore(z=>z.showAIDialog);s.useEditorStore(z=>z.selectedTableName);const i=s.useEditorStore(z=>{var X;return(X=z==null?void 0:z.card)==null?void 0:X.sql}),d=s.useEditorStore(z=>{var X;return(X=z==null?void 0:z.card)==null?void 0:X.python}),{sheetFilterValues:u}=s.useSheetFilterValues(),{setCardCustomCfg:m,setQueryResultColumns:h,setCardSql:p,setTempQueryData:g,setPythonStdOut:j,setCardPreferences:x,setCardType:b,setCardPython:f,runAssistant:N,setShowAIDialog:k}=s.useEditorActions();s.useEditorStore(z=>z.onSave),s.useEditorStore(z=>z.onClose),s.useEditorStore(z=>z.actions.setSqlGen);const I=s.useEditorStore(z=>z.runSql),S=s.useEditorStore(z=>z.actions.setRunSql),C=s.useEditorStore(z=>z.actions.setIsSqlRunning),{data:v,isLoading:T,isFetching:y,isSuccess:O,isError:E,error:B,errorSql:w,queryKey:D,refetch:L,errorMessage:F}=s.useDashboardCardQuery(l);A.useEffect(()=>{if(v&&(v.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),j((v==null?void 0:v.output)||""),v.records.length>0)){const{dimensionKeys:z}=s.getKeys(v.records);h(z)}},[v,h,j]),A.useEffect(()=>{(T||y)&&C(!0),(E||O)&&C(!1),E&&(h([]),j(""))},[T,y,v,j,E,O,C,h,B]),A.useEffect(()=>{I&&(t.getQueryData(D)||L(),S(!1))},[I,L,S,D,t]);async function R(){const z=`Can you help me debug this query?
|
|
331
|
+
*/const Ha=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 Wa(){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(Ya,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(La,{strokeWidth:1.5,className:"absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),e.jsx("span",{className:"sr-only",children:"Toggle theme"})]})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuItem,{onClick:()=>{t("light"),n("light")},children:"Light"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("dark"),n("dark")},children:"Dark"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("system"),n("system")},children:"System"})]})]})}function ss(t){var n;return{...t,sheets:(n=t==null?void 0:t.sheets)==null?void 0:n.map(a=>{var r;return{...a,frames:(r=a.frames)==null?void 0:r.map(o=>{var l;return{...o,cards:(l=o.cards)==null?void 0:l.map(c=>lt(c))}})}})}}function lt(t){return{...t,customCfg:Ka(t.customCfg),data:[]}}function Ka(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 Qa(t,n,a,r){if(!r)return null;const o=JSON.stringify(n);return await s.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:t,template:o,filterValues:a,operation:"create"})}async function vs(t,n){if(!n)return null;const{id:a,template:r,filterValues:o,isDefault:l,shared:c}=t;return await s.postRequest("https://semaphor.cloud/api/v1/lens",n,{lensId:a,template:r,filterValues:o,isDefault:l,shared:c,operation:"update"})}async function Ja(t,n){return n?await s.postRequest("https://semaphor.cloud/api/v1/lens",n,{operation:"delete",lensId:t}):null}function Xa(){const[t,n]=A.useState(""),[a,r]=A.useState(!1),o=s.useDashboardStore(x=>x.lenses),{setLenses:l,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=A.useState(!1),[u,m]=A.useState(!1),h=s.useDashboardStore(x=>x.dashboard),p=s.useDashboardStore(x=>x.filterValues),{authToken:g}=s.useSemaphorContext();async function j(){d(!0);const x=ss(h),b=await Qa(t,x,p,g==null?void 0:g.accessToken);b&&(l([...o||[],b]),c(b.id),m(!1)),d(!1)}return e.jsxs(s.Dialog,{open:u,onOpenChange:m,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create Lens"}),e.jsx(s.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(s.Label,{className:"text-right",children:"Name"}),e.jsx(s.Input,{value:t,onChange:x=>{n(x.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:j,disabled:i,children:i?"Creating...":"Add"})})]})]})}function Za(){const[t,n]=A.useState(!1),a=s.useDashboardStore(m=>m.lenses),r=s.useDashboardStore(m=>m.selectedLensId),{setLenses:o,setSelectedLensId:l}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function i(m){l(m)}async function d(m){if(await Ja(m,c==null?void 0:c.accessToken)){const p=a==null?void 0:a.filter(g=>g.id!==m);o(p||[]),l("original")}}async function u(m){const h=a==null?void 0:a.map(j=>j.id===m.id?{...j,isDefault:!m.isDefault}:{...j,isDefault:!1});o(h||[]);const p={...m,isDefault:!m.isDefault};await vs(p,c==null?void 0:c.accessToken);const g=a==null?void 0:a.find(j=>j.isDefault);if(g&&g.id!==m.id){const j={...g,isDefault:!1};await vs(j,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(ya,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:i,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),a==null?void 0:a.map(m=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:m.id,children:[e.jsx("p",{children:m.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:h=>{h.preventDefault(),u(m)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!m.isDefault,"text-green-500":m.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:h=>{h.preventDefault(),d(m.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},m.id))]})]})]})}function en({iconClassName:t}){const[n,a]=A.useState(!1),[r,o]=A.useState(""),[l,c]=A.useState(!1),i=s.useDashboardStore(m=>m.isDownloadingPdf);async function d(){const m=s.ue.loading("Generating PDF... may take up to 60 seconds");try{await s.downloadPdf(),s.ue.dismiss(m),s.ue.success("PDF downloaded successfully!",{duration:2e3})}catch(h){s.ue.dismiss(m),s.ue.error("Failed to download PDF",{description:"Please try again or contact support.",richColors:!0}),console.error("PDF download error:",h)}}async function u(){if(!r)return;a(!1),o(""),c(!1);const m=s.ue.loading("Generating protected PDF... may take up to 60 seconds");try{await s.downloadPdf(r),s.ue.dismiss(m),s.ue.success("Protected PDF downloaded successfully!",{duration:2e3,position:"top-right"})}catch(h){s.ue.dismiss(m),s.ue.error("Failed to download protected PDF. Please try again."),console.error("Protected PDF download error:",h)}}return e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenu,{modal:!1,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:i,children:e.jsx(s.Download,{className:s.cn("size-4",t)})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsxs(s.DropdownMenuItem,{onClick:d,children:[e.jsx(s.File,{className:"mr-2 h-4 w-4"}),"Download PDF"]}),e.jsxs(s.DropdownMenuItem,{onClick:()=>a(!0),children:[e.jsx(Ta,{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:l?"text":"password",value:r,onChange:m=>o(m.target.value),placeholder:"Enter password",className:"pr-10",onKeyDown:m=>{m.key==="Enter"&&r&&u()}}),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(!l),children:l?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:u,disabled:!r,children:"Download"})]})]})})]})}function ot({triggerButtonClassName:t}){const[n,a]=A.useState(!1),[r,o]=A.useState("create"),[l,c]=A.useState("current"),i=s.useDashboardStore(S=>{var C;return(C=S.dashboard)==null?void 0:C.sheets}),d=s.useDashboardStore(S=>S.selectedSheetId),u=i==null?void 0:i.find(S=>S.id===d),m=i&&i.length>1,{schedules:h,isLoading:p,createSchedule:g,deleteSchedule:j,isSubmitting:x,submitError:b,deletingId:f,refetch:N}=s.useSchedule({reportType:"DASHBOARD",enabled:n}),k=async S=>{try{const C={format:"pdf",sheetSelection:l,pdfOptions:{pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0}};l==="current"&&u&&(C.currentSheetId=u.id,C.currentSheetName=u.title),await g({...S,reportParams:C}),o("active")}catch(C){console.error("Failed to create schedule:",C)}},I=async S=>{try{await j(S)}catch(C){console.error("Failed to delete schedule:",C)}};return e.jsxs(s.Popover,{open:n,onOpenChange:a,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Schedule Dashboard",className:s.cn("h-7 p-2",t),children:e.jsx(s.Clock,{className:"size-4"})})}),e.jsx(s.PopoverContent,{align:"end",className:"w-[520px] p-0",children:e.jsxs(s.Tabs,{value:r,onValueChange:S=>o(S),className:"w-full",children:[e.jsxs("div",{className:"border-b px-6 pb-3 pt-6",children:[e.jsxs("div",{className:"mb-4 space-y-1",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Dashboard"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage your dashboard and report schedules"})]}),e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsxs(s.TabsTrigger,{value:"create",className:"flex items-center gap-2",children:[e.jsx(s.Plus,{className:"h-4 w-4"}),"Create Schedule"]}),e.jsxs(s.TabsTrigger,{value:"active",className:"flex items-center gap-2",children:[e.jsx(tt,{className:"h-4 w-4"}),"Active Schedules",h&&h.length>0&&e.jsx(s.Badge,{variant:"secondary",className:"ml-1 h-5 px-1",children:h.length})]})]})]}),e.jsxs(s.TabsContent,{value:"create",className:"mt-0 max-h-[60vh] overflow-y-auto p-6",children:[m&&e.jsxs("div",{className:"mb-6 space-y-2",children:[e.jsx(s.Label,{children:"Sheet Selection"}),e.jsxs(s.RadioGroup,{value:l,onValueChange:S=>c(S),className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"current",id:"current-sheet"}),e.jsxs(s.Label,{htmlFor:"current-sheet",className:"flex cursor-pointer items-center font-normal",children:[e.jsx(s.FileText,{className:"mr-2 h-4 w-4"}),"Current sheet (",(u==null?void 0:u.title)||"Sheet",")"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"all",id:"all-sheets"}),e.jsxs(s.Label,{htmlFor:"all-sheets",className:"flex cursor-pointer items-center font-normal",children:[e.jsx(s.Files,{className:"mr-2 h-4 w-4"}),"All sheets (",i==null?void 0:i.length," sheets)"]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l==="current"?"Only the currently selected sheet will be included in the report":"All sheets in the dashboard will be included in the report"})]}),e.jsx(s.ScheduleForm,{reportType:"DASHBOARD",onSubmit:k,isSubmitting:x,submitError:b})]}),e.jsx(s.TabsContent,{value:"active",className:"mt-0 max-h-[60vh] overflow-y-auto p-6",children:h&&h.length>0?e.jsx(s.ScheduleManager,{schedules:h,onDelete:I,isDeleting:f,isLoading:p,onRefresh:N}):e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(s.Clock,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:"No active schedules"}),e.jsx("p",{className:"mt-1 text-xs",children:'Switch to the "Create Schedule" tab to add your first subscription'})]})})]})})]})}function it(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,n)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},n))})]})})}function sn({visual:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:o=!1,onAddVisual:l,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:u,onShareVisual:m,formatDate:h}){var C,v,T;const{selectVisual:p}=s.useManagementActions(),g=s.useIsVisualSelected(t.id),{isConsoleMode:j}=s.useDashboardPreferences(),x=s.useDashboardStore(y=>y.actions.setIsDashboardPanelOpen),[b,f]=A.useState(!1),[N,k]=A.useState(!1);A.useEffect(()=>{a?(f(!0),k(!0)):N&&(f(!1),k(!1))},[a,N]);const I=()=>e.jsx(rs,{className:"h-4 w-4"}),S=()=>{p(t),c==null||c(t)};return e.jsx(s.Card,{className:s.cn("group p-3 hover:bg-accent/50 transition-colors cursor-pointer border-border/50",g&&"ring-1 ring-primary"),onClick:S,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 p-1.5 rounded bg-muted",children:I()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-foreground",value:t.title,onSave:y=>i==null?void 0:i(t.id,{title:y}),isEditable:t.ownership.isOwner&&g,isPending:r,placeholder:"Untitled Visual",displayClassName:"font-medium text-sm text-foreground truncate"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"h-2.5 w-2.5 mr-1"}),"Shared"]})]}),e.jsx(s.EditableText,{inputClassName:"text-xs text-muted-foreground line-clamp-2",value:t.description||"",onSave:y=>i==null?void 0:i(t.id,{description:y}),isEditable:t.ownership.isOwner&&g,isPending:o,placeholder:"No description",displayClassName:"text-xs text-muted-foreground line-clamp-2 mb-2"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsxs("span",{children:["Updated ",h(t.lastModified)]})]})]}),e.jsxs("div",{className:s.cn("opacity-0 transition-opacity duration-150 group-hover:opacity-100","ml-2 flex-shrink-0 flex items-center gap-1"),onClick:y=>y.stopPropagation(),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:y=>{y.stopPropagation(),l(t)},title:"Add to dashboard",children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:b,onOpenChange:f,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),l(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.preventDefault(),y.stopPropagation(),u(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),c==null||c(t)},children:[e.jsx(Fa,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),m(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),d(t),x(!1)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((C=t.ownership.createdBy)==null?void 0:C.type)==="tenant"||((v=t.ownership.createdBy)==null?void 0:v.type)==="organization"&&j)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((T=t.ownership.createdBy)==null?void 0:T.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:h(t.lastModified)})]})]})]})]})]})]})},t.id)}function ts({value:t,onChange:n,placeholder:a="Search users by name, email, or department..."}){return e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:a,value:t,onChange:r=>n(r.target.value),className:"pl-9"})]})}function Oe({currentRole:t,onRoleChange:n,roleOptions:a,disabled:r=!1,className:o="",allowDropdown:l=!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 l?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${o}`,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 ${o}`,children:c})}function ct({selectedUsers:t,selectedUserObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:o}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(l=>a(l.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:n.map(l=>{const c=t.find(d=>d.id===l.id),i=o(l.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[l.name,e.jsx(Oe,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(l.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>a(l.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},l.id)})}),e.jsx(s.Separator,{})]})}function dt({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 ut({usersToUpdate:t,allUsers:n,onRemove:a,getRoleOptions:r}){if(t.length===0)return null;const o=r("tenant"),l=i=>{const d=n.find(u=>u.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=o.find(u=>u.value===i);return(d==null?void 0:d.label)||i};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(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:l(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>a(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function mt(t,n={}){const{enabled:a=!0,eventType:r="mousedown"}=n,o=A.useRef(null);return A.useEffect(()=>{const l=c=>{const i=c.target;o.current&&o.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return a&&document.addEventListener(r,l),()=>{document.removeEventListener(r,l)}},[t,a,r]),o}function ye(t,n){var a;return((a=n.find(r=>r.value===t))==null?void 0:a.label)||t}function tn(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function ht(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function an(t,n,a){const r=ht(t),o=(a==null?void 0:a.type)||"organization";if(!(!n||!n.shares))if(o==="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 nn({user:t}){return ht(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 rn({user:t,userShare:n,usersToUpdate:a,currentUser:r,getRoleOptions:o,handleUpdateAccess:l}){if(!(n!=null&&n.role))return null;const c=tn((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=o(t.type);return n?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(Oe,{currentRole:u,onRoleChange:h=>{l(t.id,n.role,h)},roleOptions:m,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:ye(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function ln({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(ze,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function on({isUserRemoving:t,isSelected:n,hasAccess:a,isRemoving:r,isSharing:o}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),n&&!a&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:o?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Sharing..."]}):"Will share"})]})}function cn({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((p,g)=>{var f,N;const j=((f=n.find(k=>k.id===p.orgUserId))==null?void 0:f.name)||"Unknown User",x=((N=n.find(k=>k.id===p.orgUserId))==null?void 0:N.type)||"",b=ye(p.role,a(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:j}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},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((p,g)=>{var f,N;const j=((f=n.find(k=>k.id===p.tenantUserId))==null?void 0:f.name)||"Unknown User",x=((N=n.find(k=>k.id===p.tenantUserId))==null?void 0:N.type)||"",b=ye(p.role,a(x));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:j}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},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((p,g)=>{const j=ye(p.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:j})]},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((p,g)=>{const j=ye(p.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:j})]},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((p,g)=>{const j=ye(p.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:j})]},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,j;const m=((g=n.find(x=>x.id===d.tenantUserId))==null?void 0:g.name)||"Unknown User",h=((j=n.find(x=>x.id===d.tenantUserId))==null?void 0:j.type)||"",p=ye(d.role,a(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:p})]},u)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:i.map((d,u)=>{const m=ye(d.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},u)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const l=t.shares.specificTenantUsers||[],c=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[l.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",l.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[l.slice(0,3).map((i,d)=>{var p,g;const u=((p=n.find(j=>j.id===i.tenantUserId))==null?void 0:p.name)||"Unknown User",m=((g=n.find(j=>j.id===i.tenantUserId))==null?void 0:g.type)||"",h=ye(i.role,a(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),l.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",l.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,d)=>{const u=ye(i.role,a(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},d)})})]}),!l.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function dn({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 un({user:t,userShare:n,isUserRemoving:a,hasAccess:r,hasAccessFromAPI:o,isSelected:l,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:h,handleUpdateAccess:p,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":l?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:o?!a:l,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{o?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(nn,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!a?e.jsx(Oe,{currentRole:n==null?void 0:n.role,onRoleChange:j=>p(t.id,n.role,j),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(rn,{user:t,userShare:n,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:p}),l&&!o&&e.jsx("div",{onClick:j=>j.stopPropagation(),children:e.jsx(Oe,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:j=>g(t.id,j),roleOptions:i,disabled:!1})})]})]}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:t.email}),e.jsx(ln,{hasAccess:r,isUserRemoving:a,isSelected:l,hasAccessFromAPI:o}),e.jsx(on,{isUserRemoving:a,isSelected:l,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function xt({existingShares:t,isInitialLoading:n,isSearching:a,getRoleOptions:r,allUsers:o=[],currentUser:l,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),g=s.useShareSearchQuery(),j=s.useShareManagementActions(),x=c||(S=>{const C=m.some(T=>T.id===S),v=h.includes(S);C?j.removeSelectedUser(S):v?j.removeUserFromRemove(S):j.addSelectedUser({id:S,role:"VIEWER"})}),b=i||j.updateSelectedUserRole,f=d||j.addUserToRemove,N=u||((S,C,v)=>{j.addUserToUpdate({id:S,currentRole:C,newRole:v})}),k=o,I=h;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["All Users (",(k??[]).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(cn,{existingShares:t,allUsers:o,getRoleOptions:r,currentUser:l})})]})})]}),(k==null?void 0:k.length)>0&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>{m.length===k.length?j.setSelectedUsers([]):j.setSelectedUsers(k.map(S=>({id:S.id,role:"VIEWER"})))},className:"h-auto p-1 text-xs",children:m.length===k.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(dn,{isInitialLoading:n,isSearching:a,searchQuery:g,availableUsers:k||[]}),!n&&!a&&(k==null?void 0:k.length)>0&&k.map(S=>{const C=t?an(S,t,l):void 0,v=I.includes(S.id),T=!!C,y=T&&!v,O=m.some(w=>w.id===S.id),E=m.find(w=>w.id===S.id),B=r(S.type);return e.jsx(un,{user:S,userShare:C,isUserRemoving:v,hasAccess:y,hasAccessFromAPI:T,isSelected:O,selectedUser:E,roleOptions:B,currentUser:l,usersToUpdate:p,handleUserToggle:x,handleRemoveAccess:f,handleUpdateAccess:N,handleUserRoleChange:b},S.id)})]})]})}function Ss({shareType:t,onShareTypeChange:n,currentUser:a,options:r}){const o=(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(l=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:l.value,id:l.value,className:"peer sr-only",disabled:l.disabled}),e.jsxs(s.Label,{htmlFor:l.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${l.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[l.icon||e.jsx(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:l.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l.description})]})]})]},l.value))}),!o&&r.some(l=>l.value==="all_users")&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only admins, authors, power users, and super admins can share with all users."})]})}const be=()=>[{value:"VIEWER",label:"Viewer",description:"Can view only"},{value:"EDITOR",label:"Editor",description:"Can view and edit"},{value:"CONTRIBUTOR",label:"Contributor",description:"Can view, edit, and share"},{value:"OWNER",label:"Owner",description:"Full access (view, edit, share, delete)"}];function mn({currentUser:t,currentShare:n,isSharing:a,onUpdateAccess:r,allUsersToUpdate:o=null,allUsersToRemove:l=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),u=be().filter(N=>N.value==="VIEWER"||N.value==="EDITOR"||N.value==="CONTRIBUTOR"),m=n.role!=="NONE"?n.role:"NONE",h=o?o.newRole:m,p=n.role!=="NONE"&&!l&&(!o||o.newRole===m),g=o!==null&&o.newRole!==m,j=l,x=m==="NONE"||!m,b=N=>{switch(N){case"VIEWER":return e.jsx(s.Eye,{className:"h-4 w-4"});case"EDITOR":return e.jsx(s.SquarePen,{className:"h-4 w-4"});case"CONTRIBUTOR":return e.jsx(za,{className:"h-4 w-4"});default:return e.jsx(s.Eye,{className:"h-4 w-4"})}},f=N=>{r(m,N)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",g&&!j&&!x?"border-orange-300 bg-orange-50":p?"border-green-300 bg-green-50":j||x?"border-destructive bg-destructive/10":""),children:[e.jsxs(s.CardHeader,{children:[e.jsxs(s.CardTitle,{className:"flex items-center gap-2 text-base",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Share with All"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="specificOrgUsers"?"Org":"Tenant"," ","Users",p&&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"}),(j||x)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:j||x?"No access for all users.":"This will share the dashboard with all users in your "+((t==null?void 0:t.type)==="organization"?"organization":"tenant")+". Select an access level below."})]}),e.jsx(s.CardContent,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Select Access Level:"}),e.jsxs(s.HoverCard,{children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-4 w-4 p-0 text-muted-foreground hover:text-foreground",children:e.jsx(s.Info,{className:"h-3 w-3"})})}),e.jsx(s.HoverCardContent,{className:"w-80",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Share with All Users"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["This action will share the dashboard with all users in your"," ",(t==null?void 0:t.type)==="organization"?"organization":"tenant",". Users will receive the selected access level."]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Viewer:"})," Can view the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Editor:"})," Can view and edit the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Contributor:"})," Can view, edit, and share the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"None:"})," No access for all users"]})]})]})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:u.map(N=>e.jsxs(s.Button,{variant:h===N.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>f(N.value),disabled:a||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[b(N.value),e.jsx("span",{className:"font-medium",children:N.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:N.description})]},N.value))})]})})]})})}function pt({currentUser:t,currentShare:n,isSharing:a,isUpdating:r,isRemoving:o,onUpdateAccess:l,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const u=x=>x==="OWNER"?"CONTRIBUTOR":x,h=n?{role:u(n.role)}:{role:"NONE"},p=i?{currentRole:u(i.currentRole),newRole:u(i.newRole)}:null,g=(x,b)=>{l(x,b)},j=()=>{c()};return e.jsx(mn,{currentUser:t,currentShare:h,isSharing:a,isUpdating:r,isRemoving:o,onUpdateAccess:g,onRemoveAccess:j,allUsersToUpdate:p,allUsersToRemove:d})}function Ve(t){const{debouncedSearchQuery:n,resourceId:a,resourceType:r=s.ResourceType.DASHBOARD,userType:o,tenantId:l}=t,c=A.useMemo(()=>({search:n,active:!0,...o?{type:o}:{},...o==="tenant"&&l?{tenantId:l}:{}}),[n,o,l]),{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 hn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:l=!1,isRemoving:c=!1}){var X,te;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),p=s.useShareSelectedUsers(),g=s.useShareUsersToRemove(),j=s.useShareUsersToUpdate(),x=s.useShareCurrentMode(),b=s.useShareOrgWideRole(),f=s.useShareManagementActions(),[N,k]=A.useState("specific_users"),I=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},S=()=>{if(i==="tenant"&&d)return d},{allUsers:C,existingShares:v,isLoadingUsers:T}=Ve({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:I(),tenantId:S()});A.useEffect(()=>{f.setCurrentContext("org-tab"),f.setCurrentMode(N==="all_users"?"allOrgUsers":"specificOrgUsers")},[f,N]);const y=K=>{var U,ee;const H=K;if(k(H),r==null||r(H),f.setCurrentContext("org-tab"),H==="specific_users")f.setCurrentMode("specificOrgUsers");else if(H==="all_users"){f.setCurrentMode("allOrgUsers");const _=(ee=(U=v==null?void 0:v.shares)==null?void 0:U.orgUsersOnly)==null?void 0:ee[0];_&&_.role!==void 0&&f.setOrgWideRole(_.role)}},O=C.filter(K=>K.name.toLowerCase().includes(u.toLowerCase())||K.email.toLowerCase().includes(u.toLowerCase())),E=C.filter(K=>p.some(H=>H.id===K.id)),B=K=>{var _,V;const H=p.some(se=>se.id===K),U=g.includes(K),ee=(V=(_=v==null?void 0:v.shares)==null?void 0:_.specificOrgUsers)==null?void 0:V.some(se=>se.orgUserId===K);H?f.removeSelectedUser(K):U?f.removeUserFromRemove(K):ee||f.addSelectedUser({id:K,role:"VIEWER"})},w=(K,H)=>{f.updateSelectedUserRole(K,H)},D=K=>{f.addUserToRemove(K),f.removeSelectedUser(K)},L=K=>{f.removeUserFromRemove(K)},F=K=>{f.removeUserFromUpdate(K)},R=(K,H)=>{f.setOrgWideRole(H)},M=()=>{f.setOrgWideRole((P==null?void 0:P.role)||"NONE")},P=(te=(X=v==null?void 0:v.shares)==null?void 0:X.orgUsersOnly)==null?void 0:te[0];A.useEffect(()=>{N==="all_users"&&P&&P.role!==void 0&&f.setOrgWideRole(P.role)},[N,P,f]);const W=T,z=!1;return a?e.jsxs(e.Fragment,{children:[e.jsx(Ss,{shareType:N,onShareTypeChange:y,currentUser:a,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(a==null?void 0:a.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(a.role??"")}]}),N==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(ts,{value:u,onChange:m}),e.jsx(ct,{selectedUsers:p,selectedUserObjects:E,onRemove:B,onRoleChange:w,getRoleOptions:be}),e.jsx(dt,{usersToRemove:g,allUsers:O,onRemove:L}),e.jsx(ut,{usersToUpdate:j,allUsers:O,onRemove:F,getRoleOptions:be}),e.jsx(xt,{existingShares:v,isInitialLoading:W,isSearching:z,resource:t,onShare:()=>{},getRoleOptions:be,allUsers:O,currentUser:a,handleUserToggle:B,handleUserRoleChange:w,handleRemoveAccess:D,handleUpdateAccess:(K,H,U)=>{f.addUserToUpdate({id:K,currentRole:H,newRole:U})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(pt,{currentUser:a,currentShare:P,isSharing:o,isUpdating:l,isRemoving:c,onUpdateAccess:R,onRemoveAccess:M,allUsersToUpdate:x==="allOrgUsers"&&b!==((P==null?void 0:P.role)||"NONE")?{currentRole:(P==null?void 0:P.role)||"NONE",newRole:b}:null,allUsersToRemove:x==="allOrgUsers"&&(P==null?void 0:P.role)===void 0})})]}):null}function xn(t){switch(t){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function pn(t){switch(t){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function ft({groups:t,existingGroupShares:n,isLoading:a,resource:r,getRoleOptions:o,currentUser:l,handleGroupToggle:c,handleGroupRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),p=s.useShareGroupsToUpdate(),g=s.useShareManagementActions(),j=o(l==null?void 0:l.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(x=>{const b=n==null?void 0:n.find(v=>v.groupId===x.id),f=m.some(v=>v.id===x.id),N=h.includes(x.id),k=p.find(v=>v.id===x.id),I=!!b&&!N;let C=(b==null?void 0:b.role)||"VIEWER";if(f){const v=m.find(T=>T.id===x.id);C=(v==null?void 0:v.role)||"VIEWER"}else k&&(C=k.newRole);return e.jsxs("div",{className:s.cn("flex items-center justify-between rounded-lg p-2 transition-colors",I&&!N?"border border-green-200 bg-green-50":N?"border border-red-200 bg-red-50":f?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(s.Checkbox,{id:`group-${x.id}`,checked:I?!N:f,disabled:!1,onCheckedChange:()=>{I?N?g.removeGroupFromRemove(x.id):d==null||d(x.id):c==null||c(x.id)}}),e.jsxs("label",{htmlFor:`group-${x.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:x.name}),x.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:[x.memberCount," members"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:s.cn("text-xs",pn(x.type)),children:xn(x.type)}),x.type==="TENANT_GROUP"&&x.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",x.tenantName]})]}),x.description&&e.jsx("span",{className:"text-xs text-muted-foreground",children:x.description})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[I&&!N?e.jsx(Oe,{currentRole:C,onRoleChange:v=>{b&&v!==b.role&&(u==null||u(x.id,b.role,v))},roleOptions:j,disabled:!1,allowDropdown:!0,className:k?"border-orange-300 bg-orange-100":""}):f&&!I&&e.jsx(Oe,{currentRole:C,onRoleChange:v=>i==null?void 0:i(x.id,v),roleOptions:j,disabled:!1}),I&&!N&&!k&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>d==null?void 0:d(x.id),children:e.jsx(s.X,{className:"h-4 w-4"})}),N&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromRemove(x.id),children:"Undo"}),k&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g.removeGroupFromUpdate(x.id),children:"Cancel"})]})]},x.id)})})]})}function gt({selectedGroups:t,groupObjects:n,onRemove:a,onRoleChange:r,getRoleOptions:o}){if(t.length===0)return null;const l=o();return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:["Selected Groups (",t.length,")"]}),e.jsx("div",{className:"space-y-1",children:t.map(c=>{const i=n.find(d=>d.id===c.id);return i?e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted/50 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[i.type==="ORG_GROUP"?e.jsx(s.Building2,{className:"h-4 w-4 text-blue-600"}):e.jsx(s.Users,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{className:"text-sm font-medium",children:i.name}),e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[i.memberCount," members"]}),i.type==="TENANT_GROUP"&&i.tenantName&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",i.tenantName]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oe,{currentRole:c.role,onRoleChange:d=>r(c.id,d),roleOptions:l}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>a(c.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})]},c.id):null})})]})}function Us({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:l=!1,isRemoving:c=!1}){var fe;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),g=s.useShareSelectedGroups(),j=s.useShareGroupsToRemove(),x=s.useShareGroupsToUpdate(),b=s.useShareCurrentMode(),f=s.useShareTenantWideRole(),N=s.useShareAllTenantsRole(),k=s.useShareSelectedTenant(),I=s.useShareManagementActions(),{data:S,isLoading:C}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"}),{groups:v,isLoading:T}=s.useShareableGroups("tenant",(a==null?void 0:a.tenantId)||k),[y,O]=A.useState((a==null?void 0:a.type)==="organization"?"all_tenants":"specific_tenant_users");A.useEffect(()=>{(a==null?void 0:a.type)==="tenant"?(I.setCurrentContext("tenant-dialog"),I.setCurrentMode("specificTenantUsers")):(I.setCurrentContext("tenant-tab"),I.setCurrentMode("allTenants"))},[I,a==null?void 0:a.type]);const E=$=>{var Z,q,ae,ie;O($);let J;if($==="specific_tenant_users"?J="specific_users":$==="all_tenant_users"||$==="all_tenants"?J="all_users":$==="groups"?J="groups":J="specific_users",r==null||r(J),$==="groups"?(I.setCurrentContext("group-share"),I.setCurrentMode("specificGroups")):(a==null?void 0:a.type)==="tenant"?(I.setCurrentContext("tenant-dialog"),$==="specific_tenant_users"?I.setCurrentMode("specificTenantUsers"):$==="all_tenant_users"&&(I.setCurrentMode("allTenantUsers"),a!=null&&a.tenantId&&I.setSelectedTenant(a.tenantId))):(I.setCurrentContext("tenant-tab"),$==="specific_tenant_users"?I.setCurrentMode("specificTenantUsers"):$==="all_tenant_users"?I.setCurrentMode("allTenantUsers"):$==="all_tenants"&&I.setCurrentMode("allTenants")),$==="all_tenant_users"){const ce=(q=(Z=D==null?void 0:D.shares)==null?void 0:Z.tenantWide)==null?void 0:q[0];ce&&ce.role!==void 0&&I.setTenantWideRole(ce.role)}else if($==="all_tenants"){const ce=(ie=(ae=D==null?void 0:D.shares)==null?void 0:ae.allTenantsOnly)==null?void 0:ie[0];ce&&ce.role!==void 0&&I.setAllTenantsRole(ce.role)}},B=$=>{I.setSelectedTenant($)},{allUsers:w,existingShares:D,isLoadingUsers:L,isErrorLoadingUsers:F,isLoadingShares:R,isErrorLoadingShares:M}=Ve({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant",tenantId:(a==null?void 0:a.type)==="tenant"?a.tenantId:k}),P=$=>{var ae,ie;const J=m.some(ce=>ce.id===$),Z=h.includes($),q=(ie=(ae=D==null?void 0:D.shares)==null?void 0:ae.specificTenantUsers)==null?void 0:ie.some(ce=>ce.tenantUserId===$);J?I.removeSelectedUser($):Z?I.removeUserFromRemove($):q||I.addSelectedUser({id:$,role:"VIEWER"})},W=($,J)=>{I.updateSelectedUserRole($,J)},z=$=>{I.addUserToRemove($),I.removeSelectedUser($)},X=$=>{I.removeUserFromRemove($)},te=$=>{I.removeUserFromUpdate($)},K=($,J,Z)=>{I.addUserToUpdate({id:$,currentRole:J,newRole:Z})},H=($,J)=>{y==="all_tenant_users"?I.setTenantWideRole(J):y==="all_tenants"&&I.setAllTenantsRole(J)},U=()=>{y==="all_tenant_users"?I.setTenantWideRole("VIEWER"):y==="all_tenants"&&I.setAllTenantsRole("VIEWER")},_=(()=>{var $,J,Z,q;return b==="allTenants"?(J=($=D==null?void 0:D.shares)==null?void 0:$.allTenantsOnly)==null?void 0:J[0]:b==="allTenantUsers"?(q=(Z=D==null?void 0:D.shares)==null?void 0:Z.tenantWide)==null?void 0:q[0]:null})();A.useEffect(()=>{var $,J,Z,q;if(y==="all_tenant_users"){const ae=(J=($=D==null?void 0:D.shares)==null?void 0:$.tenantWide)==null?void 0:J[0];ae&&ae.role!==void 0&&I.setTenantWideRole(ae.role)}else if(y==="all_tenants"){const ae=(q=(Z=D==null?void 0:D.shares)==null?void 0:Z.allTenantsOnly)==null?void 0:q[0];ae&&ae.role!==void 0&&I.setAllTenantsRole(ae.role)}},[y,D,I]);const V=w.filter($=>m.some(J=>J.id===$.id)),se=$=>{const J=g.some(ae=>ae.id===$),Z=j.includes($),q=le==null?void 0:le.some(ae=>ae.groupId===$);J?I.removeSelectedGroup($):Z?I.removeGroupFromRemove($):q||I.addSelectedGroup({id:$,role:"VIEWER"})},ne=($,J)=>{I.updateSelectedGroupRole($,J)},G=$=>{I.addGroupToRemove($),I.removeSelectedGroup($)},Y=($,J,Z)=>{I.addGroupToUpdate({id:$,currentRole:J,newRole:Z})},re=v.filter($=>g.some(J=>J.id===$.id)),oe=A.useMemo(()=>y!=="groups"?[]:v.filter($=>$.type!=="TENANT_GROUP"?!1:$.name.toLowerCase().includes(i.toLowerCase())||$.description&&$.description.toLowerCase().includes(i.toLowerCase())),[v,y,i]),le=A.useMemo(()=>{var J,Z;const $=((J=D==null?void 0:D.shares)==null?void 0:J.specificGroups)||((Z=D==null?void 0:D.shares)==null?void 0:Z.groups)||[];return!$||$.length===0?[]:$.filter(q=>{const ae=v.find(ie=>ie.id===q.groupId);return(ae==null?void 0:ae.type)==="TENANT_GROUP"})},[D,v]),xe=L||R||y==="groups"&&T,pe=F||M,me=()=>(a==null?void 0:a.type)==="tenant"||y==="all_tenants"||y==="groups"?!0:k&&(y==="specific_tenant_users"||y==="all_tenant_users");return e.jsxs(e.Fragment,{children:[pe&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(s.CircleAlert,{className:"mx-auto mb-2 h-8 w-8 text-destructive"}),e.jsx("p",{className:"mb-4 text-sm text-destructive",children:"Failed to load users or shares"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:()=>window.location.reload(),children:"Retry"})]})}),!pe&&a&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(Ss,{shareType:y,onShareTypeChange:E,currentUser:a,options:(a==null?void 0:a.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"specific_tenant_users",label:"Specific Users",description:"Share with specific tenant users",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"groups",label:"Groups",description:"Share with tenant groups",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-green-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:e.jsx(_s,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"all_tenant_users",label:"Specific Tenant",description:"Share with all users of a specific tenant",icon:e.jsx(s.House,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"specific_tenant_users",label:"Specific Tenant User",description:"Share with users of a specific tenant",icon:e.jsx(s.User,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(a==null?void 0:a.type)==="organization"&&(y==="specific_tenant_users"||y==="all_tenant_users")&&e.jsxs("div",{className:"mt-4",children:[e.jsx(s.Label,{className:"mb-1 block text-sm font-medium",children:"Select Tenant"}),e.jsxs(s.Select,{value:k||"",onValueChange:B,disabled:C,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:C?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(fe=S==null?void 0:S.tenants)==null?void 0:fe.map($=>e.jsx(s.SelectItem,{value:$.id,children:$.name},$.id))})]})]}),me()?e.jsx(e.Fragment,{children:y==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(ts,{value:i,onChange:u}),e.jsx(ct,{selectedUsers:m,selectedUserObjects:V,onRemove:$=>P($),onRoleChange:W,getRoleOptions:be}),e.jsx(dt,{usersToRemove:h,allUsers:w,onRemove:X}),e.jsx(ut,{usersToUpdate:p,allUsers:w,onRemove:te,getRoleOptions:be}),e.jsx(xt,{existingShares:D,isInitialLoading:!!xe,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:be,allUsers:w,currentUser:a,handleUserToggle:P,handleUserRoleChange:W,handleRemoveAccess:z,handleUpdateAccess:K})]}):y==="groups"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(ts,{value:i,onChange:u,placeholder:"Search groups..."}),e.jsx(gt,{selectedGroups:g,groupObjects:re,onRemove:se,onRoleChange:ne,getRoleOptions:be}),j.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",j.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),x.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",x.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(ft,{groups:oe,existingGroupShares:le,isLoading:T,resource:t,getRoleOptions:be,currentUser:a,handleGroupToggle:se,handleGroupRoleChange:ne,handleRemoveAccess:G,handleUpdateAccess:Y})]}):y==="all_tenant_users"||y==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(pt,{currentUser:a,currentShare:_,isSharing:o,isUpdating:l,isRemoving:c,onUpdateAccess:H,onRemoveAccess:U,allUsersToUpdate:b==="allTenantUsers"&&((_==null?void 0:_.role)===void 0||f!==_.role)||b==="allTenants"&&((_==null?void 0:_.role)===void 0||N!==_.role)?{currentRole:(_==null?void 0:_.role)||"VIEWER",newRole:b==="allTenantUsers"?f:N}:null,allUsersToRemove:b==="allTenantUsers"&&(_==null?void 0:_.role)===void 0||b==="allTenants"&&(_==null?void 0:_.role)===void 0})}):null}):(a==null?void 0:a.type)==="organization"&&(y==="specific_tenant_users"||y==="all_tenant_users")&&e.jsx("div",{className:"mt-6 flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(_s,{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 fn({resource:t,resourceType:n,currentUser:a,onShareTabTypeChange:r,isSharing:o=!1,isUpdating:l=!1,isRemoving:c=!1}){var F,R;const{searchQuery:i,setSearchQuery:d}=s.useShareSearchWithDebounce(),u=s.useShareSelectedGroups(),m=s.useShareGroupsToRemove(),h=s.useShareGroupsToUpdate(),p=s.useShareManagementActions(),[g,j]=A.useState("org_groups"),[x,b]=A.useState(""),{data:f,isLoading:N}=s.useTenants({enabled:(a==null?void 0:a.type)==="organization"&&g==="tenant_groups"}),k=Array.isArray(f)?f:(f==null?void 0:f.tenants)||[],I=()=>{if((a==null?void 0:a.type)==="organization")return"organization";if((a==null?void 0:a.type)==="tenant")return"tenant"},{groups:S,isLoading:C}=s.useShareableGroups(I(),g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"?x:a==null?void 0:a.tenantId),{existingShares:v}=Ve({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n}),T=S.filter(M=>g==="org_groups"&&M.type!=="ORG_GROUP"||g==="tenant_groups"&&M.type!=="TENANT_GROUP"||g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&(!x||M.tenantId&&M.tenantId!==x)?!1:M.name.toLowerCase().includes(i.toLowerCase())||M.description&&M.description.toLowerCase().includes(i.toLowerCase())),y=((F=v==null?void 0:v.shares)==null?void 0:F.specificGroups)||((R=v==null?void 0:v.shares)==null?void 0:R.groups)||[];A.useEffect(()=>{p.setCurrentContext("group-share"),p.setCurrentMode("specificGroups")},[p]);const O=M=>{const P=M;j(P),P==="org_groups"&&b(""),r==null||r(P==="org_groups"?"specific_groups":"all_groups"),p.setCurrentContext("group-share"),p.setCurrentMode("specificGroups")},E=S.filter(M=>u.some(P=>P.id===M.id)),B=M=>{const P=u.some(X=>X.id===M),W=m.includes(M),z=y==null?void 0:y.some(X=>X.groupId===M);P?p.removeSelectedGroup(M):W?p.removeGroupFromRemove(M):z||p.addSelectedGroup({id:M,role:"VIEWER"})},w=(M,P)=>{p.updateSelectedGroupRole(M,P)},D=M=>{p.addGroupToRemove(M),p.removeSelectedGroup(M)},L=(M,P,W)=>{p.addGroupToUpdate({id:M,currentRole:P,newRole:W})};return a?e.jsxs(e.Fragment,{children:[e.jsx(Ss,{shareType:g,onShareTypeChange:O,currentUser:a,options:[{value:"org_groups",label:"Organization Groups",description:"Share with organization-level groups",icon:e.jsx(s.Building2,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"tenant_groups",label:"Tenant Groups",description:"Share with tenant-level groups",icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-green-500"})}]}),g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(s.Label,{children:"Select Tenant"}),e.jsxs(s.Select,{value:x,onValueChange:b,disabled:N,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:N?"Loading tenants...":"Select a tenant to view its groups"})}),e.jsx(s.SelectContent,{className:"z-[51]",children:k.map(M=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:M.id,children:M.name},M.id))})]})]}),e.jsx("div",{className:"mt-3 space-y-2",children:g==="tenant_groups"&&(a==null?void 0:a.type)==="organization"&&!x?e.jsx("div",{className:"rounded-md border border-dashed p-6 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant above to view and share with its groups"})}):e.jsxs(e.Fragment,{children:[e.jsx(ts,{value:i,onChange:d,placeholder:"Search groups..."}),e.jsx(gt,{selectedGroups:u,groupObjects:E,onRemove:B,onRoleChange:w,getRoleOptions:be}),m.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",m.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",h.length,")"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),e.jsx(ft,{groups:T,existingGroupShares:y,isLoading:C,resource:t,getRoleOptions:be,currentUser:a,handleGroupToggle:B,handleGroupRoleChange:w,handleRemoveAccess:D,handleUpdateAccess:L})]})})]}):null}const jt=()=>{const t=s.useShareCurrentContext(),n=s.useShareCurrentMode(),a=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),o=s.useShareUsersToUpdate(),l=s.useShareSelectedGroups(),c=s.useShareGroupsToRemove(),i=s.useShareGroupsToUpdate(),d=s.useShareSelectedTenant(),u=s.useShareOrgWideRole(),m=s.useShareAllTenantsRole(),h=s.useShareTenantWideRole(),p=s.useShareGroupWideRole(),g=A.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:o,selectedGroups:l,groupsToRemove:c,groupsToUpdate:i,selectedTenant:d,orgWideRole:u,allTenantsRole:m,tenantWideRole:h}),[t,n,a,r,o,l,c,i,d,u,m,h,p]),j=A.useMemo(()=>b=>s.validateShareData(b),[]),x=A.useMemo(()=>{if(!t||!n)return!1;switch(t){case"org-tab":return n==="specificOrgUsers"?a.length>0||r.length>0||o.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||o.length>0:!1;return!0;case"tenant-dialog":return n==="specificTenantUsers"?a.length>0||r.length>0||o.length>0:!0;case"group-share":return n==="specificGroups"?l.length>0||c.length>0||i.length>0:!0}return!1},[t,n,a,r,o,l,c,i,d]);return{buildShareData:g,validateShareData:j,isCurrentStateValid:x,currentContext:t,currentMode:n,selectedUsers:a,usersToRemove:r,usersToUpdate:o,selectedTenant:d,orgWideRole:u,allTenantsRole:m,tenantWideRole:h}};function Ys({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:o,onShare:l,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),p=s.useShareUsersToUpdate(),g=s.useShareSelectedTenant(),j=s.useShareOrgWideRole(),x=s.useShareAllTenantsRole(),b=s.useShareTenantWideRole(),{buildShareData:f,validateShareData:N,isCurrentStateValid:k}=jt(),I=a||r||o,S=()=>{var O,E,B,w;if(I)return"Updating...";if(i==="specific_users"){if(m.length===0&&h.length===0&&p.length===0)return"Select users to share with";const D=m.length+h.length+p.length;return D===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${D} user${D!==1?"s":""}`:h.length>0&&m.length===0&&p.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&p.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:p.length>0&&m.length===0&&h.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${D} user${D!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const D=d.role;return j===D?"Remove Access":"Update Access"}else if(i==="all_tenants"){const D=(E=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:E[0];if(!D||D.role===void 0)return"Share with All Tenants";const L=D.role;return x===L?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const D=(w=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:w[0];if(!D||D.role===void 0)return"Share with All Tenant Users";const L=D.role;return b===L?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(m.length===0&&h.length===0&&p.length===0)return"Select users to share with";const D=m.length+h.length+p.length;return D===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${D} user${D!==1?"s":""}`:h.length>0&&m.length===0&&p.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&p.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:p.length>0&&m.length===0&&h.length===0?`Update access for ${p.length} user${p.length!==1?"s":""}`:`Update access for ${D} user${D!==1?"s":""}`}return"Share"},C=()=>I||!t||i==="all_tenant_users"&&!g||i==="specific_tenant_users"&&!g?!0:!k,v=()=>{const O=f();O&&N(O)&&l(O)},T=()=>{var O,E,B,w;if(i==="all_users")if(!d||d.role===void 0){const D=f();D&&N(D)&&l(D)}else{const D=d.role;if(j===D)u==null||u();else{const F=f();if(F&&N(F)){const R={...F,updateAccess:!0};l(R)}}}else if(i==="all_tenants"){const D=(E=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:E[0];if(!D||D.role===void 0){const L=f();L&&N(L)&&l(L)}else{const L=D.role;if(x===L)u==null||u();else{const R=f();if(R&&N(R)){const M={...R,updateAccess:!0};l(M)}}}}else if(i==="all_tenant_users"){const D=(w=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:w[0];if(!D||D.role===void 0){const L=f();L&&N(L)&&l(L)}else{const L=D.role;if(b===L)u==null||u();else{const R=f();if(R&&N(R)){const M={...R,updateAccess:!0};l(M)}}}}},y=()=>{var O,E,B,w;if(i==="all_users"){if(!d||d.role===void 0)return"default";const D=d.role;return j===D?"destructive":"default"}else if(i==="all_tenants"){const D=(E=(O=n==null?void 0:n.shares)==null?void 0:O.allTenantsOnly)==null?void 0:E[0];if(!D||D.role===void 0)return"default";const L=D.role;return x===L?"destructive":"default"}else if(i==="all_tenant_users"){const D=(w=(B=n==null?void 0:n.shares)==null?void 0:B.tenantWide)==null?void 0:w[0];if(!D||D.role===void 0)return"default";const L=D.role;return b===L?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:I,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||h.length>0||p.length>0)&&e.jsxs(s.Button,{onClick:v,disabled:!t||I,variant:"default",children:[I?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(ze,{className:"mr-2 h-4 w-4"}),!I&&S()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:T,disabled:C(),variant:y(),children:[I?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(s.Users,{className:"mr-2 h-4 w-4"}),!I&&S()]})]})}function gn({resource:t,isSharing:n,isRemoving:a,isUpdating:r,onShare:o,onClose:l,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate(),h=s.useShareSelectedGroups(),p=s.useShareGroupsToRemove(),g=s.useShareGroupsToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const j=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:x,validateShareData:b,isCurrentStateValid:f}=jt(),N=n||a||r,k=()=>{if(N)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&m.length===0)return"Select users to share with";const y=d.length+u.length+m.length;return y===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${y} user${y!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:d.length>0&&u.length===0&&m.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${y} user${y!==1?"s":""}`}else if(c==="groups"){if(h.length===0&&p.length===0&&g.length===0)return"Select groups to share with";const y=h.length+p.length+g.length;return y===0?"Select groups to share with":h.length>0&&p.length>0?`Update access for ${y} group${y!==1?"s":""}`:p.length>0&&h.length===0&&g.length===0?`Remove access for ${p.length} group${p.length!==1?"s":""}`:h.length>0&&p.length===0&&g.length===0?`Share with ${h.length} group${h.length!==1?"s":""}`:g.length>0&&h.length===0&&p.length===0?`Update access for ${g.length} group${g.length!==1?"s":""}`:`Update access for ${y} group${y!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const y=i.role;return j===y?"Remove Access":"Update Access"}return"Share"},I=()=>N||!t?!0:!f,S=()=>{const y=x();y&&b(y)&&o(y)},C=()=>{const y=x();y&&b(y)&&o(y)},v=()=>{if(!i||i.role==="NONE"){const y=x();y&&b(y)&&o(y)}else{const y=i.role;if(j===y){const E=x();if(E&&b(E)){const B={...E,removeAccess:!0};o(B)}}else{const E=x();if(E&&b(E)){const B={...E,updateAccess:!0};o(B)}}}},T=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:l,disabled:N,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:S,disabled:!t||N,variant:"default",children:[N?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(ze,{className:"mr-2 h-4 w-4"}),!N&&k()]})}),c==="groups"&&e.jsx(e.Fragment,{children:(h.length>0||p.length>0||g.length>0)&&e.jsxs(s.Button,{onClick:C,disabled:!t||N,variant:"default",children:[N?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(ze,{className:"mr-2 h-4 w-4"}),!N&&k()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:v,disabled:I(),variant:T(),children:[N?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(ze,{className:"mr-2 h-4 w-4"}),!N&&k()]})]})}function jn({resource:t,existingShares:n,isSharing:a,isRemoving:r,isUpdating:o,onShare:l,onClose:c,shareTabType:i,currentAllGroupsShare:d,onRemoveAccess:u}){const m=s.useShareSelectedGroups(),h=s.useShareGroupsToRemove(),p=s.useShareGroupsToUpdate();s.useShareGroupWideRole(),s.useShareCurrentMode();const g=()=>{l({context:"group-share",mode:"specificGroups",selectedGroups:m,groupsToRemove:h,groupsToUpdate:p})},j=()=>m.length>0||h.length>0||p.length>0,x=()=>h.length>0&&m.length===0&&p.length===0?"Remove Access":p.length>0&&m.length===0&&h.length===0?"Update Access":"Share with Groups",b=a||r||o;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"]}),p.length>0&&e.jsxs("span",{className:"ml-2 text-orange-600",children:["• ",p.length," to update"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:b,children:"Cancel"}),e.jsxs(s.Button,{onClick:g,disabled:!j()||b,children:[b&&e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),x()]})]})]})}function je(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function Se(t,n,a){return{resourceType:t,resourceId:n,data:{shares:a}}}function bn(t,n,a){const{resourceType:r,resourceId:o,shareMutation:l,removeMutation:c,existingShares:i,resetUserSelections:d}=n;if(o)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const u=je(r,o,[{scope:"org_users_only",role:t.orgWideRole}]);l(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const p=je(r,o,u.map(g=>({scope:"specific_org_user",orgUserId:g.id,role:g.role})));l(p,{onSuccess:()=>{d()}})}if(m&&m.length>0){const p=Se(r,o,m.map(g=>{var x,b;const j=(b=(x=i==null?void 0:i.shares)==null?void 0:x.specificOrgUsers)==null?void 0:b.find(f=>f.orgUserId===g);return{scope:"specific_org_user",orgUserId:g,role:(j==null?void 0:j.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(p=>{const g=je(r,o,[{scope:"specific_org_user",orgUserId:p.id,role:p.newRole}]);l(g,{onSuccess:()=>{d()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const u=je(r,o,[{scope:"all_tenants_only",role:t.allTenantsRole}]);l(u,{onSuccess:()=>{d()}})}else if(t.mode==="allTenantUsers"){const u=je(r,o,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);l(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h,tenantId:p}=t;if(m&&m.length>0){const g=Se(r,o,m.map(j=>{var b,f;const x=(f=(b=i==null?void 0:i.shares)==null?void 0:b.specificTenantUsers)==null?void 0:f.find(N=>N.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,tenantId:p,role:(x==null?void 0:x.role)||"VIEWER"}}));c(g,{onSuccess:()=>{d()}})}if(h&&h.length>0&&h.forEach(g=>{const j=je(r,o,[{scope:"specific_tenant_user",tenantUserId:g.id,tenantId:p,role:g.newRole}]);l(j,{onSuccess:()=>{d()}})}),u&&u.length>0){const g=je(r,o,u.map(j=>({scope:"specific_tenant_user",tenantUserId:j.id,tenantId:p,role:j.role})));l(g,{onSuccess:()=>{d()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const u=Se(r,o,[{scope:"all_tenant_users",role:"VIEWER"}]);c(u,{onSuccess:()=>{d()}})}else if(t.updateAccess){const u=je(r,o,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);l(u,{onSuccess:()=>{d()}})}else{const u=je(r,o,[{scope:"all_tenant_users",tenantId:a==null?void 0:a.tenantId,role:t.tenantWideRole}]);l(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const p=je(r,o,u.map(g=>({scope:"specific_tenant_user",tenantUserId:g.id,role:g.role})));l(p,{onSuccess:()=>{d()}})}if(m&&m.length>0){const p=Se(r,o,m.map(g=>{var x,b;const j=(b=(x=i==null?void 0:i.shares)==null?void 0:x.specificTenantUsers)==null?void 0:b.find(f=>f.tenantUserId===g);return{scope:"specific_tenant_user",tenantUserId:g,role:(j==null?void 0:j.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(p=>{const g=je(r,o,[{scope:"specific_tenant_user",tenantUserId:p.id,role:p.newRole}]);l(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 p=je(r,o,u.map(g=>({scope:"group",groupId:g.id,role:g.role})));l(p,{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 p=Se(r,o,m.map(g=>({scope:"group",groupId:g,role:"VIEWER"})));c(p,{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(p=>{const g=je(r,o,[{scope:"group",groupId:p.id,role:p.newRole}]);l(g,{onSuccess:()=>{var j;d(),(j=n.resetGroupSelections)==null||j.call(n),s.ue.success("Updated access for group")}})})}break}}function vn(t,n,a,r){var u,m,h,p,g,j;const{resourceType:o,resourceId:l,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(l)if(t.length>0){const x=Se(o,l,t.map(b=>{var N,k;const f=(k=(N=i==null?void 0:i.shares)==null?void 0:N.specificTenantUsers)==null?void 0:k.find(I=>I.tenantUserId===b);return{scope:"specific_tenant_user",tenantUserId:b,role:(f==null?void 0:f.role)||"VIEWER"}}));c(x,{onSuccess:()=>{d()},onError:b=>{console.error("Remove access failed:",b)}})}else{const x=n==="tenant"&&a==="allTenants",b=n==="tenant"&&a==="allTenantUsers";if(x){const f=(m=(u=i==null?void 0:i.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(f){const N=Se(o,l,[{scope:"all_tenants_only",role:f.role}]);c(N,{onSuccess:()=>{d()},onError:k=>{console.error("Remove all-tenants access failed:",k)}})}}else if(b){const f=(p=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:p[0];if(f){const N=Se(o,l,[{scope:"all_tenant_users",role:f.role}]);c(N,{onSuccess:()=>{d()},onError:k=>{console.error("Remove all-tenant-users access failed:",k)}})}}else{const f=(j=(g=i==null?void 0:i.shares)==null?void 0:g.orgUsersOnly)==null?void 0:j[0];if(f){const N=Se(o,l,[{scope:"org_users_only",role:f.role}]);c(N,{onSuccess:()=>{d()},onError:k=>{console.error("Remove org-wide access failed:",k)}})}}}}function yn(t,n,a){const r=s.useShareManagementActions(),o=s.useShareUsersToRemove(),l=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=s.useCurrentUserInfo(),{existingShares:d}=Ve({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 j={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:n,removeMutation:a,existingShares:d,resetUserSelections:u,resetGroupSelections:m};bn(g,j,i)},[t,n,a,d,u,m,i]),p=A.useCallback(()=>{if(!t)return;const g={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:a,existingShares:d,resetUserSelections:u};vn(o,l||"",c||"",g)},[t,n,a,d,u,m,o,l,c]);return{handleShareSubmit:h,handleRemoveAccess:p}}function ls({resource:t,resourceType:n,onClose:a,onShareSuccess:r,onRemoveSuccess:o}){var w,D,L,F,R,M,P,W;const{currentUser:l}=s.useCurrentUserInfo(),[c,i]=A.useState("specific_users"),[d,u]=A.useState("specific_users"),[m,h]=A.useState("specific_groups"),p=s.useShareManagementActions(),g=s.useShareSelectedTab(),j=s.useShareCurrentMode(),x=s.useShareResource(),b=s.useRemoveResourceShares(),{handleShareSubmit:f,handleRemoveAccess:N}=yn(t.id,(z,X)=>{x.mutate(z,{...X,onSuccess:()=>{var te;(te=X==null?void 0:X.onSuccess)==null||te.call(X),r==null||r()}})},(z,X)=>{b.mutate(z,{...X,onSuccess:()=>{var te;(te=X==null?void 0:X.onSuccess)==null||te.call(X),o==null||o()}})}),k=x.isPending,I=b.isPending,S=x.isPending,{existingShares:C}=Ve({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"tenant"}),{existingShares:v}=Ve({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:n,userType:"organization"}),T=(D=(w=C==null?void 0:C.shares)==null?void 0:w.tenantWide)==null?void 0:D[0],y=(F=(L=v==null?void 0:v.shares)==null?void 0:L.orgUsersOnly)==null?void 0:F[0],O=()=>{if(g==="org")return d;switch(j){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},E=A.useCallback(()=>{p.resetShareState(),a()},[p,a]),B=(l==null?void 0:l.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:E,children:e.jsxs(s.DialogContent,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(ze,{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:z=>{const X=z;p.setSelectedTab(X),p.resetUserSelections(),p.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(hn,{resource:t,resourceType:n,currentUser:l,onShareTabTypeChange:u,isSharing:k,isUpdating:S,isRemoving:I})})}),e.jsx(s.TabsContent,{value:"tenant",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(Us,{resource:t,resourceType:n,currentUser:l,onShareTabTypeChange:z=>i(z),isSharing:k,isUpdating:S,isRemoving:I})})}),e.jsx(s.TabsContent,{value:"groups",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(fn,{resource:t,resourceType:n,currentUser:l,onShareTabTypeChange:h,isSharing:k,isUpdating:S,isRemoving:I})})})]}):e.jsx("div",{className:"mb-4 min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(Us,{resource:t,resourceType:n,currentUser:l,onShareTabTypeChange:z=>i(z),isSharing:k,isUpdating:S,isRemoving:I})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:B?g==="org"?e.jsx(Ys,{resource:t,existingShares:v,isSharing:k,isRemoving:I,isUpdating:S,onShare:f,onClose:a,shareTabType:d,currentAllUsersShare:y,onRemoveAccess:N}):g==="tenant"?e.jsx(Ys,{resource:t,existingShares:C,isSharing:k,isRemoving:I,isUpdating:S,onShare:f,onClose:a,shareTabType:O(),currentAllUsersShare:T,onRemoveAccess:N}):e.jsx(jn,{resource:t,existingShares:v,isSharing:k,isRemoving:I,isUpdating:S,onShare:f,onClose:a,shareTabType:m,currentAllGroupsShare:(l==null?void 0:l.type)==="organization"?(M=(R=v==null?void 0:v.shares)==null?void 0:R.allOrgGroups)==null?void 0:M[0]:(W=(P=C==null?void 0:C.shares)==null?void 0:P.allTenantGroups)==null?void 0:W[0],onRemoveAccess:N}):e.jsx(gn,{resource:t,isSharing:k,isRemoving:I,isUpdating:S,onShare:f,onClose:a,shareTabType:c,currentAllUsersShare:T,onRemoveAccess:N})})]})})}function Nn(t){const n=t.toUpperCase().indexOf("WHERE"),a=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),o=t.toUpperCase().indexOf("ORDER BY");let l=t.length;if(o!==-1&&(l=o),r!==-1&&r<l&&(l=r),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,l),i=t.substring(l);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function ws(t){const[n,a]=A.useState(null),[r,o]=A.useState(null);return A.useEffect(()=>{if(!t||t.trim()===""){a(null),o(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");a(()=>d.useChartStore),o(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),o(i),a(null)}})()},[t]),n}function Cn(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 l=r.split("__")[0],c=t.find(i=>i.tabTitle===l);return c?c.id:t[0].id}return n}}return t[0].id}async function $s(t,n,a){if(!t||!n)throw new Error("Missing auth token or visual ID");const r=["resource-by-id","visual",n],o=a.getQueryData(r);if(o)return console.log("Using cached visual data for:",n),{data:o,fromCache:!0};console.log("Fetching visual data from network for:",n);const l=s.ue.loading("Loading visual...",{position:"top-center"});try{const c=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${n}`,{headers:{Authorization:`Bearer ${t}`}});if(!c.ok)throw new Error("Failed to load visual");const i=await c.json();return a.setQueryData(r,i),s.ue.dismiss(l),{data:i,fromCache:!1}}catch(c){throw s.ue.dismiss(l),c}}function Sn(t,n,a,r,o){const l=t.frameObject;n(l);const c=l.cards.find(i=>i.id===l.activeCardId);c&&a(c),r(!0),o(!0)}function wn(){var p;const{setCardSql:t}=s.useEditorActions(),n=s.useEditorStore(g=>g.frame),a=s.useEditorStore(g=>g.card),r=ws(((p=a.customCardPreferences)==null?void 0:p.url)||""),o=s.useEditorStore(g=>g.selectedSchemaName),l=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=Nn(m),t(g));const j=(f=r==null?void 0:r.getState())==null?void 0:f.settings,x={...a,dataSource:a.dataSource||{mode:"directSource"},lastSelectedSchema:o,lastSelectedDatamodelId:l,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:g,customCfg:u?a.customCfg:null,preferences:a.preferences,...j&&{customCardPreferences:{...a.customCardPreferences,settings:j}}},b=n.cards.map(N=>N.id===a.id?x:N);return{...n,cards:b,activeCardId:Cn(b,n.activeCardId)}},[a,n,u,o,l,c,i,d,t,r,m])}}function Ds(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient(),a=s.useSelectedVisual(),{selectVisual:r}=s.useManagementActions(),{setFrame:o,setCard:l}=s.useEditorActions(),{setIsDashboardEditing:c,setIsVisualEditing:i,setSelectedFrameId:d,addFrame:u,setIsDashboardPanelOpen:m}=s.useDashboardActions(),h=s.useDashboardStore(x=>x.selectedSheetId),p=s.useVisualById((a==null?void 0:a.id)||"",{enabled:!!(a!=null&&a.id)&&!!(t!=null&&t.accessToken)}),g=A.useCallback(async x=>{try{r(x);const{data:b,fromCache:f}=await $s((t==null?void 0:t.accessToken)||"",x.id,n);return Sn(b,o,l,c,i),{success:!0,fromCache:f}}catch(b){return console.error("Error editing visual:",b),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,n,r,o,l,c,i]),j=A.useCallback(async x=>{try{if(r(x),!h)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:b,fromCache:f}=await $s((t==null?void 0:t.accessToken)||"",x.id,n),N=b.frameObject;if(!N)return{success:!1,error:"Visual has no frame data"};const k={...N,id:s.v4()};return u(h,k,"end"),c(!0),d(k.id),m(!1),{success:!0,fromCache:f}}catch(b){return console.error("Error adding visual:",b),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,n,r,h,u,c,d,m]);return{visual:p.data,isLoading:p.isLoading,isError:p.isError,error:p.error,handleEditLibraryVisual:g,handleAddLibraryVisual:j,getUpdatedFrame:wn().getUpdatedFrame,refetch:p.refetch}}function Dn(){const[t,n]=A.useState(""),[a,r]=A.useState(!1),[o,l]=A.useState(""),[c,i]=A.useState(""),[d,u]=A.useState(!1),[m,h]=A.useState(null),[p,g]=A.useState(!1),[j,x]=A.useState(null),[b,f]=A.useState(null),{setIsDashboardEditing:N,setIsVisualEditing:k}=s.useDashboardActions(),{handleEditLibraryVisual:I,handleAddLibraryVisual:S}=Ds(),{resources:C,isLoading:v,isError:T,createResource:y,updateResource:O,deleteResource:E,duplicateResource:B,isCreating:w,isDeleting:D}=s.useVisualManagement(()=>{g(!1),x(null)},()=>{r(!1),l(""),i("")});s.useCurrentUserInfo();const L=C.filter(V=>{var se,ne;return((se=V==null?void 0:V.title)==null?void 0:se.toLowerCase().includes(t.toLowerCase()))||((ne=V==null?void 0:V.description)==null?void 0:ne.toLowerCase().includes(t.toLowerCase()))}),F=V=>new Date(V).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),R=()=>{o.trim()&&y({title:o,description:c,isPrivate:!1})},M=V=>{x(V),g(!0)},P=()=>{j&&E(j.id)},{startUpdating:W,stopUpdating:z,isUpdating:X}=s.useResourceUpdateState(),te=(V,se)=>{const ne=se.title!==void 0?"title":"description";W(V,ne),O({resourceId:V,data:se},{onSuccess:()=>{z(V,ne)},onError:()=>{z(V,ne)}})},K=V=>{f(V),B(V,{onSettled:()=>f(null)})},H=V=>{I(V)},U=V=>{S(V)},ee=V=>{const se=C.find(ne=>ne.id===V);se&&O({resourceId:V,data:{isPrivate:!se.isPrivate}})},_=V=>{h(V),u(!0)};return v?e.jsx(it,{}):T?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:a?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:o,onChange:V=>l(V.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:V=>i(V.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:R,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||w,children:w?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),l(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:w,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",disabled:w,children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),w?"Creating...":"Create New Visual"]})}),C&&C.length>5&&e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:V=>n(V.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:L.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"mb-3",children:e.jsx(rs,{className:"h-12 w-12 mx-auto text-muted-foreground/50"})}),e.jsx("h3",{className:"font-medium text-foreground mb-1",children:t?"No visuals found":"No visuals yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:t?"Try adjusting your search":"Create your first visual component to get started"}),!t&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),"Create Visual"]})]}):L.map(V=>e.jsx(sn,{visual:V,onAddVisual:U,onEditVisual:H,onUpdateVisual:te,onDeleteClick:M,onDuplicateVisual:K,onTogglePrivacy:ee,onShareVisual:_,isDeleting:D,isDuplicating:b===V.id,isTitleUpdating:X(V.id,"title"),isDescriptionUpdating:X(V.id,"description"),formatDate:F},V.id))})}),d&&m&&e.jsx(ls,{resource:m,resourceType:s.ResourceType.VISUAL,onClose:()=>{u(!1),h(null)}}),e.jsx(s.AlertDialog,{open:p,onOpenChange:V=>{!V&&D||(g(V),V||x(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',j==null?void 0:j.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:D,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:V=>{V.preventDefault(),V.stopPropagation(),P()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:D,children:D?"Deleting...":"Delete"})]})]})})]})}function Tn({dashboard:t,isDeleting:n,isDuplicating:a,isTitleUpdating:r=!1,isDescriptionUpdating:o=!1,onLoadDashboard:l,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:u,formatDate:m,onDashboardItemClick:h}){var C,v,T;const{selectDashboard:p}=s.useManagementActions(),g=s.useIsDashboardSelected(t.id),{isConsoleMode:j}=s.useDashboardPreferences(),[x,b]=A.useState(!1),[f,N]=A.useState(!1),k=s.useDashboardStore(y=>y.actions.setIsDashboardPanelOpen);A.useEffect(()=>{a?(b(!0),N(!0)):f&&(b(!1),N(!1))},[a,f]);const I=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4"}),S=()=>{p(t),l(t.id),h==null||h(t.id)};return e.jsx(s.Card,{className:s.cn("group p-3 hover:bg-accent/50 transition-colors cursor-pointer border-border/50",g&&"ring-1 ring-primary"),onClick:S,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 p-1.5 rounded bg-muted",children:I()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(s.EditableText,{inputClassName:"text-sm font-medium text-foreground",value:t.title,onSave:y=>c==null?void 0:c(t.id,{title:y}),isEditable:t.permissions.canEdit&&g,isPending:r,placeholder:"Untitled Dashboard",displayClassName:"font-medium text-sm text-foreground truncate"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"h-2.5 w-2.5 mr-1"}),"Shared"]})]}),e.jsx(s.EditableText,{inputClassName:"text-xs text-muted-foreground line-clamp-2",value:t.description||"",onSave:y=>c==null?void 0:c(t.id,{description:y}),isEditable:t.permissions.canEdit&&g,isPending:o,placeholder:"No description",displayClassName:"text-xs text-muted-foreground line-clamp-2 mb-2"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsxs("span",{children:["Updated ",m(t.lastModified)]})]})]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-150 group-hover:opacity-100","ml-2 flex-shrink-0"),onClick:y=>y.stopPropagation(),children:e.jsxs(s.DropdownMenu,{modal:!1,open:x,onOpenChange:b,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.preventDefault(),y.stopPropagation(),d(t.id)},disabled:a,children:[a?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),a?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),u(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]})}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:y=>{y.stopPropagation(),i(t),k(!1)},className:"text-destructive",disabled:n,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),n?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((C=t.ownership.createdBy)==null?void 0:C.type)==="tenant"||((v=t.ownership.createdBy)==null?void 0:v.type)==="organization"&&j)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((T=t.ownership.createdBy)==null?void 0:T.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:m(t.lastModified)})]})]})]})]})})]})},t.id)}function kn({onRetry:t}){return e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load dashboards"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:t,children:"Retry"})]})})}function En(t){const[n,a]=A.useState(""),[r,o]=A.useState(!1),[l,c]=A.useState(""),[i,d]=A.useState(""),[u,m]=A.useState(!1),[h,p]=A.useState(null),[g,j]=A.useState(!1),[x,b]=A.useState(null),[f,N]=A.useState(null),k=s.useManagementStore(Y=>Y.lastSelectedDashboard),I=s.useManagementStore(Y=>Y.selectedDashboard),S=s.useManagementStore(Y=>Y.actions.selectDashboard),C=s.useManagementStore(Y=>Y.actions.clearSelectedDashboard),{tokenProps:v,id:T}=s.useSemaphorContext(),{permissions:y}=s.useRoleAwareDisplayPreferences(),{resources:O,isLoading:E,isError:B,createResource:w,updateResource:D,deleteResource:L,duplicateResource:F,isCreating:R,isDeleting:M}=s.useDashboardManagement(()=>{j(!1);const Y=x==null?void 0:x.id;b(null),(I==null?void 0:I.id)===Y&&(!(v!=null&&v.dashboard_id)&&!T?C():k&&k.id!==Y&&S(k))},()=>{o(!1),c(""),d("")}),{currentUser:P}=s.useCurrentUserInfo(),W=O.filter(Y=>{var re,oe;return((re=Y==null?void 0:Y.title)==null?void 0:re.toLowerCase().includes(n.toLowerCase()))||((oe=Y==null?void 0:Y.description)==null?void 0:oe.toLowerCase().includes(n.toLowerCase()))}),z=Y=>new Date(Y).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),X=()=>{l.trim()&&w({title:l,description:i,isPrivate:!1})},te=Y=>{var re;(re=t.onLoadDashboard)==null||re.call(t,Y)},K=Y=>{b(Y),j(!0)},H=()=>{x&&L(x.id)},U=Y=>{N(Y),F(Y,{onSettled:()=>N(null)})},{startUpdating:ee,stopUpdating:_,isUpdating:V}=s.useResourceUpdateState(),se=(Y,re)=>{const oe=re.title!==void 0?"title":"description";ee(Y,oe),D({resourceId:Y,data:re},{onSuccess:()=>{_(Y,oe)},onError:()=>{_(Y,oe)}})},ne=Y=>{const re=O.find(oe=>oe.id===Y);re&&D({resourceId:Y,data:{isPrivate:!re.isPrivate}})},G=Y=>{p(Y),P==null||P.type,m(!0)};return E?e.jsx(it,{}):B?e.jsx(kn,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[y.canCreateDashboards&&e.jsx("div",{className:"px-1",children:r?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Dashboard"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter dashboard title...",value:l,onChange:Y=>c(Y.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",className:"text-xs",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter dashboard description...",value:i,onChange:Y=>d(Y.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:X,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||R,children:R?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{o(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:R,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>o(!0),className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",disabled:R,children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),R?"Creating...":"Create New Dashboard"]})}),O&&O.length>5&&e.jsx("div",{className:"space-y-2 px-1",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:n,onChange:Y=>a(Y.target.value),className:"h-8"})}),e.jsx("div",{className:"mb-4 flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-2 overflow-y-auto p-1",children:W.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"mb-3",children:e.jsx(s.ChartColumn,{className:"h-12 w-12 mx-auto text-muted-foreground/50"})}),e.jsx("h3",{className:"font-medium text-foreground mb-1",children:n?"No dashboards found":"No dashboards yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:n?"Try adjusting your search":y.canCreateDashboards?"Create your first dashboard to get started":"No dashboards have been shared with you yet"}),y.canCreateDashboards&&!n&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>o(!0),children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),"Create Dashboard"]})]}):W.map(Y=>e.jsx(Tn,{dashboard:Y,isDeleting:M,isDuplicating:f===Y.id,isTitleUpdating:V(Y.id,"title"),isDescriptionUpdating:V(Y.id,"description"),onLoadDashboard:te,onEditDashboard:t.onEditDashboard,onUpdateDashboard:se,onDeleteClick:K,onDuplicateDashboard:U,onTogglePrivacy:ne,onShareDashboard:G,formatDate:z,onDashboardItemClick:t.onDashboardItemClick},Y.id))})}),u&&h&&e.jsx(ls,{resource:h,resourceType:s.ResourceType.DASHBOARD,onClose:()=>{m(!1),p(null)}}),e.jsx(s.AlertDialog,{open:g,onOpenChange:Y=>{!Y&&M||(j(Y),Y||b(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Dashboard"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',x==null?void 0:x.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:M,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:Y=>{Y.preventDefault(),Y.stopPropagation(),H()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:M,children:M?"Deleting...":"Delete"})]})]})})]})}function bt({isOpen:t,onClose:n,className:a,onDashboardItemClick:r}){s.useDashboardStore(b=>b.dashboard);const{setDashboard:o,addSheet:l}=s.useDashboardStore(b=>b.actions),{currentUser:c}=s.useCurrentUserInfo(),i=c,{permissions:d}=s.useRoleAwareDisplayPreferences(),u=(d.canAccessVisuals,"dashboards"),[m,h]=s.useLocalStorageState("resource-management-active-tab",u),p=d.canAccessVisuals?m:"dashboards",g=mt(n,{enabled:t}),j=b=>{},x=b=>{console.log("Editing dashboard:",b)};return e.jsx(s.TooltipProvider,{children:e.jsxs("div",{ref:g,className:s.cn("absolute inset-y-0 left-0 z-[51] flex w-96 flex-col border-r bg-background shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"hidden -translate-x-full",a),children:[e.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[e.jsx("div",{className:"flex items-center gap-2",children:i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx("span",{className:"text-sm font-medium text-primary",children:i.name.charAt(0).toUpperCase()})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:i.name}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:d.canCreateDashboards?"default":"secondary",className:"text-xs cursor-help",children:d.canCreateDashboards?e.jsxs(e.Fragment,{children:[e.jsx(s.Users,{className:"h-3 w-3 mr-1"}),"Power User"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Eye,{className:"h-3 w-3 mr-1"}),"Viewer"]})})}),e.jsx(s.TooltipContent,{side:"bottom",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:i.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:i.email}),i.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role: ",s.toTitleCase(i.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",i.id]})]})})]})})]})]})}),e.jsx(s.IconButton,{className:"h-8 w-8 p-0 text-muted-foreground hover:text-foreground",onClick:n,tooltip:"Close panel",children:e.jsx(s.X,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:p,onValueChange:d.canAccessVisuals?h:void 0,className:"flex h-9 grow flex-col",children:[d.canAccessVisuals?e.jsx("div",{className:"px-4 pt-4",children:e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"text-sm",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"text-sm",children:"Visuals"})]})}):e.jsx("div",{className:"px-4 pt-4 pb-0",children:e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Dashboards"})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1 mt-4",children:e.jsx(En,{onLoadDashboard:j,onEditDashboard:x,onDashboardItemClick:r})}),d.canAccessVisuals&&e.jsx(s.TabsContent,{value:"visuals",className:"flex-1 mt-4",children:e.jsx(Dn,{})})]})})]})})}const In=async(t,n)=>await s.postRequestRegular("https://semaphor.cloud/api/management/v1/groups",t,n),An=async(t,n)=>{const a=`https://semaphor.cloud/api/management/v1/groups/${n}`,r=await fetch(a,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}});if(!r.ok){const o=await r.text();throw new Error(o||"Failed to delete group")}},Mn=async(t,n,a)=>{const r=`https://semaphor.cloud/api/management/v1/groups/${n}/members`;return await s.postRequestRegular(r,t,a)},Ln=async(t,n,a)=>{const r=`https://semaphor.cloud/api/management/v1/groups/${n}/members`,o=await fetch(r,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a)});if(!o.ok){const l=await o.text();throw new Error(l||"Failed to remove group members")}};function Rn(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient();return s.useMutation({mutationFn:a=>In((t==null?void 0:t.accessToken)||"",a),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),s.ue.success("Group created successfully")},onError:a=>{console.error("Failed to create group:",a),s.ue.error("Failed to create group",{description:a.message})}})}function On(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient();return s.useMutation({mutationFn:a=>An((t==null?void 0:t.accessToken)||"",a),onSuccess:(a,r)=>{n.invalidateQueries({queryKey:["groups"]}),n.removeQueries({queryKey:["group",r]}),s.ue.success("Group deleted successfully")},onError:a=>{console.error("Failed to delete group:",a),s.ue.error("Failed to delete group",{description:a.message})}})}function Fn(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient();return s.useMutation({mutationFn:({groupId:a,data:r})=>Mn((t==null?void 0:t.accessToken)||"",a,r),onSuccess:(a,r)=>{n.invalidateQueries({queryKey:["group",r.groupId]}),n.invalidateQueries({queryKey:["group-members",r.groupId]}),n.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members added successfully")},onError:a=>{console.error("Failed to add group members:",a),s.ue.error("Failed to add members",{description:a.message})}})}function Bn(){const{authToken:t}=s.useSemaphorContext(),n=s.useQueryClient();return s.useMutation({mutationFn:({groupId:a,data:r})=>Ln((t==null?void 0:t.accessToken)||"",a,r),onSuccess:(a,r)=>{n.invalidateQueries({queryKey:["group",r.groupId]}),n.invalidateQueries({queryKey:["group-members",r.groupId]}),n.invalidateQueries({queryKey:["groups"]}),s.ue.success("Members removed successfully")},onError:a=>{console.error("Failed to remove group members:",a),s.ue.error("Failed to remove members",{description:a.message})}})}function Pn({onSuccess:t,tenantId:n,isTenantUser:a}){const[r,o]=A.useState(""),[l,c]=A.useState(""),[i,d]=A.useState({}),u=Rn(),m=()=>{const p={};return r.trim()?r.length<3?p.name="Group name must be at least 3 characters":r.length>50&&(p.name="Group name must be less than 50 characters"):p.name="Group name is required",l&&l.length>200&&(p.description="Description must be less than 200 characters"),d(p),Object.keys(p).length===0},h=async p=>{if(p.preventDefault(),!m())return;const g={name:r.trim(),description:l.trim()||void 0,type:a?"TENANT_GROUP":"ORG_GROUP",...a&&n?{tenantId:n}:{}};try{await u.mutateAsync(g),o(""),c(""),d({}),t()}catch(j){console.error("Failed to create group:",j)}};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:p=>{o(p.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:l,onChange:p=>{c(p.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:[l.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:()=>{o(""),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 zn({open:t,onOpenChange:n,group:a,onUpdate:r}){const[o,l]=A.useState("members"),[c,i]=A.useState(""),[d,u]=A.useState([]),[m,h]=A.useState([]),{data:p,isLoading:g,refetch:j}=s.useGroupMembers(a.id),x=a.type==="TENANT_GROUP"?"tenant":"organization",{users:b,isLoading:f}=s.useUnifiedUsers({type:x,tenantId:a.tenantId||void 0,active:!0,limit:100}),N=Fn(),k=Bn(),I=(p==null?void 0:p.members)||[],S=A.useMemo(()=>new Set(I.map(w=>w.userId)),[I]),C=A.useMemo(()=>b.filter(w=>!S.has(w.id)),[b,S]),v=A.useMemo(()=>{if(!c)return C;const w=c.toLowerCase();return C.filter(D=>{var L,F;return((L=D.name)==null?void 0:L.toLowerCase().includes(w))||((F=D.email)==null?void 0:F.toLowerCase().includes(w))})},[C,c]),T=A.useMemo(()=>{if(!c)return I;const w=c.toLowerCase();return I.filter(D=>{var L,F,R,M;return((F=(L=D.user)==null?void 0:L.name)==null?void 0:F.toLowerCase().includes(w))||((M=(R=D.user)==null?void 0:R.email)==null?void 0:M.toLowerCase().includes(w))})},[I,c]),y=async()=>{if(d.length!==0)try{await N.mutateAsync({groupId:a.id,data:{userIds:d,userType:x==="tenant"?"tenant":"org"}}),u([]),l("members"),j(),r==null||r()}catch(w){console.error("Failed to add members:",w)}},O=async()=>{if(m.length!==0)try{await k.mutateAsync({groupId:a.id,data:{userIds:m}}),h([]),j(),r==null||r()}catch(w){console.error("Failed to remove members:",w)}},E=w=>{u(D=>D.includes(w)?D.filter(L=>L!==w):[...D,w])},B=w=>{h(D=>D.includes(w)?D.filter(L=>L!==w):[...D,w])};return e.jsx(e.Fragment,{children:e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-3xl max-h-[80vh]","aria-describedby":"group-members-description",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:a.name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[I.length," ",I.length===1?"member":"members"]})}),e.jsxs("p",{id:"group-members-description",className:"sr-only",children:["Add or remove members from the ",a.name," group"]})]}),e.jsxs(s.Tabs,{value:o,onValueChange:w=>{l(w),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:w=>i(w.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(w=>e.jsx(s.Skeleton,{className:"h-16 w-full"},w))}):T.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:T.map(w=>e.jsx(_n,{member:w,selected:m.includes(w.userId),onToggle:()=>B(w.userId)},w.id))})}),m.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[m.length," member",m.length!==1?"s":""," selected"]}),e.jsx(s.Button,{variant:"destructive",size:"sm",onClick:O,disabled:k.isPending,children:k.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:w=>i(w.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(w=>e.jsx(s.Skeleton,{className:"h-16 w-full"},w))}):v.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(es,{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(w=>e.jsx(Vn,{user:w,selected:d.includes(w.id),onToggle:()=>E(w.id)},w.id))})}),d.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[d.length," user",d.length!==1?"s":""," selected"]}),e.jsx(s.Button,{onClick:y,disabled:N.isPending,children:N.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Adding..."]}):e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"mr-2 h-4 w-4"}),"Add Members"]})})]})]})]})]})})})}function _n({member:t,selected:n,onToggle:a}){var o,l,c,i;const r=((l=(o=t.user)==null?void 0:o.name)==null?void 0:l.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 Vn({user:t,selected:n,onToggle:a}){var o;const r=((o=t.name)==null?void 0:o.split(" ").map(l=>l[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 Gn({open:t,onOpenChange:n}){const[a,r]=A.useState("groups"),[o,l]=A.useState(""),[c,i]=A.useState(null),[d,u]=A.useState(!1),[m,h]=A.useState(null),{tokenProps:p}=s.useSemaphorContext(),{currentUser:g}=s.useCurrentUserInfo(),j=On(),x=(g==null?void 0:g.type)==="tenant",b=p==null?void 0:p.tenantId,{groups:f,isLoading:N,refetch:k}=s.useGroups({type:x?"TENANT_GROUP":"all",tenantId:x?b:void 0,includeMembers:!1}),I=f.filter(T=>{var y;return T.name.toLowerCase().includes(o.toLowerCase())||((y=T.description)==null?void 0:y.toLowerCase().includes(o.toLowerCase()))}),S=async()=>{if(m)try{await j.mutateAsync(m.id),h(null),k()}catch(T){console.error("Failed to delete group:",T)}},C=T=>{i(T),u(!0)},v=()=>{r("groups"),k()};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:o,onChange:T=>l(T.target.value),className:"pl-10"})]}),e.jsx(s.ScrollArea,{className:"h-[400px]",children:N?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(T=>e.jsx(s.Skeleton,{className:"h-24 w-full"},T))}):I.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(s.Users,{className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{className:"text-sm font-medium",children:"No groups found"}),e.jsx("p",{className:"text-xs mt-1",children:o?"Try a different search":"Create your first group to get started"})]}):e.jsx("div",{className:"space-y-3",children:I.map(T=>e.jsx(Un,{group:T,onManageMembers:()=>C(T),onDelete:()=>h(T),currentUserId:g==null?void 0:g.id},T.id))})})]})}),e.jsx(s.TabsContent,{value:"create",className:"mt-4",children:e.jsx(Pn,{onSuccess:v,tenantId:b,isTenantUser:x})})]})]})}),c&&e.jsx(zn,{open:d,onOpenChange:u,group:c,onUpdate:()=>k()}),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:S,disabled:j.isPending,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:j.isPending?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Deleting..."]}):"Delete Group"})]})]})})]})}function Un({group:t,onManageMembers:n,onDelete:a,currentUserId:r}){const o=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(es,{className:"h-4 w-4"})}),o&&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 Yn(){var $,J,Z;const{authToken:t,tokenProps:n,id:a}=s.useSemaphorContext(),{isLocalDev:r}=s.useDashboardPreferences(),{permissions:o}=s.useRoleAwareDisplayPreferences(),l=s.useHasDashboardId();s.useDashboardStore(q=>q.theme);const c=s.useDashboardStore(q=>q.lenses),i=s.useDashboardStore(q=>q.selectedLensId),d=c==null?void 0:c.find(q=>q.id===i),u=s.useDashboardStore(q=>q.dashboard);s.useDashboardStore(q=>q.selectedSheetId);const m=s.useDashboardStore(q=>q.isDashboardEditing),h=s.useEditorStore(q=>q.card),p=s.useEditorStore(q=>q.selectedConnectionId),[g,j]=A.useState(!1),[x,b]=A.useState(!1),[f,N]=A.useState(!1),k=s.useDashboardStore(q=>q.isDashboardPanelOpen),I=s.useDashboardStore(q=>q.actions.setIsDashboardPanelOpen),S=s.useDashboardStore(q=>q.filterValues),C=s.useDashboardStore(q=>q.isVisualEditing),v=s.useManagementStore(q=>q.selectedDashboard),T=s.useManagementStore(q=>q.initialDashboard),y=v?(J=v==null?void 0:v.permissions)==null?void 0:J.canEdit:($=T==null?void 0:T.permissions)==null?void 0:$.canEdit,O=s.useDashboardStore(q=>q.showFilters),E=s.useDashboardStore(q=>q.showDashboardJSON),B=s.useDashboardStore(q=>q.onSaveFunction),w=s.useDashboardStore(q=>q.actions.setShowFilters),{addFrame:D,setSelectedFrameId:L}=s.useDashboardStore(q=>q.actions),{getSelectedSheet:F,setIsDashboardEditing:R,setShowDashboardJSON:M}=s.useDashboardStore(q=>q.actions),P=F(),{setInitialDashboard:W,clearSelectedDashboard:z}=s.useManagementStore(q=>q.actions),{resources:X}=s.useResourceManagement(s.ResourceType.DASHBOARD),{currentUser:te}=s.useCurrentUserInfo(),K=s.canUserManageGroups(te),H=v||T,U=H?{id:H.id,title:(u==null?void 0:u.title)||H.title||"Dashboard"}:null;A.useEffect(()=>{if(X&&X.length>0){const q=u==null?void 0:u.id;if(q){const ae=X.find(ie=>ie.id===q);ae&&W(ae)}}},[X,u==null?void 0:u.id,W]);const ee=n.orgUserId||n.tenantId,_=m&&!C&&ee&&y;function V(){var ce,Ee;const q=h.dataSource;if(q)return q;const ae=(Ee=(ce=u.aiContext)==null?void 0:ce.selectedEntities)==null?void 0:Ee[0],ie=ae==null?void 0:ae.type;if(ae)return{connectionId:ae.connectionId,connectionType:ae.connectionType,type:ie,selectedEntities:[ae]}}const se=()=>{if(!m||!P)return;const ae={dataSource:V(),mode:"explorer",connectionId:p,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},ie={id:s.v4(),cards:[ae],activeCardId:ae.id};D(P.id,ie),L(ie.id)},ne=()=>{R(!0)},[G,Y]=A.useState(!1),re=s.useUpdateResource(s.ResourceType.DASHBOARD);async function oe(){const q=ss(u);Y(!0);const ae={template:q};re.mutate({resourceId:q.id,data:ae},{onSuccess:()=>{Y(!1),s.ue.success("Dashboard saved!")},onError:()=>{Y(!1),s.ue.error("Failed to save dashboard")}})}async function le(){if(j(!0),!i||!d)return;const q=ss(u),ae=JSON.stringify(q),ie={...d,template:ae,filterValues:S};await vs(ie,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),B==null||B(q),j(!1)}if(C)return null;const xe=(d==null?void 0:d.name)||u.title,me=X&&X.length>0&&(n.orgUserId||n.tenantId&&n.endUserId&&n.endUserEmail),fe=v&&!(n!=null&&n.dashboard_id)&&!a;return e.jsxs("div",{className:"flex h-10 items-center justify-between gap-2 border-b py-2 pl-3 pr-2",role:"dashboard-controls",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[me&&e.jsxs(e.Fragment,{children:[fe&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Back to Dashboard Hub",onClick:()=>z(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})}),e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:l?"Manage Dashboards":"Select a dashboard to continue",onClick:()=>I(!0),className:"h-7 p-2",buttonProps:{disabled:!l},children:e.jsx(Ea,{className:"h-4 w-4"})})]}),!C&&l&&e.jsx(s.Label,{children:xe})]}),e.jsxs("div",{className:"flex gap-2",children:[r&&e.jsx(s.IconButton,{tooltip:"Invalidate Token",onClick:s.invalidateToken,className:"h-7 p-2",children:e.jsx(_a,{className:"h-4 w-4"})}),!C&&l&&e.jsx(en,{}),!C&&l&&e.jsx(ot,{}),!C&&l&&K&&e.jsx(s.IconButton,{tooltip:"Manage Groups",onClick:()=>N(!0),className:"h-7 p-2",children:e.jsx(s.Users,{className:"h-4 w-4"})}),!C&&l&&((Z=H==null?void 0:H.permissions)==null?void 0:Z.canShare)&&e.jsx(s.IconButton,{tooltip:"Share Dashboard",onClick:()=>b(!0),className:"h-7 p-2",children:e.jsx(es,{className:"h-4 w-4"})}),m&&!C&&ee&&r&&l&&e.jsx(Xa,{}),!C&&ee&&r&&l&&e.jsx(Za,{}),m&&!C&&ee&&d&&r&&l&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:g,onClick:le,size:"sm",children:[e.jsx(bs,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),m&&!C&&l&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!m,onClick:se,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!C&&!m&&o.canEdit&&l&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:ne,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),m&&!C&&l&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{R(!1),M(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),_&&l&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"outline",disabled:G,onClick:oe,size:"sm",children:[G?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(bs,{className:"mr-2 h-4 w-4"}),G?"Saving...":"Save"]}),!O&&!C&&m&&o.canUseFilters&&l&&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&&m&&r&&l&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>M(!E),size:"sm",variant:"ghost",children:e.jsx(_e,{className:"h-4 w-4"})})}),!C&&r&&e.jsx(Wa,{}),!C&&e.jsx(bt,{isOpen:k,onClose:()=>I(!1)}),x&&U&&e.jsx(ls,{resource:U,resourceType:s.ResourceType.DASHBOARD,onClose:()=>b(!1)}),e.jsx(Gn,{open:f,onOpenChange:N})]})]})}function $n({name:t,items:n,value:a,onChange:r,isLoading:o,isError:l,refetch:c,className:i,icon:d,showNone:u=!1}){const m=Ie.useRef(null),[h,p]=Ie.useState(!1),[g,j]=Ie.useState("100%"),x=u?[...n||[],{id:"none",name:"None"}]:n;Ie.useLayoutEffect(()=>{m.current&&j(m.current.offsetWidth)},[]);function b(){var N;return o?"Loading...":l?"Error":a?(N=n==null?void 0:n.find(k=>k.id===a))==null?void 0:N.name:`Select ${t}`}function f(N,k){r(k),p(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:p,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:b()})]}),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(at,{className:s.cn("size-3.5 opacity-50",o&&"animate-spin")})})]}),e.jsxs(s.CommandList,{children:[e.jsxs(s.CommandEmpty,{children:["No ",t==null?void 0:t.toLowerCase()," found."]}),e.jsx(s.CommandGroup,{children:x==null?void 0:x.map(N=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:N.name,onSelect:k=>f(k,N.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",a===N.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:N.name,children:N.name})]})},N.id))})]})]})})]})}function Pe({title:t,items:n,value:a,isLoading:r,isError:o,refetch:l,onChange:c,showNone:i=!1,className:d,disabled:u=!1,type:m="combobox"}){const h=r?"Loading...":o?"Error":a;function p(){if(t==="Connection")return e.jsx(Ba,{className:"size-4"});if(t==="Database")return e.jsx(s.Database,{className:"size-4"});if(t==="Schema")return e.jsx(Ra,{className:"size-4"});if(t==="Table")return e.jsx(s.Table2,{className:"size-4"});if(t==="Model")return e.jsx(ia,{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...":o?"Error":`Select ${t}`})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[r?e.jsx(s.SelectLabel,{children:"Loading..."}):e.jsxs(s.SelectLabel,{className:"flex items-center justify-between gap-2",children:[t,e.jsx(at,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:l})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),n&&n.map((x,b)=>e.jsx(s.SelectItem,{value:x.id,children:x.name},b))]}),(r||o)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function j(){return e.jsx($n,{icon:p(),items:n,value:h,onChange:c||(()=>{}),isLoading:r,isError:o,refetch:l,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():j()})})}function qn({column:t}){const[n,a]=A.useState(!1),r=s.useEditorStore(x=>x.selectedTableName),o=s.useEditorStore(x=>x.selectedSchemaName),l=s.useEditorStore(x=>x.selectedDatabaseName),c=s.useEditorStore(x=>x.selectedDatamodelId),i=s.useEditorStore(x=>x.sqlGen),{modelItems:d,connectionType:u}=s.useEditorAside(),m=s.useEditorStore(x=>x.actions.setSqlGen),h=s.useEditorStore(x=>x.actions.setCardSql),p=s.useEditorStore(x=>x.actions.setRunSql);function g(x,b){var I;const f=s.createSqlGenConfig(x,i,b),N=(I=d==null?void 0:d.find(S=>S.id===c))==null?void 0:I.name;m(f);const k=s.getSql(f,s.fmt(o||""),s.fmt(r),N||"",u,l||"");k&&(h(k),p(!0)),a(!1)}function j(){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:j()})]})}function Hn({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Re,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(_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($e,{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(We,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})}function ds({column:t,className:n}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center gap-2 px-3 py-[6px] text-sm",n),children:[e.jsx(Hn,{dataType:t.data_type}),e.jsx("span",{children:t.column_name})]})}function Wn({id:t,children:n,type:a="column"}){const{attributes:r,listeners:o,setNodeRef:l,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:l,style:i,...o,...r,children:n})}function Kn({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}),o=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.metricColumns}),l=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.filterColumns});function c(m){return i(m)||d(m)||u(m)}function i(m){return r==null?void 0:r.some(h=>h.name===m.column_name)}function d(m){return o==null?void 0:o.some(h=>h.name===m.column_name)}function u(m){return l==null?void 0:l.some(h=>h.name===m.column_name)}return e.jsxs("div",{onClick:()=>t(n),className:s.cn("group relative grow cursor-pointer overflow-x-hidden overflow-y-hidden border border-dashed border-background transition-colors hover:bg-muted/50",{"bg-muted":c(n)}),children:[a===n.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(ds,{column:n,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),a===n.column_name&&e.jsx("div",{className:"absolute inset-0",children:a===n.column_name&&e.jsx(ds,{column:n})}),e.jsx(Wn,{id:n.column_name,type:"column",children:e.jsx(ds,{column:n})})]})}const us={id:"__placeholder__",role:"groupby",type:"string"},ms={id:"__placeholder__",role:"groupby",type:"string"},hs={id:"__placeholder__",role:"metric",type:"number"},xs={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},vt={id:"__placeholder__"},Ae="droppable-group-by",Me="droppable-metrics",Le="droppable-pivot-by",as="sortable-group-by",ys="sortable-metrics",ns="sortable-pivot-by",Ns="droppable-filters",Cs="sortable-filters",Ts="sortable-order-by";function Qn(){const t=s.useDndStore(D=>D.insertIndex),n=s.useEditorStore(D=>{var L;return((L=D.card.queryConfig)==null?void 0:L.groupByColumns)||[]}),a=s.useEditorStore(D=>{var L;return((L=D.card.queryConfig)==null?void 0:L.metricColumns)||[]}),r=s.useEditorStore(D=>{var L;return((L=D.card.queryConfig)==null?void 0:L.filterColumns)||[]}),o=s.useEditorStore(D=>{var L;return((L=D.card.queryConfig)==null?void 0:L.orderBy)||[]}),l=s.useEditorStore(D=>{var L;return((L=D.card.queryConfig)==null?void 0:L.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:u,setPreviewFilterColumns:m,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:p,setMetricColumns:g,setFilterColumns:j,setOrderByColumns:x,setPivotByColumns:b}=s.useEditorActions(),{columns:f}=s.useDataColumns(),{formattedTableName:N}=s.useEditorAside(),k=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),I=D=>{var R;const{active:L,over:F}=D;if(((R=L.data.current)==null?void 0:R.type)==="column"&&F){const M=F.id,P=f.find(te=>te.column_name===L.id);if(!P)return;const W=s.isNumberDataType(P.data_type),z=s.isTextDataType(P.data_type),X=s.isDateDataType(P.data_type);if(z||X){if(n.some(K=>K.id===M)){const K=n.findIndex(U=>U.id===M);c(K);const H=n.filter(U=>U.id!==us.id);H.splice(K,0,us),d(H)}else if(F.id===Ae){c(n.length);const K=[...n,us];d(K),u(a),m(r)}}if(z||X){if(l.some(K=>K.id===M)){const K=l.findIndex(U=>U.id===M);c(K);const H=l.filter(U=>U.id!==ms.id);H.splice(K,0,ms),h(H)}else if(F.id===Le){c(l.length);const K=[...l,ms];h(K),d(n),u(a),m(r)}}if(W||z){if(a.some(K=>K.id===M)){console.log("isOverMetricSortable",M);const K=a.findIndex(U=>U.id===M);c(K);const H=a.filter(U=>U.id!==hs.id);H.splice(K,0,hs),u(H)}else if(F.id===Me){c(a.length);const K=[...a,hs];u(K),m(r),d(n),h(l)}}if(C(P)){if(r.some(K=>K.id===M)){const K=r.findIndex(U=>U.id===M);c(K);const H=r.filter(U=>U.id!==xs.id);H.splice(K,0,xs),m(H)}else if(F.id===Ns){c(r.length);const K=[...r,xs];m(K),u(a),d(n),h(l)}}}else d(n),u(a),m(r),h(l)};function S(D){i(D.active.id),c(null),d(n),u(a),m(r),h(l)}function C(D){return!r.some(L=>L.name===D.column_name)}function v(D,L="SUM"){const{column_name:F,data_type:R}=D,M=[...a],P=t!==null?t:a.length,W={...D,id:Ne(F),name:F,label:He(F,L),type:R,role:"metric",aggregate:L};M.splice(P,0,W),g(M)}function T(D){const L=s.isTextDataType(D.data_type);s.isDateDataType(D.data_type);const F=[...l],R=t!==null?t:l.length;let M;L?M={...D,id:Ne(D.column_name),name:D.column_name,type:D.data_type,role:"groupby"}:M={...D,id:Ne(D.column_name),name:D.column_name,type:D.data_type,role:"groupby",label:Ge(D.column_name,"month"),granularity:"month"},F.splice(R,0,M),b(F)}function y(D){const L=s.isTextDataType(D.data_type);s.isDateDataType(D.data_type);const F=[...n],R=t!==null?t:n.length;let M;L?M={...D,id:Ne(D.column_name),name:D.column_name,type:D.data_type,role:"groupby"}:M={...D,id:Ne(D.column_name),name:D.column_name,type:D.data_type,role:"groupby",label:Ge(D.column_name,"month"),granularity:"month"},F.splice(R,0,M),p(F)}function O(D){const L=[...r],F=t!==null?t:r.length,R={...D,id:Ne(D.column_name),name:D.column_name,type:D.data_type,sql:s.getDefaultFilterSql(D.data_type,N,s.fmt(D.column_name)),role:"filter"};L.splice(F,0,R),j(L)}function E(D){var M,P,W,z,X,te,K,H;const{active:L,over:F}=D,R=L.data.current;if((R==null?void 0:R.type)==="column"&&F){const U=f.find(se=>se.column_name===L.id);if(!U)return;const ee=s.isNumberDataType(U.data_type),_=s.isTextDataType(U.data_type),V=s.isDateDataType(U.data_type);(_||V)&&(F.id===Ae||((M=F.data.current)==null?void 0:M.type)===as)&&y(U),(_||V)&&(F.id===Le||((P=F.data.current)==null?void 0:P.type)===ns)?T(U):(ee||_)&&(F.id===Me||((W=F.data.current)==null?void 0:W.type)===ys)?(ee&&v(U),_&&v(U,"COUNT")):C(U)&&(F.id===Ns||((z=F.data.current)==null?void 0:z.type)===Cs)&&O(U)}if(F&&((X=F.data.current)==null?void 0:X.type)===as&&n.some(U=>U.id===L.id)){const U=n.findIndex(_=>_.id===L.id),ee=n.findIndex(_=>_.id===F.id);if(U!==-1&&ee!==-1&&U!==ee){const _=[...n],[V]=_.splice(U,1);_.splice(ee,0,V),p(_)}}if(F&&((te=F.data.current)==null?void 0:te.type)===ns&&l.some(U=>U.id===L.id)){const U=l.findIndex(_=>_.id===L.id),ee=l.findIndex(_=>_.id===F.id);if(U!==-1&&ee!==-1&&U!==ee){const _=[...l],[V]=_.splice(U,1);_.splice(ee,0,V),b(_)}}if(F&&((K=F.data.current)==null?void 0:K.type)===ys&&a.some(U=>U.id===L.id)){const U=a.findIndex(_=>_.id===L.id),ee=a.findIndex(_=>_.id===F.id);if(U!==-1&&ee!==-1&&U!==ee){const _=[...a],[V]=_.splice(U,1);_.splice(ee,0,V),g(_)}}if(F&&((H=F.data.current)==null?void 0:H.type)===Cs&&r.some(U=>U.id===L.id)){const U=r.findIndex(_=>_.id===L.id),ee=r.findIndex(_=>_.id===F.id);if(U!==-1&&ee!==-1&&U!==ee){const _=[...r],[V]=_.splice(U,1);_.splice(ee,0,V),j(_)}}B(D),i(null),c(null),d(n),u(a),m(r),h(l)}function B(D){const{active:L,over:F}=D,R=L.data.current;if((R==null?void 0:R.type)===Ts&&F){const M=o.findIndex(W=>Ye(W.columnId)===L.id),P=o.findIndex(W=>Ye(W.columnId)===F.id);if(M!==-1&&P!==-1&&M!==P){const W=[...o],[z]=W.splice(M,1);W.splice(P,0,z),x(W)}}}function w(){i(null),c(null),d(n),u(a),m(r)}return{handleDragOver:I,handleDragEnd:E,handleDragStart:S,handleDragCancel:w,sensors:k}}function Ne(t){return`${t}-${s.v4()}`}function He(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 Ye(t){return`${Ts}-${t}`}function Ge(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 Jn({dataType:t}){const n=s.getDataType(t);return n==="string"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-blue-100 text-xs text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:e.jsx(ve,{className:"h-3 w-3"})}):n==="number"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-green-100 text-xs text-green-700 dark:bg-green-950 dark:text-green-300",children:e.jsx(De,{className:"h-3 w-3"})}):n==="date"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-purple-100 text-xs text-purple-700 dark:bg-purple-950 dark:text-purple-300",children:e.jsx(s.Calendar,{className:"h-3 w-3"})}):n==="boolean"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-orange-100 text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx(Re,{className:"h-3 w-3"})}):n==="json"?e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(_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($e,{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(We,{className:"h-3 w-3"})}):e.jsx("div",{className:"flex size-6 shrink-0 items-center justify-center rounded-sm bg-gray-100 text-xs text-gray-700 dark:bg-gray-950 dark:text-gray-300",children:e.jsx(ve,{className:"h-3 w-3"})})}function Xn({schemaName:t,tableName:n,columns:a,status:r}){const[o,l]=A.useState(""),[c,i]=A.useState("all"),d=s.useEditorStore(M=>M.sqlGen),u=s.useEditorStore(M=>M.isDevMode);s.useEditorStore(M=>M.selectedConnectionId);const m=s.useEditorStore(M=>{var P,W;return(W=(P=M.card)==null?void 0:P.queryConfig)==null?void 0:W.metricColumns});s.useEditorStore(M=>{var P,W;return(W=(P=M.card)==null?void 0:P.queryConfig)==null?void 0:W.groupByColumns});const h=s.useEditorStore(M=>M.selectedDatabaseName);s.useEditorStore(M=>M.selectedSchemaName),s.useEditorStore(M=>M.selectedTableName);const p=s.useEditorStore(M=>M.selectedDatamodelId);s.useDashboardStore(M=>M.dashboard.aiScopeTables);const{addToAIScope:g,removeFromAIScope:j}=s.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:b,setCardSql:f,setRunSql:N,setSqlGen:k,setIsShowingVisual:I}=s.useEditorActions(),{connectionType:S,modelItems:C,selectedDatamodelName:v}=s.useEditorAside();function T(M){var P;if(u){const W=s.createSqlGenConfig(M,d);k(W);const z=(P=C==null?void 0:C.find(te=>te.id===p))==null?void 0:P.name,X=s.getSql(W,s.fmt(t),s.fmt(n),z||"",S,h||"");X&&(f(X),N(!0))}if(!u){if(s.isTextDataType(M.data_type))if(m&&m.length>0){const W={...M,role:"groupby",id:Ne(M.column_name),name:M.column_name,type:M.data_type};b(W)}else{const W={...M,role:"metric",id:Ne(M.column_name),name:M.column_name,label:He(M.column_name,"COUNT"),type:M.data_type,aggregate:"COUNT"};x(W)}if(s.isDateDataType(M.data_type)){const W={...M,role:"groupby",id:Ne(M.column_name),name:M.column_name,type:M.data_type,label:Ge(M.column_name,"month"),granularity:"month"};b(W)}if(s.isNumberDataType(M.data_type)){const W={...M,role:"metric",id:Ne(M.column_name),name:M.column_name,label:He(M.column_name,"SUM"),type:M.data_type,aggregate:"SUM"};x(W)}}}function y(){const M=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:S,databaseName:h||""});I(!1);const P=S==="MSSQL"?`SELECT top 10 * FROM ${M}`:`SELECT * FROM ${M} LIMIT 10`;f(P),N(!0)}function O(){const M=s.getFormattedTableNameForQuery({schemaName:t,tableName:n,modelName:v,connectionType:S,databaseName:h||""});f(`SELECT COUNT(*) as count FROM ${M}`),N(!0)}const E=(a==null?void 0:a.filter(M=>M.column_name.toLowerCase().includes(o.toLowerCase())))||[],B=M=>s.isNumberDataType(M.data_type)?"number":"text",w=c==="all"?E:E.filter(M=>B(M)===c),D=E.filter(M=>B(M)==="text").length,L=E.filter(M=>B(M)==="number").length;function F(M){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:()=>T(M),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Jn,{dataType:M.data_type}),e.jsx("span",{children:M.column_name})]}),e.jsx("div",{onClick:P=>P.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(M.data_type)&&e.jsx(qn,{column:M})})]}):e.jsx(Kn,{onClick:T,column:M})}function R(){return e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:r!=="Success",onClick:y,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(ka,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:O,size:"sm",variant:"secondary",className:"grow",children:[r!=="Success"?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(nt,{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((M,P)=>e.jsx(s.Skeleton,{className:"h-8 w-full"},P))}):e.jsxs("div",{className:"flex grow flex-col",children:[e.jsxs("div",{className:"flex-shrink-0 space-y-3 px-4",children:[u&&e.jsx("div",{className:"flex items-center justify-center gap-2",children:R()}),a&&a.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:o,onChange:M=>l(M.target.value)})]}),E.length>0&&e.jsx(s.Tabs,{defaultValue:"all",value:c,onValueChange:M=>i(M),children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-3",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:E.length})]}),e.jsxs(s.TabsTrigger,{value:"text",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:D})]}),e.jsxs(s.TabsTrigger,{value:"number",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:L})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-4 pt-3",children:[w.length===0&&o&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',o,'"']}),w.length===0&&!o&&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:w==null?void 0:w.map(M=>e.jsx("div",{children:F(M)},M.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function yt({ColumnsComponent:t,type:n}){var J;const[a,r]=A.useState(!1),o=s.useEditorStore(Z=>Z.card),l=s.useEditorStore(Z=>Z.selectedConnectionId),c=s.useDashboardStore(Z=>Z.showFilters),i=s.useEditorStore(Z=>Z.selectedDatamodelId),d=s.useEditorStore(Z=>Z.selectedDatabaseName),u=s.useEditorStore(Z=>Z.selectedSchemaName),m=s.useEditorStore(Z=>Z.selectedTableName),h=s.useEditorStore(Z=>Z.isDevMode),{setSelectedTableName:p,setIsDevMode:g,setCardSql:j}=s.useEditorActions(),{connectionItems:x,modelItems:b,schemaItems:f,databaseItems:N,tableItems:k,columns:I,isConnectionsLoading:S,isModelsLoading:C,isConnectionsError:v,isModelsError:T,isDatabasesLoadingOrFetching:y,isDatabaseError:O,isSchemaLoadingOrFetching:E,isSchemaError:B,isColumnsError:w,isColumnsLoadingOrFetching:D,isTableLoadingOrFetching:L,isTableError:F,connectionType:R,isNonDbConnection:M,refetchDatabases:P,refetchModels:W,refetchSchemas:z,refetchTables:X,refetchColumns:te,refetchConnections:K,handleConnectionChange:H,handleDatabaseChange:U,handleSchemaChange:ee,handleDatamodelChange:_,handleTableChange:V,tableName:se,schemaName:ne}=s.useEditorAside(),{data:G,refetch:Y}=s.useDashboardCardQuery(o);function re(){return t?t(ne,se,I):e.jsx(Xn,{schemaName:ne,tableName:se,columns:I,status:D?"Loading...":w?"Error":"Success"})}function oe(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function le(Z){Z===!0?G&&(j(G.userSql),setTimeout(()=>{Y()},100)):j(""),g(Z)}function xe(){if(!l||R==="S3"||R==="API")return null;if(!i||i==="none")return e.jsx(Pe,{refetch:P,showNone:!0,onChange:U,isError:O,isLoading:y,items:N,value:d||"",title:"Database",type:"combobox"})}function pe(){if(l&&!M&&(!d||d==="none")&&(!i||i==="none"))return e.jsxs("div",{className:"grid grid-cols-3",children:[e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(s.Separator,{})})]})}function me(){if(!l||R==="S3"||R==="API")return null;if(!d||d==="none")return e.jsx(Pe,{refetch:W,showNone:!0,onChange:_,isError:T,isLoading:C,items:b,value:i||"",title:"Model",type:"combobox"})}function fe(){return!l||R==="S3"||R==="API"||!d||d==="none"?null:e.jsx(Pe,{refetch:z,onChange:ee,isError:B,isLoading:E,items:f,value:u||"",title:"Schema",type:"combobox"})}function $(){function Z(){let q=!1;return R==="API"?(q=!1,q):((R==="S3"||l&&d&&d!=="none"&&u)&&(q=!0),q)}return Z()?e.jsx(Pe,{refetch:X,onChange:V,isError:F,items:k,isLoading:L,value:m||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:s.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!c}),children:[e.jsxs("section",{className:s.cn("px-4",{"px-4 pb-0 pt-4":a,"px-4 py-4":!a}),children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Direct Source"}),e.jsx(s.Button,{onClick:()=>r(!a),size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:a?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),!a&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Pe,{refetch:K,items:x,title:"Connection",value:l||"",onChange:H,isLoading:S,isError:v,type:"combobox",connectionTooltip:((J=x==null?void 0:x.find(Z=>Z.id===l))==null?void 0:J.type)||""}),xe(),pe(),me(),fe(),$()]})]}),re(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:n==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:h,onCheckedChange:le,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:oe,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(Ia,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function Nt({error:t,errorSql:n,onSendFeedback:a,className:r,showFeedbackButton:o=!0}){const[l,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:l,onOpenChange:c,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:l?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"]})})})}),o&&a&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:a,children:[e.jsx(Ma,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),n&&e.jsx(s.Collapsible,{open:l,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 Ct({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){const o=s.useEditorStore(u=>u.isDevMode),{setIsDevMode:l,setCardSql:c,setRunSql:i}=s.useEditorActions();function d(){l(!o),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(Nt,{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"})})})]}),!o&&t&&!n&&e.jsxs(s.Button,{onClick:d,variant:"secondary",size:"sm",children:[e.jsx(ga,{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(Na,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function St({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(ua,{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(Ct,{errorSql:a,sql:t,error:n,onDebugWithAssistant:r})})]})}function Zn(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 wt(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(x=>x.theme),r=s.useEditorStore(x=>x.frame),o=s.useEditorStore(x=>x.card),l=s.useEditorStore(x=>x.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(o),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),m=A.useRef(),h=A.useRef({}),p=r.cards.find(x=>x.id===l),g=A.useCallback(()=>{let x="";return t==="python"&&(x=(p==null?void 0:p.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(x=(p==null?void 0:p.sql)||""),x},[t,p]);A.useEffect(()=>{if(l&&o.id&&o.id!==l){if(m.current&&c){const x=m.current.getModel();x&&(h.current[o.id]=x);let b=h.current[l];if(!b){const f=g();b=c.editor.createModel(f,t),h.current[l]=b}m.current.setModel(b)}d(l,o),u(!0)}},[l,o,d,c,u,t,g]),A.useEffect(()=>{if(!c)return;const x=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",b=a==="system"?x:a;c.editor.defineTheme("default",{base:b==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":b==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[n,a,c]),A.useEffect(()=>{const x=m.current;x&&c&&o&&x.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,o]);function j(x,b){if(m.current=x,!h.current[o.id]){const f=x.getModel(),N=g();h.current[o.id]=f||(b==null?void 0:b.editor.createModel(N,t))||x.getModel()}x.setModel(h.current[o.id])}return{handleEditorDidMount:j}}function er(){const t=s.useEditorStore(c=>c.card.sql),n=s.useEditorStore(c=>c.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:o}=wt("sql");function l(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:l,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:o})]})}function sr(){const t=s.useEditorStore(o=>o.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=wt("python");function r(o){n(o)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:a})}function tr({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 ks({variant:t="outline"}){var c;const{setCardSql:n}=s.useEditorActions();s.useEditorStore(i=>i.frame);const a=s.useEditorStore(i=>i.card);ws(((c=a.customCardPreferences)==null?void 0:c.url)||""),s.useEditorStore(i=>i.selectedSchemaName),s.useEditorStore(i=>i.selectedDatamodelId),s.useEditorStore(i=>i.selectedDatabaseName),s.useEditorStore(i=>i.selectedTableName),s.useEditorStore(i=>i.selectedConnectionId),s.useEditorStore(i=>i.isShowingVisual),a.sql;const r=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:o}=Ds();function l(){const i=o();r==null||r(i)}return e.jsxs(s.Button,{onClick:l,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function ar(){const t=s.useQueryClient(),[n,a]=A.useState(!1),r=s.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{setIsVisualEditing:o}=s.useDashboardActions(),{getUpdatedFrame:l}=Ds(),c=s.useSelectedVisual(),i=s.useUpdateVisualMutation(),d=()=>{const u=l();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}a(!0),i.mutate({visualId:c.id,data:{frameObject:u}},{onSuccess:()=>{a(!1),o(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{a(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:d,className:"h-8",size:"sm",children:[n&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!n&&e.jsxs(e.Fragment,{children:[e.jsx(bs,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function Es(){const{setTempQueryData:t,setSqlGen:n}=s.useEditorActions(),a=s.useQueryClient(),r=s.useEditorStore(d=>d.tempQueryData),o=s.useEditorStore(d=>d.onClose),l=s.useEditorStore(d=>d.card),{queryKey:c}=s.useDashboardCardQuery(l);function i(){if(r){const{queryKey:d,queryData:u}=r;d&&u&&a.setQueryData(d,u)}n({}),o==null||o()}return e.jsxs(s.Button,{onClick:i,className:"h-8",size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function os(){const{setTempQueryData:t}=s.useEditorActions(),n=s.useQueryClient(),a=s.useEditorStore(b=>b.isDevMode),r=s.useEditorStore(b=>b.tempQueryData),o=s.useEditorStore(b=>b.card),{queryKey:l}=s.useDashboardCardQuery(o),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:u,setCardPreferences:m,updateDataSource:h,clearQueryConfig:p,setCardConfig:g,setCardType:j}=s.useEditorActions();function x(){const b=n.getQueryData(l);r!=null&&r.queryData||t({queryKey:l,queryData:b}),n.setQueryData(l,null),n.removeQueries({queryKey:l,exact:!0}),a&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),p(),g(void 0),d(""),u(""),m({}),j("bar")}return e.jsxs(s.Button,{onClick:x,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function nr(){const t=s.useQueryClient(),[n,a]=A.useState(!1),[r,o]=A.useState(!1);s.useEditorStore(z=>z.frame);const l=s.useEditorStore(z=>z.card);s.useEditorStore(z=>z.isShowingVisual),s.useEditorStore(z=>z.selectedConnectionId),s.useEditorStore(z=>z.tempQueryData),s.useEditorStore(z=>z.selectedDatabaseName),s.useEditorStore(z=>z.selectedDatamodelId),s.useEditorStore(z=>z.selectedSchemaName);const c=s.useEditorStore(z=>z.showAIDialog);s.useEditorStore(z=>z.selectedTableName);const i=s.useEditorStore(z=>{var X;return(X=z==null?void 0:z.card)==null?void 0:X.sql}),d=s.useEditorStore(z=>{var X;return(X=z==null?void 0:z.card)==null?void 0:X.python}),{sheetFilterValues:u}=s.useSheetFilterValues(),{setCardCustomCfg:m,setQueryResultColumns:h,setCardSql:p,setTempQueryData:g,setPythonStdOut:j,setCardPreferences:x,setCardType:b,setCardPython:f,runAssistant:N,setShowAIDialog:k}=s.useEditorActions();s.useEditorStore(z=>z.onSave),s.useEditorStore(z=>z.onClose),s.useEditorStore(z=>z.actions.setSqlGen);const I=s.useEditorStore(z=>z.runSql),S=s.useEditorStore(z=>z.actions.setRunSql),C=s.useEditorStore(z=>z.actions.setIsSqlRunning),{data:v,isLoading:T,isFetching:y,isSuccess:O,isError:E,error:B,errorSql:w,queryKey:D,refetch:L,errorMessage:F}=s.useDashboardCardQuery(l);A.useEffect(()=>{if(v&&(v.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),j((v==null?void 0:v.output)||""),v.records.length>0)){const{dimensionKeys:z}=s.getKeys(v.records);h(z)}},[v,h,j]),A.useEffect(()=>{(T||y)&&C(!0),(E||O)&&C(!1),E&&(h([]),j(""))},[T,y,v,j,E,O,C,h,B]),A.useEffect(()=>{I&&(t.getQueryData(D)||L(),S(!1))},[I,L,S,D,t]);async function R(){const z=`Can you help me debug this query?
|
|
332
332
|
|
|
333
333
|
Error:
|
|
334
334
|
|