react-semaphor 0.0.624 → 0.0.626

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.
@@ -1,4 +1,4 @@
1
- "use strict";const e=require("react/jsx-runtime"),s=require("./index-tXl52zph.js"),I=require("react");require("react-dom");function ea(t){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return a.default=t,Object.freeze(a)}const ke=ea(I);/**
1
+ "use strict";const e=require("react/jsx-runtime"),s=require("./index-BgTQ-g-l.js"),I=require("react");require("react-dom");function ea(t){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return a.default=t,Object.freeze(a)}const ke=ea(I);/**
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(),a=s.useDashboardStore(n=>n.actions.setDashboardTheme);return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"h-7 p-2",variant:"ghost",size:"sm",children:[e.jsx(qa,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(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"),a("light")},children:"Light"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("dark"),a("dark")},children:"Dark"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("system"),a("system")},children:"System"})]})]})}function es(t){var a;return{...t,sheets:(a=t==null?void 0:t.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(l=>{var o;return{...l,cards:(o=l.cards)==null?void 0:o.map(c=>at(c))}})}})}}function at(t){return{...t,customCfg:Ka(t.customCfg),data:[]}}function Ka(t){var a,n;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(n=(a=t==null?void 0:t.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function Ja(t,a,n,r){if(!r)return null;const l=JSON.stringify(a);return await s.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:t,template:l,filterValues:n,operation:"create"})}async function js(t,a){if(!a)return null;const{id:n,template:r,filterValues:l,isDefault:o,shared:c}=t;return await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:l,isDefault:o,shared:c,operation:"update"})}async function Qa(t,a){return a?await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:t}):null}function Xa(){const[t,a]=I.useState(""),[n,r]=I.useState(!1),l=s.useDashboardStore(p=>p.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=I.useState(!1),[u,m]=I.useState(!1),h=s.useDashboardStore(p=>p.dashboard),f=s.useDashboardStore(p=>p.filterValues),{authToken:g}=s.useSemaphorContext();async function j(){d(!0);const p=es(h),b=await Ja(t,p,f,g==null?void 0:g.accessToken);b&&(o([...l||[],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:p=>{a(p.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),n&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:j,disabled:i,children:i?"Creating...":"Add"})})]})]})}function Za(){const[t,a]=I.useState(!1),n=s.useDashboardStore(m=>m.lenses),r=s.useDashboardStore(m=>m.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function i(m){o(m)}async function d(m){if(await Qa(m,c==null?void 0:c.accessToken)){const f=n==null?void 0:n.filter(g=>g.id!==m);l(f||[]),o("original")}}async function u(m){const h=n==null?void 0:n.map(j=>j.id===m.id?{...j,isDefault:!m.isDefault}:{...j,isDefault:!1});l(h||[]);const f={...m,isDefault:!m.isDefault};await js(f,c==null?void 0:c.accessToken);const g=n==null?void 0:n.find(j=>j.isDefault);if(g&&g.id!==m.id){const j={...g,isDefault:!1};await js(j,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:a,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(va,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:i,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(m=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:m.id,children:[e.jsx("p",{children:m.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:h=>{h.preventDefault(),u(m)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!m.isDefault,"text-green-500":m.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:h=>{h.preventDefault(),d(m.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},m.id))]})]})]})}function en({iconClassName:t}){const[a,n]=I.useState(!1),[r,l]=I.useState(""),[o,c]=I.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;n(!1),l(""),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:()=>n(!0),children:[e.jsx(ka,{className:"mr-2 h-4 w-4"}),"Download Protected PDF"]})]})]}),e.jsx(s.Dialog,{open:a,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Download Protected PDF"}),e.jsx(s.DialogDescription,{children:"Enter a password to protect your PDF. The PDF will be encrypted and require this password to open."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Input,{id:"password",type:o?"text":"password",value:r,onChange:m=>l(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(!o),children:o?e.jsx(s.EyeOff,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(s.Eye,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:u,disabled:!r,children:"Download"})]})]})})]})}function nt({triggerButtonClassName:t}){const[a,n]=I.useState(!1),[r,l]=I.useState("create"),[o,c]=I.useState("current"),i=s.useDashboardStore(N=>{var S;return(S=N.dashboard)==null?void 0:S.sheets}),d=s.useDashboardStore(N=>N.selectedSheetId),u=i==null?void 0:i.find(N=>N.id===d),m=i&&i.length>1,{schedules:h,isLoading:f,createSchedule:g,deleteSchedule:j,isSubmitting:p,submitError:b,deletingId:x,refetch:v}=s.useSchedule({reportType:"DASHBOARD"}),k=async N=>{try{const S={format:"pdf",sheetSelection:o,pdfOptions:{pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0}};o==="current"&&u&&(S.currentSheetId=u.id,S.currentSheetName=u.title),await g({...N,reportParams:S}),l("active"),s.ue.success("Schedule created successfully!")}catch(S){console.error("Failed to create schedule:",S)}},L=async N=>{try{await j(N)}catch(S){console.error("Failed to delete schedule:",S)}};return e.jsxs(s.Popover,{open:a,onOpenChange:n,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:N=>l(N),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(Zs,{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:o,onValueChange:N=>c(N),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:o==="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:p,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:L,isDeleting:x,isLoading:f,onRefresh:v}):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 rt(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,a)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},a))})]})})}function sn({visual:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onAddVisual:o,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:u,onShareVisual:m,formatDate:h}){var S,y,D;const{selectVisual:f}=s.useManagementActions(),g=s.useIsVisualSelected(t.id),{isConsoleMode:j}=s.useDashboardPreferences(),p=s.useDashboardStore(C=>C.actions.setIsDashboardPanelOpen),[b,x]=I.useState(!1),[v,k]=I.useState(!1);I.useEffect(()=>{n?(x(!0),k(!0)):v&&(x(!1),k(!1))},[n,v]);const L=()=>e.jsx(ns,{className:"h-4 w-4"}),N=()=>{f(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:N,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:L()}),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:C=>i==null?void 0:i(t.id,{title:C}),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:C=>i==null?void 0:i(t.id,{description:C}),isEditable:t.ownership.isOwner&&g,isPending:l,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:C=>C.stopPropagation(),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:C=>{C.stopPropagation(),o(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:x,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:C=>{C.stopPropagation(),o(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.preventDefault(),C.stopPropagation(),u(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.stopPropagation(),c==null||c(t)},children:[e.jsx(Ba,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.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:C=>{C.stopPropagation(),d(t),p(!1)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((S=t.ownership.createdBy)==null?void 0:S.type)==="tenant"||((y=t.ownership.createdBy)==null?void 0:y.type)==="organization"&&j)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Be,{className:"h-3 w-3"}),e.jsx("span",{children:((D=t.ownership.createdBy)==null?void 0:D.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 lt({value:t,onChange:a,placeholder:n="Search users by name, email, or department..."}){return e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:n,value:t,onChange:r=>a(r.target.value),className:"pl-9"})]})}function ss({currentRole:t,onRoleChange:a,roleOptions:n,disabled:r=!1,className:l="",allowDropdown:o=!0}){var d;const c=((d=n.find(u=>u.value===t))==null?void 0:d.label)||t,i=n.filter(u=>u.value!==t);return o?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${l}`,onClick:()=>console.log("Badge clicked:",{currentRole:t,disabled:r,allowDropdown:o}),children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.map(u=>e.jsx(s.DropdownMenuItem,{onClick:()=>{console.log("Dropdown item clicked:",{currentRole:t,newRole:u.value,disabled:r}),a(u.value)},disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})},u.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${l}`,children:c})}function ot({selectedUsers:t,selectedUserObjects:a,onRemove:n,onRoleChange:r,getRoleOptions:l}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(o=>n(o.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:a.map(o=>{const c=t.find(d=>d.id===o.id),i=l(o.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[o.name,e.jsx(ss,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(o.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>n(o.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},o.id)})}),e.jsx(s.Separator,{})]})}function it({usersToRemove:t,allUsers:a,onRemove:n}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium text-destructive",children:["Users to Remove Access (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(r=>n(r)),className:"h-auto p-1 text-xs text-destructive hover:text-destructive",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:a.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>n(r.id),className:"ml-1 rounded-full p-0.5 hover:bg-destructive-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},r.id))}),e.jsx(s.Separator,{})]})}function ct({usersToUpdate:t,allUsers:a,onRemove:n,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),o=i=>{const d=a.find(u=>u.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=l.find(u=>u.value===i);return(d==null?void 0:d.label)||i};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(i=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:o(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>n(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function dt(t,a={}){const{enabled:n=!0,eventType:r="mousedown"}=a,l=I.useRef(null);return I.useEffect(()=>{const o=c=>{const i=c.target;l.current&&l.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return n&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,n,r]),l}function je(t,a){var n;return((n=a.find(r=>r.value===t))==null?void 0:n.label)||t}function tn(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function ut(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function an(t,a,n){const r=ut(t),l=(n==null?void 0:n.type)||"organization";if(!(!a||!a.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in a.shares)return(a.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function nn({user:t}){return ut(t)==="tenant"?e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:t.role==="POWER_USER"?"Power User":"Viewer"}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:t.role==="ADMIN"?"Admin":t.role==="POWER_USER"?"Power User":"Viewer"})}function rn({user:t,userShare:a,usersToUpdate:n,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(a!=null&&a.role))return null;const c=tn((r==null?void 0:r.type)||""),i=n.some(h=>h.id===t.id),d=n.find(h=>h.id===t.id),u=d?d.newRole:a==null?void 0:a.role,m=l(t.type);return a?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(ss,{currentRole:u,onRoleChange:h=>{o(t.id,a.role,h)},roleOptions:m,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:je(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function ln({hasAccess:t,isUserRemoving:a,isSelected:n,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!a&&e.jsxs(s.Badge,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Has Access"]}),a&&e.jsxs(s.Badge,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[e.jsx(s.X,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),n&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(Ye,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function on({isUserRemoving:t,isSelected:a,hasAccess:n,isRemoving:r,isSharing:l}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),a&&!n&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:l?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Sharing..."]}):"Will share"})]})}function cn({existingShares:t,allUsers:a,getRoleOptions:n,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],d=c.specificTenantUsers||[],u=c.orgWide||[],m=c.orgUsersOnly||[],h=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((f,g)=>{var x,v;const j=((x=a.find(k=>k.id===f.orgUserId))==null?void 0:x.name)||"Unknown User",p=((v=a.find(k=>k.id===f.orgUserId))==null?void 0:v.type)||"",b=je(f.role,n(p));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((f,g)=>{var x,v;const j=((x=a.find(k=>k.id===f.tenantUserId))==null?void 0:x.name)||"Unknown User",p=((v=a.find(k=>k.id===f.tenantUserId))==null?void 0:v.type)||"",b=je(f.role,n(p));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((f,g)=>{const j=je(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children: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((f,g)=>{const j=je(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children: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((f,g)=>{const j=je(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children: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=a.find(p=>p.id===d.tenantUserId))==null?void 0:g.name)||"Unknown User",h=((j=a.find(p=>p.id===d.tenantUserId))==null?void 0:j.type)||"",f=je(d.role,n(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:f})]},u)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:i.map((d,u)=>{const m=je(d.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},u)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const o=t.shares.specificTenantUsers||[],c=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",o.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[o.slice(0,3).map((i,d)=>{var f,g;const u=((f=a.find(j=>j.id===i.tenantUserId))==null?void 0:f.name)||"Unknown User",m=((g=a.find(j=>j.id===i.tenantUserId))==null?void 0:g.type)||"",h=je(i.role,n(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),o.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,d)=>{const u=je(i.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},d)})})]}),!o.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function dn({isInitialLoading:t,searchQuery:a,availableUsers:n}){return t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):n.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:a?"No users found matching your search.":"No users available to share with."}):null}function un({user:t,userShare:a,isUserRemoving:n,hasAccess:r,hasAccessFromAPI:l,isSelected:o,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:h,handleUpdateAccess:f,handleUserRoleChange:g}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!n?"border border-green-200 bg-green-50":n?"border border-red-200 bg-red-50":o?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:l?!n:o,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{l?n?m(t.id):h(t.id):m(t.id)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:t.name}),e.jsx(nn,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?e.jsx(ss,{currentRole:a==null?void 0:a.role,onRoleChange:j=>f(t.id,a.role,j),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(rn,{user:t,userShare:a,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:f}),o&&!l&&e.jsx("div",{onClick:j=>j.stopPropagation(),children:e.jsx(ss,{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:n,isSelected:o,hasAccessFromAPI:l}),e.jsx(on,{isUserRemoving:n,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function mt({existingShares:t,isInitialLoading:a,isSearching:n,getRoleOptions:r,allUsers:l=[],currentUser:o,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),g=s.useShareSearchQuery(),j=s.useShareManagementActions(),p=c||(N=>{const S=m.some(D=>D.id===N),y=h.includes(N);S?j.removeSelectedUser(N):y?j.removeUserFromRemove(N):j.addSelectedUser({id:N,role:"VIEWER"})}),b=i||j.updateSelectedUserRole,x=d||j.addUserToRemove,v=u||((N,S,y)=>{j.addUserToUpdate({id:N,currentRole:S,newRole:y})}),k=l,L=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:l,getRoleOptions:r,currentUser:o})})]})})]}),(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(N=>({id:N.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:a,isSearching:n,searchQuery:g,availableUsers:k||[]}),!a&&!n&&(k==null?void 0:k.length)>0&&k.map(N=>{const S=t?an(N,t,o):void 0,y=L.includes(N.id),D=!!S,C=D&&!y,B=m.some(T=>T.id===N.id),w=m.find(T=>T.id===N.id),F=r(N.type);return e.jsx(un,{user:N,userShare:S,isUserRemoving:y,hasAccess:C,hasAccessFromAPI:D,isSelected:B,selectedUser:w,roleOptions:F,currentUser:o,usersToUpdate:f,handleUserToggle:p,handleRemoveAccess:x,handleUpdateAccess:v,handleUserRoleChange:b},N.id)})]})]})}function ht({shareType:t,onShareTypeChange:a,currentUser:n,options:r}){const l=(n==null?void 0:n.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:a,className:`grid grid-cols-${r.length} gap-4`,children:r.map(o=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:o.value,id:o.value,className:"peer sr-only",disabled:o.disabled}),e.jsxs(s.Label,{htmlFor:o.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${o.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[o.icon||e.jsx(Be,{className:"mb-3 h-6 w-6"}),e.jsxs("div",{className:"space-y-1 text-center",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:o.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o.description})]})]})]},o.value))}),!l&&r.some(o=>o.value==="all_users")&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only admins, authors, power users, and super admins can share with all users."})]})}const Te=()=>[{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:a,isSharing:n,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:o=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),u=Te().filter(v=>v.value==="VIEWER"||v.value==="EDITOR"||v.value==="CONTRIBUTOR"),m=a.role!=="NONE"?a.role:"NONE",h=l?l.newRole:m,f=a.role!=="NONE"&&!o&&(!l||l.newRole===m),g=l!==null&&l.newRole!==m,j=o,p=m==="NONE"||!m,b=v=>{switch(v){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"})}},x=v=>{r(m,v)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",g&&!j&&!p?"border-orange-300 bg-orange-50":f?"border-green-300 bg-green-50":j||p?"border-destructive bg-destructive/10":""),children:[e.jsxs(s.CardHeader,{children:[e.jsxs(s.CardTitle,{className:"flex items-center gap-2 text-base",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Share with All"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="specificOrgUsers"?"Org":"Tenant"," ","Users",f&&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||p)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:j||p?"No access for all users.":"This will share the dashboard with all users in your "+((t==null?void 0:t.type)==="organization"?"organization":"tenant")+". Select an access level below."})]}),e.jsx(s.CardContent,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Select Access Level:"}),e.jsxs(s.HoverCard,{children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-4 w-4 p-0 text-muted-foreground hover:text-foreground",children:e.jsx(s.Info,{className:"h-3 w-3"})})}),e.jsx(s.HoverCardContent,{className:"w-80",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Share with All Users"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["This action will share the dashboard with all users in your"," ",(t==null?void 0:t.type)==="organization"?"organization":"tenant",". Users will receive the selected access level."]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Viewer:"})," Can view the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Editor:"})," Can view and edit the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Contributor:"})," Can view, edit, and share the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"None:"})," No access for all users"]})]})]})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:u.map(v=>e.jsxs(s.Button,{variant:h===v.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>x(v.value),disabled:n||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[b(v.value),e.jsx("span",{className:"font-medium",children:v.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:v.description})]},v.value))})]})})]})})}function xt({currentUser:t,currentShare:a,isSharing:n,isUpdating:r,isRemoving:l,onUpdateAccess:o,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const u=p=>p==="OWNER"?"CONTRIBUTOR":p,h=a?{role:u(a.role)}:{role:"NONE"},f=i?{currentRole:u(i.currentRole),newRole:u(i.newRole)}:null,g=(p,b)=>{o(p,b)},j=()=>{c()};return e.jsx(mn,{currentUser:t,currentShare:h,isSharing:n,isUpdating:r,isRemoving:l,onUpdateAccess:g,onRemoveAccess:j,allUsersToUpdate:f,allUsersToRemove:d})}const hn=async(t,a={})=>{const n={};return a.search&&(n.search=a.search),a.type&&(n.type=a.type),a.active!==void 0&&(n.active=a.active.toString()),a.tenantId&&(n.tenantId=a.tenantId),a.limit&&(n.limit=a.limit.toString()),a.offset&&(n.offset=a.offset.toString()),a.page&&(n.page=a.page.toString()),a.pageSize&&(n.pageSize=a.pageSize.toString()),await s.getRequest("https://semaphor.cloud/api/management/v1/unified-users",t,n)};function xn(t={}){var o,c,i;const{authToken:a,tokenProps:n}=s.useSemaphorContext(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),l=s.useQuery({queryKey:["unified-users",t],queryFn:()=>hn((a==null?void 0:a.accessToken)||"",t),enabled:!!(a!=null&&a.accessToken)&&!!r,retry:(d,u)=>u instanceof Error&&u.message.includes("401")||u instanceof Error&&u.message.includes("403")?!1:d<2,retryDelay:d=>Math.min(1e3*2**d,3e4)});return{users:((o=l.data)==null?void 0:o.users)||[],userContext:(c=l.data)==null?void 0:c.userContext,total:((i=l.data)==null?void 0:i.total)||0,isLoading:l.isLoading,isError:l.isError,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function De(t){const{debouncedSearchQuery:a,resourceId:n,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:o}=t,c=I.useMemo(()=>({search:a,active:!0,...l?{type:l}:{},...l==="tenant"&&o?{tenantId:o}:{}}),[a,l,o]),{users:i,isLoading:d,isError:u}=xn(c),m=s.useResourceShares(r,n);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function pn({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var te,X;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),f=s.useShareSelectedUsers(),g=s.useShareUsersToRemove(),j=s.useShareUsersToUpdate(),p=s.useShareCurrentMode(),b=s.useShareOrgWideRole(),x=s.useShareManagementActions(),[v,k]=I.useState("specific_users"),L=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},N=()=>{if(i==="tenant"&&d)return d},{allUsers:S,existingShares:y,isLoadingUsers:D}=De({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:L(),tenantId:N()});I.useEffect(()=>{x.setCurrentContext("org-tab"),x.setCurrentMode(v==="all_users"?"allOrgUsers":"specificOrgUsers")},[x,v]);const C=$=>{var _,J;const H=$;if(k(H),r==null||r(H),x.setCurrentContext("org-tab"),H==="specific_users")x.setCurrentMode("specificOrgUsers");else if(H==="all_users"){x.setCurrentMode("allOrgUsers");const z=(J=(_=y==null?void 0:y.shares)==null?void 0:_.orgUsersOnly)==null?void 0:J[0];z&&z.role!==void 0&&x.setOrgWideRole(z.role)}},B=S.filter($=>$.name.toLowerCase().includes(u.toLowerCase())||$.email.toLowerCase().includes(u.toLowerCase())),w=S.filter($=>f.some(H=>H.id===$.id)),F=$=>{var z,U;const H=f.some(Z=>Z.id===$),_=g.includes($),J=(U=(z=y==null?void 0:y.shares)==null?void 0:z.specificOrgUsers)==null?void 0:U.some(Z=>Z.orgUserId===$);H?x.removeSelectedUser($):_?x.removeUserFromRemove($):J||x.addSelectedUser({id:$,role:"VIEWER"})},T=($,H)=>{x.updateSelectedUserRole($,H)},E=$=>{x.addUserToRemove($),x.removeSelectedUser($)},A=$=>{x.removeUserFromRemove($)},R=$=>{x.removeUserFromUpdate($)},M=($,H)=>{x.setOrgWideRole(H)},O=()=>{x.setOrgWideRole((P==null?void 0:P.role)||"NONE")},P=(X=(te=y==null?void 0:y.shares)==null?void 0:te.orgUsersOnly)==null?void 0:X[0];I.useEffect(()=>{v==="all_users"&&P&&P.role!==void 0&&x.setOrgWideRole(P.role)},[v,P,x]);const K=D,Y=!1;return n?e.jsxs(e.Fragment,{children:[e.jsx(ht,{shareType:v,onShareTypeChange:C,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(Be,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(n==null?void 0:n.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),v==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(lt,{value:u,onChange:m}),e.jsx(ot,{selectedUsers:f,selectedUserObjects:w,onRemove:F,onRoleChange:T,getRoleOptions:Te}),e.jsx(it,{usersToRemove:g,allUsers:B,onRemove:A}),e.jsx(ct,{usersToUpdate:j,allUsers:B,onRemove:R,getRoleOptions:Te}),e.jsx(mt,{existingShares:y,isInitialLoading:K,isSearching:Y,resource:t,onShare:()=>{},getRoleOptions:Te,allUsers:B,currentUser:n,handleUserToggle:F,handleUserRoleChange:T,handleRemoveAccess:E,handleUpdateAccess:($,H,_)=>{x.addUserToUpdate({id:$,currentRole:H,newRole:_})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(xt,{currentUser:n,currentShare:P,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:M,onRemoveAccess:O,allUsersToUpdate:p==="allOrgUsers"&&b!==((P==null?void 0:P.role)||"NONE")?{currentRole:(P==null?void 0:P.role)||"NONE",newRole:b}:null,allUsersToRemove:p==="allOrgUsers"&&(P==null?void 0:P.role)===void 0})})]}):null}function Vs({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var z;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),g=s.useShareCurrentMode(),j=s.useShareTenantWideRole(),p=s.useShareAllTenantsRole(),b=s.useShareSelectedTenant(),x=s.useShareManagementActions(),{data:v,isLoading:k}=s.useTenants({enabled:(n==null?void 0:n.type)==="organization"}),[L,N]=I.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");I.useEffect(()=>{(n==null?void 0:n.type)==="tenant"?(x.setCurrentContext("tenant-dialog"),x.setCurrentMode("specificTenantUsers")):(x.setCurrentContext("tenant-tab"),x.setCurrentMode("allTenants"))},[x,n==null?void 0:n.type]);const S=U=>{var le,V,se,ne;N(U);let Z;if(U==="specific_tenant_users"?Z="specific_users":U==="all_tenant_users"||U==="all_tenants"?Z="all_users":Z="specific_users",r==null||r(Z),(n==null?void 0:n.type)==="tenant"?(x.setCurrentContext("tenant-dialog"),U==="specific_tenant_users"?x.setCurrentMode("specificTenantUsers"):U==="all_tenant_users"&&(x.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&x.setSelectedTenant(n.tenantId))):(x.setCurrentContext("tenant-tab"),U==="specific_tenant_users"?x.setCurrentMode("specificTenantUsers"):U==="all_tenant_users"?x.setCurrentMode("allTenantUsers"):U==="all_tenants"&&x.setCurrentMode("allTenants")),U==="all_tenant_users"){const q=(V=(le=C==null?void 0:C.shares)==null?void 0:le.tenantWide)==null?void 0:V[0];q&&q.role!==void 0&&x.setTenantWideRole(q.role)}else if(U==="all_tenants"){const q=(ne=(se=C==null?void 0:C.shares)==null?void 0:se.allTenantsOnly)==null?void 0:ne[0];q&&q.role!==void 0&&x.setAllTenantsRole(q.role)}},y=U=>{x.setSelectedTenant(U)},{allUsers:D,existingShares:C,isLoadingUsers:B,isErrorLoadingUsers:w,isLoadingShares:F,isErrorLoadingShares:T}=De({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:b}),E=U=>{var se,ne;const Z=m.some(q=>q.id===U),le=h.includes(U),V=(ne=(se=C==null?void 0:C.shares)==null?void 0:se.specificTenantUsers)==null?void 0:ne.some(q=>q.tenantUserId===U);Z?x.removeSelectedUser(U):le?x.removeUserFromRemove(U):V||x.addSelectedUser({id:U,role:"VIEWER"})},A=(U,Z)=>{x.updateSelectedUserRole(U,Z)},R=U=>{x.addUserToRemove(U),x.removeSelectedUser(U)},M=U=>{x.removeUserFromRemove(U)},O=U=>{x.removeUserFromUpdate(U)},P=(U,Z,le)=>{x.addUserToUpdate({id:U,currentRole:Z,newRole:le})},K=(U,Z)=>{L==="all_tenant_users"?x.setTenantWideRole(Z):L==="all_tenants"&&x.setAllTenantsRole(Z)},Y=()=>{L==="all_tenant_users"?x.setTenantWideRole("VIEWER"):L==="all_tenants"&&x.setAllTenantsRole("VIEWER")},X=(()=>{var U,Z,le,V;return g==="allTenants"?(Z=(U=C==null?void 0:C.shares)==null?void 0:U.allTenantsOnly)==null?void 0:Z[0]:g==="allTenantUsers"?(V=(le=C==null?void 0:C.shares)==null?void 0:le.tenantWide)==null?void 0:V[0]:null})();I.useEffect(()=>{var U,Z,le,V;if(L==="all_tenant_users"){const se=(Z=(U=C==null?void 0:C.shares)==null?void 0:U.tenantWide)==null?void 0:Z[0];se&&se.role!==void 0&&x.setTenantWideRole(se.role)}else if(L==="all_tenants"){const se=(V=(le=C==null?void 0:C.shares)==null?void 0:le.allTenantsOnly)==null?void 0:V[0];se&&se.role!==void 0&&x.setAllTenantsRole(se.role)}},[L,C,x]);const $=D.filter(U=>m.some(Z=>Z.id===U.id)),H=B||F,_=w||T,J=()=>(n==null?void 0:n.type)==="tenant"||L==="all_tenants"?!0:b&&(L==="specific_tenant_users"||L==="all_tenant_users");return e.jsxs(e.Fragment,{children:[_&&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"})]})}),!_&&n&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(ht,{shareType:L,onShareTypeChange:S,currentUser:n,options:(n==null?void 0:n.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(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(Be,{className:"mb-3 h-6 w-6 text-orange-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:e.jsx(Fs,{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(Be,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(n==null?void 0:n.type)==="organization"&&(L==="specific_tenant_users"||L==="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:b||"",onValueChange:y,disabled:k,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:k?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(z=v==null?void 0:v.tenants)==null?void 0:z.map(U=>e.jsx(s.SelectItem,{value:U.id,children:U.name},U.id))})]})]}),J()?e.jsx(e.Fragment,{children:L==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(lt,{value:i,onChange:u}),e.jsx(ot,{selectedUsers:m,selectedUserObjects:$,onRemove:U=>E(U),onRoleChange:A,getRoleOptions:Te}),e.jsx(it,{usersToRemove:h,allUsers:D,onRemove:M}),e.jsx(ct,{usersToUpdate:f,allUsers:D,onRemove:O,getRoleOptions:Te}),e.jsx(mt,{existingShares:C,isInitialLoading:!!H,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:Te,allUsers:D,currentUser:n,handleUserToggle:E,handleUserRoleChange:A,handleRemoveAccess:R,handleUpdateAccess:P})]}):L==="all_tenant_users"||L==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(xt,{currentUser:n,currentShare:X,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:K,onRemoveAccess:Y,allUsersToUpdate:g==="allTenantUsers"&&((X==null?void 0:X.role)===void 0||j!==X.role)||g==="allTenants"&&((X==null?void 0:X.role)===void 0||p!==X.role)?{currentRole:(X==null?void 0:X.role)||"VIEWER",newRole:g==="allTenantUsers"?j:p}:null,allUsersToRemove:g==="allTenantUsers"&&(X==null?void 0:X.role)===void 0||g==="allTenants"&&(X==null?void 0:X.role)===void 0})}):null}):(n==null?void 0:n.type)==="organization"&&(L==="specific_tenant_users"||L==="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(Fs,{className:"mx-auto mb-2 h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant to continue"})]})})]})]})}const pt=()=>{const t=s.useShareCurrentContext(),a=s.useShareCurrentMode(),n=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),o=s.useShareSelectedTenant(),c=s.useShareOrgWideRole(),i=s.useShareAllTenantsRole(),d=s.useShareTenantWideRole(),u=I.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}),[t,a,n,r,l,o,c,i,d]),m=I.useMemo(()=>f=>s.validateShareData(f),[]),h=I.useMemo(()=>{if(!t||!a)return!1;switch(t){case"org-tab":return a==="specificOrgUsers"?n.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(a==="allTenantUsers"){if(!o)return!1}else if(a==="specificTenantUsers")return o?n.length>0||r.length>0||l.length>0:!1;return!0;case"tenant-dialog":return a==="specificTenantUsers"?n.length>0||r.length>0||l.length>0:!0}return!1},[t,a,n,r,l,o]);return{buildShareData:u,validateShareData:m,isCurrentStateValid:h,currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}};function _s({resource:t,existingShares:a,isSharing:n,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const g=s.useShareSelectedTenant();s.useShareSelectedTab();const j=s.useShareOrgWideRole(),p=s.useShareAllTenantsRole(),b=s.useShareTenantWideRole(),{buildShareData:x,validateShareData:v,isCurrentStateValid:k}=pt(),L=n||r||l,N=()=>{var B,w,F,T;if(L)return"Updating...";if(i==="specific_users"){if(m.length===0&&h.length===0&&f.length===0)return"Select users to share with";const E=m.length+h.length+f.length;return E===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${E} user${E!==1?"s":""}`:h.length>0&&m.length===0&&f.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&f.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:f.length>0&&m.length===0&&h.length===0?`Update access for ${f.length} user${f.length!==1?"s":""}`:`Update access for ${E} user${E!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const E=d.role;return j===E?"Remove Access":"Update Access"}else if(i==="all_tenants"){const E=(w=(B=a==null?void 0:a.shares)==null?void 0:B.allTenantsOnly)==null?void 0:w[0];if(!E||E.role===void 0)return"Share with All Tenants";const A=E.role;return p===A?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const E=(T=(F=a==null?void 0:a.shares)==null?void 0:F.tenantWide)==null?void 0:T[0];if(!E||E.role===void 0)return"Share with All Tenant Users";const A=E.role;return b===A?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(m.length===0&&h.length===0&&f.length===0)return"Select users to share with";const E=m.length+h.length+f.length;return E===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${E} user${E!==1?"s":""}`:h.length>0&&m.length===0&&f.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&f.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:f.length>0&&m.length===0&&h.length===0?`Update access for ${f.length} user${f.length!==1?"s":""}`:`Update access for ${E} user${E!==1?"s":""}`}return"Share"},S=()=>L||!t||i==="all_tenant_users"&&!g||i==="specific_tenant_users"&&!g?!0:!k,y=()=>{const B=x();B&&v(B)&&o(B)},D=()=>{var B,w,F,T;if(i==="all_users")if(!d||d.role===void 0){const E=x();E&&v(E)&&o(E)}else{const E=d.role;if(j===E)u==null||u();else{const R=x();if(R&&v(R)){const M={...R,updateAccess:!0};o(M)}}}else if(i==="all_tenants"){const E=(w=(B=a==null?void 0:a.shares)==null?void 0:B.allTenantsOnly)==null?void 0:w[0];if(!E||E.role===void 0){const A=x();A&&v(A)&&o(A)}else{const A=E.role;if(p===A)u==null||u();else{const M=x();if(M&&v(M)){const O={...M,updateAccess:!0};o(O)}}}}else if(i==="all_tenant_users"){const E=(T=(F=a==null?void 0:a.shares)==null?void 0:F.tenantWide)==null?void 0:T[0];if(!E||E.role===void 0){const A=x();A&&v(A)&&o(A)}else{const A=E.role;if(b===A)u==null||u();else{const M=x();if(M&&v(M)){const O={...M,updateAccess:!0};o(O)}}}}},C=()=>{var B,w,F,T;if(i==="all_users"){if(!d||d.role===void 0)return"default";const E=d.role;return j===E?"destructive":"default"}else if(i==="all_tenants"){const E=(w=(B=a==null?void 0:a.shares)==null?void 0:B.allTenantsOnly)==null?void 0:w[0];if(!E||E.role===void 0)return"default";const A=E.role;return p===A?"destructive":"default"}else if(i==="all_tenant_users"){const E=(T=(F=a==null?void 0:a.shares)==null?void 0:F.tenantWide)==null?void 0:T[0];if(!E||E.role===void 0)return"default";const A=E.role;return b===A?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:L,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||h.length>0||f.length>0)&&e.jsxs(s.Button,{onClick:y,disabled:!t||L,variant:"default",children:[L?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!L&&N()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:D,disabled:S(),variant:C(),children:[L?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"}),!L&&N()]})]})}function fn({resource:t,isSharing:a,isRemoving:n,isUpdating:r,onShare:l,onClose:o,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const h=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:f,validateShareData:g,isCurrentStateValid:j}=pt(),p=a||n||r,b=()=>{if(p)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&m.length===0)return"Select users to share with";const N=d.length+u.length+m.length;return N===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${N} user${N!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:d.length>0&&u.length===0&&m.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${N} user${N!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const N=i.role;return h===N?"Remove Access":"Update Access"}return"Share"},x=()=>p||!t?!0:!j,v=()=>{const N=f();N&&g(N)&&l(N)},k=()=>{if(!i||i.role==="NONE"){const N=f();N&&g(N)&&l(N)}else{const N=i.role;if(h===N){const y=f();if(y&&g(y)){const D={...y,removeAccess:!0};l(D)}}else{const y=f();if(y&&g(y)){const D={...y,updateAccess:!0};l(D)}}}},L=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:o,disabled:p,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:v,disabled:!t||p,variant:"default",children:[p?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!p&&b()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:k,disabled:x(),variant:L(),children:[p?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!p&&b()]})]})}function ft({resource:t,resourceType:a,isSharing:n,isRemoving:r,isUpdating:l,onClose:o,onShare:c,onRemoveAccess:i}){var y,D,C,B;const{currentUser:d}=s.useCurrentUserInfo(),[u,m]=I.useState("specific_users"),[h,f]=I.useState("specific_users"),g=s.useShareManagementActions(),j=s.useShareSelectedTab(),p=s.useShareCurrentMode(),{existingShares:b}=De({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant"}),{existingShares:x}=De({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"organization"}),v=(D=(y=b==null?void 0:b.shares)==null?void 0:y.tenantWide)==null?void 0:D[0],k=(B=(C=x==null?void 0:x.shares)==null?void 0:C.orgUsersOnly)==null?void 0:B[0],L=()=>{if(j==="org")return h;switch(p){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},N=I.useCallback(()=>{g.resetShareState(),o()},[g,o]),S=(d==null?void 0:d.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:N,children:e.jsxs(s.DialogContent,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ye,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:S?"Share this resource with org users or tenant users. As a super admin, you can share with all users.":"Share this resource with other users in your tenant."})]}),S?e.jsxs(s.Tabs,{value:j,onValueChange:w=>{const F=w;g.setSelectedTab(F),g.resetUserSelections()},className:"mb-4 min-h-0 flex-1",children:[e.jsxs(s.TabsList,{className:"mb-2 grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"org",children:"Org Users"}),e.jsx(s.TabsTrigger,{value:"tenant",children:"Tenant Users"})]}),e.jsx(s.TabsContent,{value:"org",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(pn,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:f,isSharing:n,isUpdating:l,isRemoving:r})})}),e.jsx(s.TabsContent,{value:"tenant",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(Vs,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:w=>m(w),isSharing:n,isUpdating:l,isRemoving:r})})})]}):e.jsx("div",{className:"mb-4 min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(Vs,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:w=>m(w),isSharing:n,isUpdating:l,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:S?j==="org"?e.jsx(_s,{resource:t,existingShares:x,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:h,currentAllUsersShare:k,onRemoveAccess:i}):e.jsx(_s,{resource:t,existingShares:b,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:L(),currentAllUsersShare:v,onRemoveAccess:i}):e.jsx(fn,{resource:t,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:u,currentAllUsersShare:v,onRemoveAccess:i})})]})})}function pe(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function we(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function gt(t,a,n){const{resourceType:r,resourceId:l,shareMutation:o,removeMutation:c,existingShares:i,resetUserSelections:d}=a;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const u=pe(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const f=pe(r,l,u.map(g=>({scope:"specific_org_user",orgUserId:g.id,role:g.role})));o(f,{onSuccess:()=>{d()}})}if(m&&m.length>0){const f=we(r,l,m.map(g=>{var p,b;const j=(b=(p=i==null?void 0:i.shares)==null?void 0:p.specificOrgUsers)==null?void 0:b.find(x=>x.orgUserId===g);return{scope:"specific_org_user",orgUserId:g,role:(j==null?void 0:j.role)||"VIEWER"}}));c(f,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(f=>{const g=pe(r,l,[{scope:"specific_org_user",orgUserId:f.id,role:f.newRole}]);o(g,{onSuccess:()=>{d()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const u=pe(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="allTenantUsers"){const u=pe(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h,tenantId:f}=t;if(m&&m.length>0){const g=we(r,l,m.map(j=>{var b,x;const p=(x=(b=i==null?void 0:i.shares)==null?void 0:b.specificTenantUsers)==null?void 0:x.find(v=>v.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,tenantId:f,role:(p==null?void 0:p.role)||"VIEWER"}}));c(g,{onSuccess:()=>{d()}})}if(h&&h.length>0&&h.forEach(g=>{const j=pe(r,l,[{scope:"specific_tenant_user",tenantUserId:g.id,tenantId:f,role:g.newRole}]);o(j,{onSuccess:()=>{d()}})}),u&&u.length>0){const g=pe(r,l,u.map(j=>({scope:"specific_tenant_user",tenantUserId:j.id,tenantId:f,role:j.role})));o(g,{onSuccess:()=>{d()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const u=we(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);c(u,{onSuccess:()=>{d()}})}else if(t.updateAccess){const u=pe(r,l,[{scope:"all_tenant_users",tenantId:n==null?void 0:n.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else{const u=pe(r,l,[{scope:"all_tenant_users",tenantId:n==null?void 0:n.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const f=pe(r,l,u.map(g=>({scope:"specific_tenant_user",tenantUserId:g.id,role:g.role})));o(f,{onSuccess:()=>{d()}})}if(m&&m.length>0){const f=we(r,l,m.map(g=>{var p,b;const j=(b=(p=i==null?void 0:i.shares)==null?void 0:p.specificTenantUsers)==null?void 0:b.find(x=>x.tenantUserId===g);return{scope:"specific_tenant_user",tenantUserId:g,role:(j==null?void 0:j.role)||"VIEWER"}}));c(f,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(f=>{const g=pe(r,l,[{scope:"specific_tenant_user",tenantUserId:f.id,role:f.newRole}]);o(g,{onSuccess:()=>{d()}})})}break}}function jt(t,a,n,r){var u,m,h,f,g,j;const{resourceType:l,resourceId:o,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(o)if(t.length>0){const p=we(l,o,t.map(b=>{var v,k;const x=(k=(v=i==null?void 0:i.shares)==null?void 0:v.specificTenantUsers)==null?void 0:k.find(L=>L.tenantUserId===b);return{scope:"specific_tenant_user",tenantUserId:b,role:(x==null?void 0:x.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()},onError:b=>{console.error("Remove access failed:",b)}})}else{const p=a==="tenant"&&n==="allTenants",b=a==="tenant"&&n==="allTenantUsers";if(p){const x=(m=(u=i==null?void 0:i.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(x){const v=we(l,o,[{scope:"all_tenants_only",role:x.role}]);c(v,{onSuccess:()=>{d()},onError:k=>{console.error("Remove all-tenants access failed:",k)}})}}else if(b){const x=(f=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:f[0];if(x){const v=we(l,o,[{scope:"all_tenant_users",role:x.role}]);c(v,{onSuccess:()=>{d()},onError:k=>{console.error("Remove all-tenant-users access failed:",k)}})}}else{const x=(j=(g=i==null?void 0:i.shares)==null?void 0:g.orgUsersOnly)==null?void 0:j[0];if(x){const v=we(l,o,[{scope:"org_users_only",role:x.role}]);c(v,{onSuccess:()=>{d()},onError:k=>{console.error("Remove org-wide access failed:",k)}})}}}}function gn(t,a,n){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=s.useCurrentUserInfo(),{existingShares:d}=De({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),u=I.useCallback(()=>{r.resetUserSelections()},[r]),m=I.useCallback(f=>{if(!t)return;const g={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:a,removeMutation:n,existingShares:d,resetUserSelections:u};gt(f,g,i)},[t,a,n,d,u,i]),h=I.useCallback(()=>{if(!t)return;const f={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:n,existingShares:d,resetUserSelections:u};jt(l,o||"",c||"",f)},[t,a,n,d,u,l,o,c]);return{handleShareSubmit:m,handleRemoveAccess:h}}function jn(t,a,n){const{currentUser:r}=s.useCurrentUserInfo(),l=s.useShareManagementActions(),o=s.useShareUsersToRemove(),c=s.useShareSelectedTab(),i=s.useShareCurrentMode(),{existingShares:d}=De({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.VISUAL,userType:"tenant"}),u=I.useCallback(()=>{l.resetUserSelections()},[l]),m=I.useCallback(f=>{if(!t)return;const g={resourceType:s.ResourceType.VISUAL,resourceId:t,shareMutation:a,removeMutation:n,existingShares:d,resetUserSelections:u};gt(f,g,r)},[t,a,n,d,u,r]),h=I.useCallback(()=>{if(!t)return;const f={resourceType:s.ResourceType.VISUAL,resourceId:t,removeMutation:n,existingShares:d,resetUserSelections:u};jt(o,c||"",i||"",f)},[t,a,n,d,u,o,c,i]);return{handleShareSubmit:m,handleRemoveAccess:h}}function bn(t){const a=t.toUpperCase().indexOf("WHERE"),n=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let o=t.length;if(l!==-1&&(o=l),r!==-1&&r<o&&(o=r),a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,o),i=t.substring(o);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function Ns(t){const[a,n]=I.useState(null),[r,l]=I.useState(null);return I.useEffect(()=>{if(!t||t.trim()===""){n(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");n(()=>d.useChartStore),l(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),l(i),n(null)}})()},[t]),a}function yn(t,a){if(t.length===0)return"";if(a){const n=t.find(r=>r.id===a);if(n){const r=n.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const o=r.split("__")[0],c=t.find(i=>i.tabTitle===o);return c?c.id:t[0].id}return a}}return t[0].id}async function Us(t,a,n){if(!t||!a)throw new Error("Missing auth token or visual ID");const r=["resource-by-id","visual",a],l=n.getQueryData(r);if(l)return console.log("Using cached visual data for:",a),{data:l,fromCache:!0};console.log("Fetching visual data from network for:",a);const o=s.ue.loading("Loading visual...",{position:"top-center"});try{const c=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${t}`}});if(!c.ok)throw new Error("Failed to load visual");const i=await c.json();return n.setQueryData(r,i),s.ue.dismiss(o),{data:i,fromCache:!1}}catch(c){throw s.ue.dismiss(o),c}}function vn(t,a,n,r,l){const o=t.frameObject;a(o);const c=o.cards.find(i=>i.id===o.activeCardId);c&&n(c),r(!0),l(!0)}function Nn(){var f;const{setCardSql:t}=s.useEditorActions(),a=s.useEditorStore(g=>g.frame),n=s.useEditorStore(g=>g.card),r=Ns(((f=n.customCardPreferences)==null?void 0:f.url)||""),l=s.useEditorStore(g=>g.selectedSchemaName),o=s.useEditorStore(g=>g.selectedDatamodelId),c=s.useEditorStore(g=>g.selectedDatabaseName),i=s.useEditorStore(g=>g.selectedTableName),d=s.useEditorStore(g=>g.selectedConnectionId),u=s.useEditorStore(g=>g.isShowingVisual),m=n.sql;return{getUpdatedFrame:I.useCallback(()=>{var x;let g=m;m&&!m.includes("{{")&&(g=bn(m),t(g));const j=(x=r==null?void 0:r.getState())==null?void 0:x.settings,p={...n,dataSource:n.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:o,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:g,customCfg:u?n.customCfg:null,preferences:n.preferences,...j&&{customCardPreferences:{...n.customCardPreferences,settings:j}}},b=a.cards.map(v=>v.id===n.id?p:v);return{...a,cards:b,activeCardId:yn(b,a.activeCardId)}},[n,a,u,l,o,c,i,d,t,r,m])}}function Cs(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient(),n=s.useSelectedVisual(),{selectVisual:r}=s.useManagementActions(),{setFrame:l,setCard:o}=s.useEditorActions(),{setIsDashboardEditing:c,setIsVisualEditing:i,setSelectedFrameId:d,addFrame:u,setIsDashboardPanelOpen:m}=s.useDashboardActions(),h=s.useDashboardStore(p=>p.selectedSheetId),f=s.useVisualById((n==null?void 0:n.id)||"",{enabled:!!(n!=null&&n.id)&&!!(t!=null&&t.accessToken)}),g=I.useCallback(async p=>{try{r(p);const{data:b,fromCache:x}=await Us((t==null?void 0:t.accessToken)||"",p.id,a);return vn(b,l,o,c,i),{success:!0,fromCache:x}}catch(b){return console.error("Error editing visual:",b),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,a,r,l,o,c,i]),j=I.useCallback(async p=>{try{if(r(p),!h)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:b,fromCache:x}=await Us((t==null?void 0:t.accessToken)||"",p.id,a),v=b.frameObject;if(!v)return{success:!1,error:"Visual has no frame data"};const k={...v,id:s.v4()};return u(h,k,"end"),c(!0),d(k.id),m(!1),{success:!0,fromCache:x}}catch(b){return console.error("Error adding visual:",b),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,a,r,h,u,c,d,m]);return{visual:f.data,isLoading:f.isLoading,isError:f.isError,error:f.error,handleEditLibraryVisual:g,handleAddLibraryVisual:j,getUpdatedFrame:Nn().getUpdatedFrame,refetch:f.refetch}}function Cn(){const[t,a]=I.useState(""),[n,r]=I.useState(!1),[l,o]=I.useState(""),[c,i]=I.useState(""),[d,u]=I.useState(!1),[m,h]=I.useState(null),[f,g]=I.useState(!1),[j,p]=I.useState(null),[b,x]=I.useState(null),{setIsDashboardEditing:v,setIsVisualEditing:k}=s.useDashboardActions(),{handleEditLibraryVisual:L,handleAddLibraryVisual:N}=Cs(),{resources:S,isLoading:y,isError:D,createResource:C,updateResource:B,deleteResource:w,duplicateResource:F,shareResource:T,isCreating:E,isDeleting:A,removeResourceShares:R,isSharing:M,isRemovingShares:O,isUpdatingShares:P}=s.useVisualManagement(()=>{g(!1),p(null)},()=>{r(!1),o(""),i("")}),{handleShareSubmit:K,handleRemoveAccess:Y}=jn((m==null?void 0:m.id)||null,T,R);s.useCurrentUserInfo();const te=S.filter(W=>{var re,ie;return((re=W==null?void 0:W.title)==null?void 0:re.toLowerCase().includes(t.toLowerCase()))||((ie=W==null?void 0:W.description)==null?void 0:ie.toLowerCase().includes(t.toLowerCase()))}),X=W=>new Date(W).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{l.trim()&&C({title:l,description:c,isPrivate:!1})},H=W=>{p(W),g(!0)},_=()=>{j&&w(j.id)},{startUpdating:J,stopUpdating:z,isUpdating:U}=s.useResourceUpdateState(),Z=(W,re)=>{const ie=re.title!==void 0?"title":"description";J(W,ie),B({resourceId:W,data:re},{onSuccess:()=>{z(W,ie)},onError:()=>{z(W,ie)}})},le=W=>{x(W),F(W,{onSettled:()=>x(null)})},V=W=>{L(W)},se=W=>{N(W)},ne=W=>{const re=S.find(ie=>ie.id===W);re&&B({resourceId:W,data:{isPrivate:!re.isPrivate}})},q=W=>{h(W),u(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),De({debouncedSearchQuery:"",resourceId:(m==null?void 0:m.id)||"",resourceType:s.ResourceType.VISUAL,userType:"tenant"}),y?e.jsx(rt,{}):D?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:n?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:W=>o(W.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:W=>i(W.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:$,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||E,children:E?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),o(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:E,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",disabled:E,children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),E?"Creating...":"Create New Visual"]})}),S&&S.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:W=>a(W.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:te.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"mb-3",children:e.jsx(ns,{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"]})]}):te.map(W=>e.jsx(sn,{visual:W,onAddVisual:se,onEditVisual:V,onUpdateVisual:Z,onDeleteClick:H,onDuplicateVisual:le,onTogglePrivacy:ne,onShareVisual:q,isDeleting:A,isDuplicating:b===W.id,isTitleUpdating:U(W.id,"title"),isDescriptionUpdating:U(W.id,"description"),formatDate:X},W.id))})}),d&&m&&e.jsx(ft,{resource:m,resourceType:s.ResourceType.VISUAL,onShare:K,isSharing:M,isRemoving:O,isUpdating:P,onClose:()=>{u(!1),h(null)},onRemoveAccess:Y}),e.jsx(s.AlertDialog,{open:f,onOpenChange:W=>{!W&&A||(g(W),W||p(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:A,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:W=>{W.preventDefault(),W.stopPropagation(),_()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:A,children:A?"Deleting...":"Delete"})]})]})})]})}function Sn({dashboard:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onLoadDashboard:o,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:u,formatDate:m,onDashboardItemClick:h}){var S,y,D;const{selectDashboard:f}=s.useManagementActions(),g=s.useIsDashboardSelected(t.id),{isConsoleMode:j}=s.useDashboardPreferences(),[p,b]=I.useState(!1),[x,v]=I.useState(!1),k=s.useDashboardStore(C=>C.actions.setIsDashboardPanelOpen);I.useEffect(()=>{n?(b(!0),v(!0)):x&&(b(!1),v(!1))},[n,x]);const L=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4"}),N=()=>{f(t),o(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:N,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:L()}),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:C=>c==null?void 0:c(t.id,{title:C}),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:C=>c==null?void 0:c(t.id,{description:C}),isEditable:t.permissions.canEdit&&g,isPending:l,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:C=>C.stopPropagation(),children:e.jsxs(s.DropdownMenu,{modal:!1,open:p,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:C=>{C.preventDefault(),C.stopPropagation(),d(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.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:C=>{C.stopPropagation(),i(t),k(!1)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((S=t.ownership.createdBy)==null?void 0:S.type)==="tenant"||((y=t.ownership.createdBy)==null?void 0:y.type)==="organization"&&j)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Be,{className:"h-3 w-3"}),e.jsx("span",{children:((D=t.ownership.createdBy)==null?void 0:D.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 wn({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 Dn(t){const[a,n]=I.useState(""),[r,l]=I.useState(!1),[o,c]=I.useState(""),[i,d]=I.useState(""),[u,m]=I.useState(!1),[h,f]=I.useState(null),[g,j]=I.useState(!1),[p,b]=I.useState(null),[x,v]=I.useState(null),k=s.useManagementStore(Q=>Q.lastSelectedDashboard),L=s.useManagementStore(Q=>Q.selectedDashboard),N=s.useManagementStore(Q=>Q.actions.selectDashboard),S=s.useManagementStore(Q=>Q.actions.clearSelectedDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{tokenProps:y,id:D}=s.useSemaphorContext(),{permissions:C}=s.useRoleAwareDisplayPreferences(),{resources:B,isLoading:w,isError:F,createResource:T,updateResource:E,deleteResource:A,duplicateResource:R,isCreating:M,isDeleting:O,isSharing:P,isRemovingShares:K,isUpdatingShares:Y,shareResource:te,removeResourceShares:X}=s.useDashboardManagement(()=>{j(!1);const Q=p==null?void 0:p.id;b(null),(L==null?void 0:L.id)===Q&&(!(y!=null&&y.dashboard_id)&&!D?S():k&&k.id!==Q&&N(k))},()=>{l(!1),c(""),d("")}),{handleShareSubmit:$,handleRemoveAccess:H}=gn((h==null?void 0:h.id)||null,te,X),{currentUser:_}=s.useCurrentUserInfo(),J=B.filter(Q=>{var oe,ee;return((oe=Q==null?void 0:Q.title)==null?void 0:oe.toLowerCase().includes(a.toLowerCase()))||((ee=Q==null?void 0:Q.description)==null?void 0:ee.toLowerCase().includes(a.toLowerCase()))}),z=Q=>new Date(Q).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),U=()=>{o.trim()&&T({title:o,description:i,isPrivate:!1})},Z=Q=>{var oe;(oe=t.onLoadDashboard)==null||oe.call(t,Q)},le=Q=>{b(Q),j(!0)},V=()=>{p&&A(p.id)},se=Q=>{v(Q),R(Q,{onSettled:()=>v(null)})},{startUpdating:ne,stopUpdating:q,isUpdating:W}=s.useResourceUpdateState(),re=(Q,oe)=>{const ee=oe.title!==void 0?"title":"description";ne(Q,ee),E({resourceId:Q,data:oe},{onSuccess:()=>{q(Q,ee)},onError:()=>{q(Q,ee)}})},ie=Q=>{const oe=B.find(ee=>ee.id===Q);oe&&E({resourceId:Q,data:{isPrivate:!oe.isPrivate}})},he=Q=>{f(Q),_==null||_.type,m(!0)};return De({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),w?e.jsx(rt,{}):F?e.jsx(wn,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[C.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:o,onChange:Q=>c(Q.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:Q=>d(Q.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:U,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||M,children:M?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{l(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:M,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>l(!0),className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",disabled:M,children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),M?"Creating...":"Create New Dashboard"]})}),B&&B.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:a,onChange:Q=>n(Q.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:J.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:a?"No dashboards found":"No dashboards yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:a?"Try adjusting your search":C.canCreateDashboards?"Create your first dashboard to get started":"No dashboards have been shared with you yet"}),C.canCreateDashboards&&!a&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>l(!0),children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),"Create Dashboard"]})]}):J.map(Q=>e.jsx(Sn,{dashboard:Q,isDeleting:O,isDuplicating:x===Q.id,isTitleUpdating:W(Q.id,"title"),isDescriptionUpdating:W(Q.id,"description"),onLoadDashboard:Z,onEditDashboard:t.onEditDashboard,onUpdateDashboard:re,onDeleteClick:le,onDuplicateDashboard:se,onTogglePrivacy:ie,onShareDashboard:he,formatDate:z,onDashboardItemClick:t.onDashboardItemClick},Q.id))})}),u&&h&&e.jsx(ft,{resource:h,resourceType:s.ResourceType.DASHBOARD,onShare:$,isSharing:P,isRemoving:K,isUpdating:Y,onClose:()=>{m(!1),f(null)},onRemoveAccess:H}),e.jsx(s.AlertDialog,{open:g,onOpenChange:Q=>{!Q&&O||(j(Q),Q||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 "',p==null?void 0:p.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:O,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),V()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:O,children:O?"Deleting...":"Delete"})]})]})})]})}function bt({isOpen:t,onClose:a,className:n,onDashboardItemClick:r}){s.useDashboardStore(b=>b.dashboard);const{setDashboard:l,addSheet:o}=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),f=d.canAccessVisuals?m:"dashboards",g=dt(a,{enabled:t}),j=b=>{},p=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",n),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:a,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:f,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(Dn,{onLoadDashboard:j,onEditDashboard:p,onDashboardItemClick:r})}),d.canAccessVisuals&&e.jsx(s.TabsContent,{value:"visuals",className:"flex-1 mt-4",children:e.jsx(Cn,{})})]})})]})})}function kn(){var se,ne;const{authToken:t,tokenProps:a,id:n}=s.useSemaphorContext(),{isLocalDev:r}=s.useDashboardPreferences(),{permissions:l}=s.useRoleAwareDisplayPreferences(),o=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),f=s.useEditorStore(q=>q.selectedConnectionId),[g,j]=I.useState(!1),p=s.useDashboardStore(q=>q.isDashboardPanelOpen),b=s.useDashboardStore(q=>q.actions.setIsDashboardPanelOpen),x=s.useDashboardStore(q=>q.filterValues),v=s.useDashboardStore(q=>q.isVisualEditing),k=s.useManagementStore(q=>q.selectedDashboard),L=s.useManagementStore(q=>q.initialDashboard),N=k?(ne=k==null?void 0:k.permissions)==null?void 0:ne.canEdit:(se=L==null?void 0:L.permissions)==null?void 0:se.canEdit,S=s.useDashboardStore(q=>q.showFilters),y=s.useDashboardStore(q=>q.showDashboardJSON),D=s.useDashboardStore(q=>q.onSaveFunction),C=s.useDashboardStore(q=>q.actions.setShowFilters),{addFrame:B,setSelectedFrameId:w}=s.useDashboardStore(q=>q.actions),{getSelectedSheet:F,setIsDashboardEditing:T,setShowDashboardJSON:E}=s.useDashboardStore(q=>q.actions),A=F(),{setInitialDashboard:R,clearSelectedDashboard:M}=s.useManagementStore(q=>q.actions),{resources:O}=s.useResourceManagement(s.ResourceType.DASHBOARD);I.useEffect(()=>{if(O&&O.length>0){const q=u==null?void 0:u.id;if(q){const W=O.find(re=>re.id===q);W&&R(W)}}},[O,u==null?void 0:u.id,R]);const P=a.orgUserId||a.tenantId,K=m&&!v&&P&&N;function Y(){var ie,he;const q=h.dataSource;if(q)return q;const W=(he=(ie=u.aiContext)==null?void 0:ie.selectedEntities)==null?void 0:he[0],re=W==null?void 0:W.type;if(W)return{connectionId:W.connectionId,connectionType:W.connectionType,type:re,selectedEntities:[W]}}const te=()=>{if(!m||!A)return;const W={dataSource:Y(),mode:"explorer",connectionId:f,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},re={id:s.v4(),cards:[W],activeCardId:W.id};B(A.id,re),w(re.id)},X=()=>{T(!0)},[$,H]=I.useState(!1),_=s.useUpdateResource(s.ResourceType.DASHBOARD);async function J(){const q=es(u);H(!0);const W={template:q};_.mutate({resourceId:q.id,data:W},{onSuccess:()=>{H(!1),s.ue.success("Dashboard saved!")},onError:()=>{H(!1),s.ue.error("Failed to save dashboard")}})}async function z(){if(j(!0),!i||!d)return;const q=es(u),W=JSON.stringify(q),re={...d,template:W,filterValues:x};await js(re,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),D==null||D(q),j(!1)}if(v)return null;const U=(d==null?void 0:d.name)||u.title,le=O&&O.length>0&&(a.orgUserId||a.tenantId&&a.endUserId&&a.endUserEmail),V=k&&!(a!=null&&a.dashboard_id)&&!n;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:[le&&e.jsxs(e.Fragment,{children:[V&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Back to Dashboard Hub",onClick:()=>M(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})}),e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:o?"Manage Dashboards":"Select a dashboard to continue",onClick:()=>b(!0),className:"h-7 p-2",buttonProps:{disabled:!o},children:e.jsx(Ea,{className:"h-4 w-4"})})]}),!v&&o&&e.jsx(s.Label,{children:U})]}),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(Va,{className:"h-4 w-4"})}),!v&&o&&e.jsx(en,{}),!v&&o&&e.jsx(nt,{}),m&&!v&&P&&r&&o&&e.jsx(Xa,{}),!v&&P&&r&&o&&e.jsx(Za,{}),m&&!v&&P&&d&&r&&o&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:g,onClick:z,size:"sm",children:[e.jsx(gs,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),m&&!v&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!m,onClick:te,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!v&&!m&&l.canEdit&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:X,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),m&&!v&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{T(!1),E(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),K&&o&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"outline",disabled:$,onClick:J,size:"sm",children:[$?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(gs,{className:"mr-2 h-4 w-4"}),$?"Saving...":"Save"]}),!S&&!v&&m&&l.canUseFilters&&o&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>C(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!v&&m&&r&&o&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>E(!y),size:"sm",variant:"ghost",children:e.jsx(Oe,{className:"h-4 w-4"})})}),!v&&r&&e.jsx(Wa,{}),!v&&e.jsx(bt,{isOpen:p,onClose:()=>b(!1)})]})]})}function Tn({name:t,items:a,value:n,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:d,showNone:u=!1}){const m=ke.useRef(null),[h,f]=ke.useState(!1),[g,j]=ke.useState("100%"),p=u?[...a||[],{id:"none",name:"None"}]:a;ke.useLayoutEffect(()=>{m.current&&j(m.current.offsetWidth)},[]);function b(){var v;return l?"Loading...":o?"Error":n?(v=a==null?void 0:a.find(k=>k.id===n))==null?void 0:v.name:`Select ${t}`}function x(v,k){r(k),f(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:f,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:m,variant:"outline",role:"combobox","aria-expanded":h,className:s.cn("flex h-9 w-full justify-between",i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx("div",{className:"mr-2",children:d}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children: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(et,{className:s.cn("size-3.5 opacity-50",l&&"animate-spin")})})]}),e.jsxs(s.CommandList,{children:[e.jsxs(s.CommandEmpty,{children:["No ",t==null?void 0:t.toLowerCase()," found."]}),e.jsx(s.CommandGroup,{children:p==null?void 0:p.map(v=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:v.name,onSelect:k=>x(k,v.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",n===v.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:v.name,children:v.name})]})},v.id))})]})]})})]})}function Re({title:t,items:a,value:n,isLoading:r,isError:l,refetch:o,onChange:c,showNone:i=!1,className:d,disabled:u=!1,type:m="combobox"}){const h=r?"Loading...":l?"Error":n;function f(){if(t==="Connection")return e.jsx(Fa,{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...":l?"Error":`Select ${t}`})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[r?e.jsx(s.SelectLabel,{children:"Loading..."}):e.jsxs(s.SelectLabel,{className:"flex items-center justify-between gap-2",children:[t,e.jsx(et,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:o})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),a&&a.map((p,b)=>e.jsx(s.SelectItem,{value:p.id,children:p.name},b))]}),(r||l)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function j(){return e.jsx(Tn,{icon:f(),items:a,value:h,onChange:c||(()=>{}),isLoading:r,isError:l,refetch:o,name:t,showNone:i})}return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:m==="select"?g():j()})})}function En({column:t}){const[a,n]=I.useState(!1),r=s.useEditorStore(p=>p.selectedTableName),l=s.useEditorStore(p=>p.selectedSchemaName),o=s.useEditorStore(p=>p.selectedDatabaseName),c=s.useEditorStore(p=>p.selectedDatamodelId),i=s.useEditorStore(p=>p.sqlGen),{modelItems:d,connectionType:u}=s.useEditorAside(),m=s.useEditorStore(p=>p.actions.setSqlGen),h=s.useEditorStore(p=>p.actions.setCardSql),f=s.useEditorStore(p=>p.actions.setRunSql);function g(p,b){var L;const x=s.createSqlGenConfig(p,i,b),v=(L=d==null?void 0:d.find(N=>N.id===c))==null?void 0:L.name;m(x);const k=s.getSql(x,s.fmt(l||""),s.fmt(r),v||"",u,o||"");k&&(h(k),f(!0)),n(!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:a,onOpenChange:n,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:j()})]})}function In({dataType:t}){const a=s.getDataType(t);return a==="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(fe,{className:"h-3 w-3"})}):a==="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(Ne,{className:"h-3 w-3"})}):a==="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"})}):a==="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(Me,{className:"h-3 w-3"})}):a==="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(Oe,{className:"h-3 w-3"})}):a==="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"})}):a==="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($e,{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(fe,{className:"h-3 w-3"})})}function is({column:t,className:a}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center gap-2 px-3 py-[6px] text-sm",a),children:[e.jsx(In,{dataType:t.data_type}),e.jsx("span",{children:t.column_name})]})}function An({id:t,children:a,type:n="column"}){const{attributes:r,listeners:l,setNodeRef:o,transform:c}=s.useDraggable({id:t,data:{type:n}}),i=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:o,style:i,...l,...r,children:a})}function Mn({onClick:t,column:a}){const n=s.useDndStore(m=>m.activeId),r=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.groupByColumns}),l=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.metricColumns}),o=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.filterColumns});function c(m){return i(m)||d(m)||u(m)}function i(m){return r==null?void 0:r.some(h=>h.name===m.column_name)}function d(m){return l==null?void 0:l.some(h=>h.name===m.column_name)}function u(m){return o==null?void 0:o.some(h=>h.name===m.column_name)}return e.jsxs("div",{onClick:()=>t(a),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(a)}),children:[n===a.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(is,{column:a,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),n===a.column_name&&e.jsx("div",{className:"absolute inset-0",children:n===a.column_name&&e.jsx(is,{column:a})}),e.jsx(An,{id:a.column_name,type:"column",children:e.jsx(is,{column:a})})]})}const cs={id:"__placeholder__",role:"groupby",type:"string"},ds={id:"__placeholder__",role:"groupby",type:"string"},us={id:"__placeholder__",role:"metric",type:"number"},ms={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},yt={id:"__placeholder__"},Ee="droppable-group-by",Ie="droppable-metrics",Ae="droppable-pivot-by",ts="sortable-group-by",bs="sortable-metrics",as="sortable-pivot-by",ys="droppable-filters",vs="sortable-filters",Ss="sortable-order-by";function Ln(){const t=s.useDndStore(E=>E.insertIndex),a=s.useEditorStore(E=>{var A;return((A=E.card.queryConfig)==null?void 0:A.groupByColumns)||[]}),n=s.useEditorStore(E=>{var A;return((A=E.card.queryConfig)==null?void 0:A.metricColumns)||[]}),r=s.useEditorStore(E=>{var A;return((A=E.card.queryConfig)==null?void 0:A.filterColumns)||[]}),l=s.useEditorStore(E=>{var A;return((A=E.card.queryConfig)==null?void 0:A.orderBy)||[]}),o=s.useEditorStore(E=>{var A;return((A=E.card.queryConfig)==null?void 0:A.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:u,setPreviewFilterColumns:m,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:f,setMetricColumns:g,setFilterColumns:j,setOrderByColumns:p,setPivotByColumns:b}=s.useEditorActions(),{columns:x}=s.useDataColumns(),{formattedTableName:v}=s.useEditorAside(),k=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),L=E=>{var M;const{active:A,over:R}=E;if(((M=A.data.current)==null?void 0:M.type)==="column"&&R){const O=R.id,P=x.find(X=>X.column_name===A.id);if(!P)return;const K=s.isNumberDataType(P.data_type),Y=s.isTextDataType(P.data_type),te=s.isDateDataType(P.data_type);if(Y||te){if(a.some($=>$.id===O)){const $=a.findIndex(_=>_.id===O);c($);const H=a.filter(_=>_.id!==cs.id);H.splice($,0,cs),d(H)}else if(R.id===Ee){c(a.length);const $=[...a,cs];d($),u(n),m(r)}}if(Y||te){if(o.some($=>$.id===O)){const $=o.findIndex(_=>_.id===O);c($);const H=o.filter(_=>_.id!==ds.id);H.splice($,0,ds),h(H)}else if(R.id===Ae){c(o.length);const $=[...o,ds];h($),d(a),u(n),m(r)}}if(K||Y){if(n.some($=>$.id===O)){console.log("isOverMetricSortable",O);const $=n.findIndex(_=>_.id===O);c($);const H=n.filter(_=>_.id!==us.id);H.splice($,0,us),u(H)}else if(R.id===Ie){c(n.length);const $=[...n,us];u($),m(r),d(a),h(o)}}if(S(P)){if(r.some($=>$.id===O)){const $=r.findIndex(_=>_.id===O);c($);const H=r.filter(_=>_.id!==ms.id);H.splice($,0,ms),m(H)}else if(R.id===ys){c(r.length);const $=[...r,ms];m($),u(n),d(a),h(o)}}}else d(a),u(n),m(r),h(o)};function N(E){i(E.active.id),c(null),d(a),u(n),m(r),h(o)}function S(E){return!r.some(A=>A.name===E.column_name)}function y(E,A="SUM"){const{column_name:R,data_type:M}=E,O=[...n],P=t!==null?t:n.length,K={...E,id:be(R),name:R,label:qe(R,A),type:M,role:"metric",aggregate:A};O.splice(P,0,K),g(O)}function D(E){const A=s.isTextDataType(E.data_type);s.isDateDataType(E.data_type);const R=[...o],M=t!==null?t:o.length;let O;A?O={...E,id:be(E.column_name),name:E.column_name,type:E.data_type,role:"groupby"}:O={...E,id:be(E.column_name),name:E.column_name,type:E.data_type,role:"groupby",label:Fe(E.column_name,"month"),granularity:"month"},R.splice(M,0,O),b(R)}function C(E){const A=s.isTextDataType(E.data_type);s.isDateDataType(E.data_type);const R=[...a],M=t!==null?t:a.length;let O;A?O={...E,id:be(E.column_name),name:E.column_name,type:E.data_type,role:"groupby"}:O={...E,id:be(E.column_name),name:E.column_name,type:E.data_type,role:"groupby",label:Fe(E.column_name,"month"),granularity:"month"},R.splice(M,0,O),f(R)}function B(E){const A=[...r],R=t!==null?t:r.length,M={...E,id:be(E.column_name),name:E.column_name,type:E.data_type,sql:s.getDefaultFilterSql(E.data_type,v,s.fmt(E.column_name)),role:"filter"};A.splice(R,0,M),j(A)}function w(E){var O,P,K,Y,te,X,$,H;const{active:A,over:R}=E,M=A.data.current;if((M==null?void 0:M.type)==="column"&&R){const _=x.find(Z=>Z.column_name===A.id);if(!_)return;const J=s.isNumberDataType(_.data_type),z=s.isTextDataType(_.data_type),U=s.isDateDataType(_.data_type);(z||U)&&(R.id===Ee||((O=R.data.current)==null?void 0:O.type)===ts)&&C(_),(z||U)&&(R.id===Ae||((P=R.data.current)==null?void 0:P.type)===as)?D(_):(J||z)&&(R.id===Ie||((K=R.data.current)==null?void 0:K.type)===bs)?(J&&y(_),z&&y(_,"COUNT")):S(_)&&(R.id===ys||((Y=R.data.current)==null?void 0:Y.type)===vs)&&B(_)}if(R&&((te=R.data.current)==null?void 0:te.type)===ts&&a.some(_=>_.id===A.id)){const _=a.findIndex(z=>z.id===A.id),J=a.findIndex(z=>z.id===R.id);if(_!==-1&&J!==-1&&_!==J){const z=[...a],[U]=z.splice(_,1);z.splice(J,0,U),f(z)}}if(R&&((X=R.data.current)==null?void 0:X.type)===as&&o.some(_=>_.id===A.id)){const _=o.findIndex(z=>z.id===A.id),J=o.findIndex(z=>z.id===R.id);if(_!==-1&&J!==-1&&_!==J){const z=[...o],[U]=z.splice(_,1);z.splice(J,0,U),b(z)}}if(R&&(($=R.data.current)==null?void 0:$.type)===bs&&n.some(_=>_.id===A.id)){const _=n.findIndex(z=>z.id===A.id),J=n.findIndex(z=>z.id===R.id);if(_!==-1&&J!==-1&&_!==J){const z=[...n],[U]=z.splice(_,1);z.splice(J,0,U),g(z)}}if(R&&((H=R.data.current)==null?void 0:H.type)===vs&&r.some(_=>_.id===A.id)){const _=r.findIndex(z=>z.id===A.id),J=r.findIndex(z=>z.id===R.id);if(_!==-1&&J!==-1&&_!==J){const z=[...r],[U]=z.splice(_,1);z.splice(J,0,U),j(z)}}F(E),i(null),c(null),d(a),u(n),m(r),h(o)}function F(E){const{active:A,over:R}=E,M=A.data.current;if((M==null?void 0:M.type)===Ss&&R){const O=l.findIndex(K=>Ve(K.columnId)===A.id),P=l.findIndex(K=>Ve(K.columnId)===R.id);if(O!==-1&&P!==-1&&O!==P){const K=[...l],[Y]=K.splice(O,1);K.splice(P,0,Y),p(K)}}}function T(){i(null),c(null),d(a),u(n),m(r)}return{handleDragOver:L,handleDragEnd:w,handleDragStart:N,handleDragCancel:T,sensors:k}}function be(t){return`${t}-${s.v4()}`}function qe(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Ve(t){return`${Ss}-${t}`}function Fe(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function Rn({dataType:t}){const a=s.getDataType(t);return a==="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(fe,{className:"h-3 w-3"})}):a==="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(Ne,{className:"h-3 w-3"})}):a==="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"})}):a==="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(Me,{className:"h-3 w-3"})}):a==="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(Oe,{className:"h-3 w-3"})}):a==="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"})}):a==="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($e,{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(fe,{className:"h-3 w-3"})})}function On({schemaName:t,tableName:a,columns:n,status:r}){const[l,o]=I.useState(""),[c,i]=I.useState("all"),d=s.useEditorStore(O=>O.sqlGen),u=s.useEditorStore(O=>O.isDevMode);s.useEditorStore(O=>O.selectedConnectionId);const m=s.useEditorStore(O=>{var P,K;return(K=(P=O.card)==null?void 0:P.queryConfig)==null?void 0:K.metricColumns});s.useEditorStore(O=>{var P,K;return(K=(P=O.card)==null?void 0:P.queryConfig)==null?void 0:K.groupByColumns});const h=s.useEditorStore(O=>O.selectedDatabaseName);s.useEditorStore(O=>O.selectedSchemaName),s.useEditorStore(O=>O.selectedTableName);const f=s.useEditorStore(O=>O.selectedDatamodelId);s.useDashboardStore(O=>O.dashboard.aiScopeTables);const{addToAIScope:g,removeFromAIScope:j}=s.useDashboardActions(),{addColumnToMetricColumns:p,addColumnToGroupBy:b,setCardSql:x,setRunSql:v,setSqlGen:k,setIsShowingVisual:L}=s.useEditorActions(),{connectionType:N,modelItems:S,selectedDatamodelName:y}=s.useEditorAside();function D(O){var P;if(u){const K=s.createSqlGenConfig(O,d);k(K);const Y=(P=S==null?void 0:S.find(X=>X.id===f))==null?void 0:P.name,te=s.getSql(K,s.fmt(t),s.fmt(a),Y||"",N,h||"");te&&(x(te),v(!0))}if(!u){if(s.isTextDataType(O.data_type))if(m&&m.length>0){const K={...O,role:"groupby",id:be(O.column_name),name:O.column_name,type:O.data_type};b(K)}else{const K={...O,role:"metric",id:be(O.column_name),name:O.column_name,label:qe(O.column_name,"COUNT"),type:O.data_type,aggregate:"COUNT"};p(K)}if(s.isDateDataType(O.data_type)){const K={...O,role:"groupby",id:be(O.column_name),name:O.column_name,type:O.data_type,label:Fe(O.column_name,"month"),granularity:"month"};b(K)}if(s.isNumberDataType(O.data_type)){const K={...O,role:"metric",id:be(O.column_name),name:O.column_name,label:qe(O.column_name,"SUM"),type:O.data_type,aggregate:"SUM"};p(K)}}}function C(){const O=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:y,connectionType:N,databaseName:h||""});L(!1);const P=N==="MSSQL"?`SELECT top 10 * FROM ${O}`:`SELECT * FROM ${O} LIMIT 10`;x(P),v(!0)}function B(){const O=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:y,connectionType:N,databaseName:h||""});x(`SELECT COUNT(*) as count FROM ${O}`),v(!0)}const w=(n==null?void 0:n.filter(O=>O.column_name.toLowerCase().includes(l.toLowerCase())))||[],F=O=>s.isNumberDataType(O.data_type)?"number":"text",T=c==="all"?w:w.filter(O=>F(O)===c),E=w.filter(O=>F(O)==="text").length,A=w.filter(O=>F(O)==="number").length;function R(O){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:()=>D(O),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rn,{dataType:O.data_type}),e.jsx("span",{children:O.column_name})]}),e.jsx("div",{onClick:P=>P.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(O.data_type)&&e.jsx(En,{column:O})})]}):e.jsx(Mn,{onClick:D,column:O})}function M(){return e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:r!=="Success",onClick:C,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(Ta,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:B,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(st,{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((O,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:M()}),n&&n.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:l,onChange:O=>o(O.target.value)})]}),w.length>0&&e.jsx(s.Tabs,{defaultValue:"all",value:c,onValueChange:O=>i(O),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:w.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:E})]}),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:A})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-4 pt-3",children:[T.length===0&&l&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',l,'"']}),T.length===0&&!l&&c!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",c," fields found"]}),e.jsx("div",{className:"flex flex-col gap-1",children:T==null?void 0:T.map(O=>e.jsx("div",{children:R(O)},O.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function vt({ColumnsComponent:t,type:a}){var ee;const[n,r]=I.useState(!1),l=s.useEditorStore(ae=>ae.card),o=s.useEditorStore(ae=>ae.selectedConnectionId),c=s.useDashboardStore(ae=>ae.showFilters),i=s.useEditorStore(ae=>ae.selectedDatamodelId),d=s.useEditorStore(ae=>ae.selectedDatabaseName),u=s.useEditorStore(ae=>ae.selectedSchemaName),m=s.useEditorStore(ae=>ae.selectedTableName),h=s.useEditorStore(ae=>ae.isDevMode),{setSelectedTableName:f,setIsDevMode:g,setCardSql:j}=s.useEditorActions(),{connectionItems:p,modelItems:b,schemaItems:x,databaseItems:v,tableItems:k,columns:L,isConnectionsLoading:N,isModelsLoading:S,isConnectionsError:y,isModelsError:D,isDatabasesLoadingOrFetching:C,isDatabaseError:B,isSchemaLoadingOrFetching:w,isSchemaError:F,isColumnsError:T,isColumnsLoadingOrFetching:E,isTableLoadingOrFetching:A,isTableError:R,connectionType:M,isNonDbConnection:O,refetchDatabases:P,refetchModels:K,refetchSchemas:Y,refetchTables:te,refetchColumns:X,refetchConnections:$,handleConnectionChange:H,handleDatabaseChange:_,handleSchemaChange:J,handleDatamodelChange:z,handleTableChange:U,tableName:Z,schemaName:le}=s.useEditorAside(),{data:V,refetch:se}=s.useDashboardCardQuery(l);function ne(){return t?t(le,Z,L):e.jsx(On,{schemaName:le,tableName:Z,columns:L,status:E?"Loading...":T?"Error":"Success"})}function q(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function W(ae){ae===!0?V&&(j(V.userSql),setTimeout(()=>{se()},100)):j(""),g(ae)}function re(){if(!o||M==="S3"||M==="API")return null;if(!i||i==="none")return e.jsx(Re,{refetch:P,showNone:!0,onChange:_,isError:B,isLoading:C,items:v,value:d||"",title:"Database",type:"combobox"})}function ie(){if(o&&!O&&(!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 he(){if(!o||M==="S3"||M==="API")return null;if(!d||d==="none")return e.jsx(Re,{refetch:K,showNone:!0,onChange:z,isError:D,isLoading:S,items:b,value:i||"",title:"Model",type:"combobox"})}function Q(){return!o||M==="S3"||M==="API"||!d||d==="none"?null:e.jsx(Re,{refetch:Y,onChange:J,isError:F,isLoading:w,items:x,value:u||"",title:"Schema",type:"combobox"})}function oe(){function ae(){let ue=!1;return M==="API"?(ue=!1,ue):((M==="S3"||o&&d&&d!=="none"&&u)&&(ue=!0),ue)}return ae()?e.jsx(Re,{refetch:te,onChange:U,isError:R,items:k,isLoading:A,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":n,"px-4 py-4":!n}),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(!n),size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:n?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),!n&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Re,{refetch:$,items:p,title:"Connection",value:o||"",onChange:H,isLoading:N,isError:y,type:"combobox",connectionTooltip:((ee=p==null?void 0:p.find(ae=>ae.id===o))==null?void 0:ee.type)||""}),re(),ie(),he(),Q(),oe()]})]}),ne(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:a==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:h,onCheckedChange:W,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:q,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:a,onSendFeedback:n,className:r,showFeedbackButton:l=!0}){const[o,c]=I.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:[a&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:o?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),l&&n&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:n,children:[e.jsx(Ma,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),a&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleContent,{className:"space-y-2",children:e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Error SQL Query"}),e.jsx(s.CopyButton,{text:a,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:a,language:"sql"})})]})})})]})]})})}function Ct({sql:t,error:a,errorSql:n,onDebugWithAssistant:r}){const l=s.useEditorStore(u=>u.isDevMode),{setIsDevMode:o,setCardSql:c,setRunSql:i}=s.useEditorActions();function d(){o(!l),c(t),setTimeout(()=>{i(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-3",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(Nt,{error:a,errorSql:n,showFeedbackButton:!1}),!a&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!l&&t&&!a&&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"]}),a&&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:a,errorSql:n,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:a?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(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:n,sql:t,error:a,onDebugWithAssistant:r})})]})}function Bn(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:a}=s.useTheme(),n=s.useDashboardStore(p=>p.theme),r=s.useEditorStore(p=>p.frame),l=s.useEditorStore(p=>p.card),o=s.useEditorStore(p=>p.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(l),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),m=I.useRef(),h=I.useRef({}),f=r.cards.find(p=>p.id===o),g=I.useCallback(()=>{let p="";return t==="python"&&(p=(f==null?void 0:f.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(p=(f==null?void 0:f.sql)||""),p},[t,f]);I.useEffect(()=>{if(o&&l.id&&l.id!==o){if(m.current&&c){const p=m.current.getModel();p&&(h.current[l.id]=p);let b=h.current[o];if(!b){const x=g();b=c.editor.createModel(x,t),h.current[o]=b}m.current.setModel(b)}d(o,l),u(!0)}},[o,l,d,c,u,t,g]),I.useEffect(()=>{if(!c)return;const p=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",b=n==="system"?p:n;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")},[a,n,c]),I.useEffect(()=>{const p=m.current;p&&c&&l&&p.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function j(p,b){if(m.current=p,!h.current[l.id]){const x=p.getModel(),v=g();h.current[l.id]=x||(b==null?void 0:b.editor.createModel(v,t))||p.getModel()}p.setModel(h.current[l.id])}return{handleEditorDidMount:j}}function Fn(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=wt("sql");function o(c){n(c),s.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:o,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function Pn(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=wt("python");function r(l){a(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function zn({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 ws({variant:t="outline"}){var c;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(i=>i.frame);const n=s.useEditorStore(i=>i.card);Ns(((c=n.customCardPreferences)==null?void 0:c.url)||""),s.useEditorStore(i=>i.selectedSchemaName),s.useEditorStore(i=>i.selectedDatamodelId),s.useEditorStore(i=>i.selectedDatabaseName),s.useEditorStore(i=>i.selectedTableName),s.useEditorStore(i=>i.selectedConnectionId),s.useEditorStore(i=>i.isShowingVisual),n.sql;const r=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:l}=Cs();function o(){const i=l();r==null||r(i)}return e.jsxs(s.Button,{onClick:o,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Vn(){const t=s.useQueryClient(),[a,n]=I.useState(!1),r=s.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{setIsVisualEditing:l}=s.useDashboardActions(),{getUpdatedFrame:o}=Cs(),c=s.useSelectedVisual(),i=s.useUpdateVisualMutation(),d=()=>{const u=o();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}n(!0),i.mutate({visualId:c.id,data:{frameObject:u}},{onSuccess:()=>{n(!1),l(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{n(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:d,className:"h-8",size:"sm",children:[a&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!a&&e.jsxs(e.Fragment,{children:[e.jsx(gs,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function Ds(){const{setTempQueryData:t,setSqlGen:a}=s.useEditorActions(),n=s.useQueryClient(),r=s.useEditorStore(d=>d.tempQueryData),l=s.useEditorStore(d=>d.onClose),o=s.useEditorStore(d=>d.card),{queryKey:c}=s.useDashboardCardQuery(o);function i(){if(r){const{queryKey:d,queryData:u}=r;d&&u&&n.setQueryData(d,u)}a({}),l==null||l()}return e.jsxs(s.Button,{onClick:i,className:"h-8",size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function rs(){const{setTempQueryData:t}=s.useEditorActions(),a=s.useQueryClient(),n=s.useEditorStore(b=>b.isDevMode),r=s.useEditorStore(b=>b.tempQueryData),l=s.useEditorStore(b=>b.card),{queryKey:o}=s.useDashboardCardQuery(l),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:u,setCardPreferences:m,updateDataSource:h,clearQueryConfig:f,setCardConfig:g,setCardType:j}=s.useEditorActions();function p(){const b=a.getQueryData(o);r!=null&&r.queryData||t({queryKey:o,queryData:b}),a.setQueryData(o,null),a.removeQueries({queryKey:o,exact:!0}),n&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),f(),g(void 0),d(""),u(""),m({}),j("bar")}return e.jsxs(s.Button,{onClick:p,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function _n(){const t=s.useQueryClient(),[a,n]=I.useState(!1),[r,l]=I.useState(!1);s.useEditorStore(Y=>Y.frame);const o=s.useEditorStore(Y=>Y.card);s.useEditorStore(Y=>Y.isShowingVisual),s.useEditorStore(Y=>Y.selectedConnectionId),s.useEditorStore(Y=>Y.tempQueryData),s.useEditorStore(Y=>Y.selectedDatabaseName),s.useEditorStore(Y=>Y.selectedDatamodelId),s.useEditorStore(Y=>Y.selectedSchemaName);const c=s.useEditorStore(Y=>Y.showAIDialog);s.useEditorStore(Y=>Y.selectedTableName);const i=s.useEditorStore(Y=>{var te;return(te=Y==null?void 0:Y.card)==null?void 0:te.sql}),d=s.useEditorStore(Y=>{var te;return(te=Y==null?void 0:Y.card)==null?void 0:te.python}),{sheetFilterValues:u}=s.useSheetFilterValues(),{setCardCustomCfg:m,setQueryResultColumns:h,setCardSql:f,setTempQueryData:g,setPythonStdOut:j,setCardPreferences:p,setCardType:b,setCardPython:x,runAssistant:v,setShowAIDialog:k}=s.useEditorActions();s.useEditorStore(Y=>Y.onSave),s.useEditorStore(Y=>Y.onClose),s.useEditorStore(Y=>Y.actions.setSqlGen);const L=s.useEditorStore(Y=>Y.runSql),N=s.useEditorStore(Y=>Y.actions.setRunSql),S=s.useEditorStore(Y=>Y.actions.setIsSqlRunning),{data:y,isLoading:D,isFetching:C,isSuccess:B,isError:w,error:F,errorSql:T,queryKey:E,refetch:A,errorMessage:R}=s.useDashboardCardQuery(o);I.useEffect(()=>{if(y&&(y.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),j((y==null?void 0:y.output)||""),y.records.length>0)){const{dimensionKeys:Y}=s.getKeys(y.records);h(Y)}},[y,h,j]),I.useEffect(()=>{(D||C)&&S(!0),(w||B)&&S(!1),w&&(h([]),j(""))},[D,C,y,j,w,B,S,h,F]),I.useEffect(()=>{L&&(t.getQueryData(E)||A(),N(!1))},[L,A,N,E,t]);async function M(){const Y=`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(),a=s.useDashboardStore(n=>n.actions.setDashboardTheme);return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"h-7 p-2",variant:"ghost",size:"sm",children:[e.jsx(qa,{strokeWidth:1.5,className:"h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),e.jsx(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"),a("light")},children:"Light"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("dark"),a("dark")},children:"Dark"}),e.jsx(s.DropdownMenuItem,{onClick:()=>{t("system"),a("system")},children:"System"})]})]})}function es(t){var a;return{...t,sheets:(a=t==null?void 0:t.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(l=>{var o;return{...l,cards:(o=l.cards)==null?void 0:o.map(c=>at(c))}})}})}}function at(t){return{...t,customCfg:Ka(t.customCfg),data:[]}}function Ka(t){var a,n;return t?{...t,data:{...t==null?void 0:t.data,labels:[],datasets:(n=(a=t==null?void 0:t.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function Ja(t,a,n,r){if(!r)return null;const l=JSON.stringify(a);return await s.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:t,template:l,filterValues:n,operation:"create"})}async function js(t,a){if(!a)return null;const{id:n,template:r,filterValues:l,isDefault:o,shared:c}=t;return await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:l,isDefault:o,shared:c,operation:"update"})}async function Qa(t,a){return a?await s.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:t}):null}function Xa(){const[t,a]=I.useState(""),[n,r]=I.useState(!1),l=s.useDashboardStore(p=>p.lenses),{setLenses:o,setSelectedLensId:c}=s.useDashboardActions(),[i,d]=I.useState(!1),[u,m]=I.useState(!1),h=s.useDashboardStore(p=>p.dashboard),f=s.useDashboardStore(p=>p.filterValues),{authToken:g}=s.useSemaphorContext();async function j(){d(!0);const p=es(h),b=await Ja(t,p,f,g==null?void 0:g.accessToken);b&&(o([...l||[],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:p=>{a(p.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),n&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{size:"sm",variant:"outline",type:"submit",onClick:j,disabled:i,children:i?"Creating...":"Add"})})]})]})}function Za(){const[t,a]=I.useState(!1),n=s.useDashboardStore(m=>m.lenses),r=s.useDashboardStore(m=>m.selectedLensId),{setLenses:l,setSelectedLensId:o}=s.useDashboardActions(),{authToken:c}=s.useSemaphorContext();async function i(m){o(m)}async function d(m){if(await Qa(m,c==null?void 0:c.accessToken)){const f=n==null?void 0:n.filter(g=>g.id!==m);l(f||[]),o("original")}}async function u(m){const h=n==null?void 0:n.map(j=>j.id===m.id?{...j,isDefault:!m.isDefault}:{...j,isDefault:!1});l(h||[]);const f={...m,isDefault:!m.isDefault};await js(f,c==null?void 0:c.accessToken);const g=n==null?void 0:n.find(j=>j.isDefault);if(g&&g.id!==m.id){const j={...g,isDefault:!1};await js(j,c==null?void 0:c.accessToken)}}return e.jsxs(s.DropdownMenu,{open:t,onOpenChange:a,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(va,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(s.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuRadioGroup,{value:r,onValueChange:i,children:[e.jsx(s.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(m=>e.jsxs(s.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:m.id,children:[e.jsx("p",{children:m.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(s.House,{onClick:h=>{h.preventDefault(),u(m)},className:s.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!m.isDefault,"text-green-500":m.isDefault}),strokeWidth:1.5}),e.jsx(s.Cross2Icon,{onClick:h=>{h.preventDefault(),d(m.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},m.id))]})]})]})}function en({iconClassName:t}){const[a,n]=I.useState(!1),[r,l]=I.useState(""),[o,c]=I.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;n(!1),l(""),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:()=>n(!0),children:[e.jsx(ka,{className:"mr-2 h-4 w-4"}),"Download Protected PDF"]})]})]}),e.jsx(s.Dialog,{open:a,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Download Protected PDF"}),e.jsx(s.DialogDescription,{children:"Enter a password to protect your PDF. The PDF will be encrypted and require this password to open."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid gap-2",children:[e.jsx(s.Label,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Input,{id:"password",type:o?"text":"password",value:r,onChange:m=>l(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(!o),children:o?e.jsx(s.EyeOff,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(s.Eye,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:u,disabled:!r,children:"Download"})]})]})})]})}function nt({triggerButtonClassName:t}){const[a,n]=I.useState(!1),[r,l]=I.useState("create"),[o,c]=I.useState("current"),i=s.useDashboardStore(N=>{var S;return(S=N.dashboard)==null?void 0:S.sheets}),d=s.useDashboardStore(N=>N.selectedSheetId),u=i==null?void 0:i.find(N=>N.id===d),m=i&&i.length>1,{schedules:h,isLoading:f,createSchedule:g,deleteSchedule:j,isSubmitting:p,submitError:b,deletingId:x,refetch:v}=s.useSchedule({reportType:"DASHBOARD"}),k=async N=>{try{const S={format:"pdf",sheetSelection:o,pdfOptions:{pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0}};o==="current"&&u&&(S.currentSheetId=u.id,S.currentSheetName=u.title),await g({...N,reportParams:S}),l("active")}catch(S){console.error("Failed to create schedule:",S)}},L=async N=>{try{await j(N)}catch(S){console.error("Failed to delete schedule:",S)}};return e.jsxs(s.Popover,{open:a,onOpenChange:n,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:N=>l(N),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(Zs,{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:o,onValueChange:N=>c(N),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:o==="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:p,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:L,isDeleting:x,isLoading:f,onRefresh:v}):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 rt(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4",children:[e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-8 w-full rounded bg-muted"})}),e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((t,a)=>e.jsx("div",{className:"animate-pulse",children:e.jsxs("div",{className:"group relative flex items-start gap-3 px-4 py-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md bg-muted"})}),e.jsxs("div",{className:"flex w-full items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("div",{className:"h-4 w-32 rounded bg-muted"})}),e.jsx("div",{className:"shrink-0",children:e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-muted"})})]}),e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-3 w-48 rounded bg-muted"})})]}),e.jsx("div",{className:"absolute right-3 top-2",children:e.jsx("div",{className:"flex items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:e.jsx("div",{className:"h-6 w-6 rounded bg-muted"})})})]})]})},a))})]})})}function sn({visual:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onAddVisual:o,onEditVisual:c,onUpdateVisual:i,onDeleteClick:d,onDuplicateVisual:u,onShareVisual:m,formatDate:h}){var S,y,D;const{selectVisual:f}=s.useManagementActions(),g=s.useIsVisualSelected(t.id),{isConsoleMode:j}=s.useDashboardPreferences(),p=s.useDashboardStore(C=>C.actions.setIsDashboardPanelOpen),[b,x]=I.useState(!1),[v,k]=I.useState(!1);I.useEffect(()=>{n?(x(!0),k(!0)):v&&(x(!1),k(!1))},[n,v]);const L=()=>e.jsx(ns,{className:"h-4 w-4"}),N=()=>{f(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:N,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:L()}),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:C=>i==null?void 0:i(t.id,{title:C}),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:C=>i==null?void 0:i(t.id,{description:C}),isEditable:t.ownership.isOwner&&g,isPending:l,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:C=>C.stopPropagation(),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:C=>{C.stopPropagation(),o(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:x,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:C=>{C.stopPropagation(),o(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.preventDefault(),C.stopPropagation(),u(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.stopPropagation(),c==null||c(t)},children:[e.jsx(Ba,{className:"mr-2 h-3 w-3"}),"Edit"]}),e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.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:C=>{C.stopPropagation(),d(t),p(!1)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((S=t.ownership.createdBy)==null?void 0:S.type)==="tenant"||((y=t.ownership.createdBy)==null?void 0:y.type)==="organization"&&j)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Be,{className:"h-3 w-3"}),e.jsx("span",{children:((D=t.ownership.createdBy)==null?void 0:D.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 lt({value:t,onChange:a,placeholder:n="Search users by name, email, or department..."}){return e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:n,value:t,onChange:r=>a(r.target.value),className:"pl-9"})]})}function ss({currentRole:t,onRoleChange:a,roleOptions:n,disabled:r=!1,className:l="",allowDropdown:o=!0}){var d;const c=((d=n.find(u=>u.value===t))==null?void 0:d.label)||t,i=n.filter(u=>u.value!==t);return o?e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:`cursor-pointer hover:bg-muted ${r?"cursor-not-allowed opacity-50":""} ${l}`,onClick:()=>console.log("Badge clicked:",{currentRole:t,disabled:r,allowDropdown:o}),children:c})}),e.jsx(s.DropdownMenuContent,{className:"z-[51]",children:i.map(u=>e.jsx(s.DropdownMenuItem,{onClick:()=>{console.log("Dropdown item clicked:",{currentRole:t,newRole:u.value,disabled:r}),a(u.value)},disabled:r,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})},u.value))})]}):e.jsx(s.Badge,{variant:"outline",className:`text-xs ${l}`,children:c})}function ot({selectedUsers:t,selectedUserObjects:a,onRemove:n,onRoleChange:r,getRoleOptions:l}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium",children:["Selected Users (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(o=>n(o.id)),className:"h-auto p-1 text-xs",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:a.map(o=>{const c=t.find(d=>d.id===o.id),i=l(o.type);return e.jsxs(s.Badge,{variant:"secondary",className:"gap-1",children:[o.name,e.jsx(ss,{currentRole:(c==null?void 0:c.role)||"VIEWER",onRoleChange:d=>r(o.id,d),roleOptions:i}),e.jsx("button",{onClick:()=>n(o.id),className:"ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},o.id)})}),e.jsx(s.Separator,{})]})}function it({usersToRemove:t,allUsers:a,onRemove:n}){return t.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{className:"text-sm font-medium text-destructive",children:["Users to Remove Access (",t.length,")"]}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>t.forEach(r=>n(r)),className:"h-auto p-1 text-xs text-destructive hover:text-destructive",children:"Clear all"})]}),e.jsx("div",{className:"flex max-h-20 flex-wrap gap-2 overflow-y-auto",children:a.filter(r=>t.includes(r.id)).map(r=>e.jsxs(s.Badge,{variant:"destructive",className:"gap-1",children:[r.name,e.jsx("button",{onClick:()=>n(r.id),className:"ml-1 rounded-full p-0.5 hover:bg-destructive-foreground/20",children:e.jsx(s.X,{className:"h-3 w-3"})})]},r.id))}),e.jsx(s.Separator,{})]})}function ct({usersToUpdate:t,allUsers:a,onRemove:n,getRoleOptions:r}){if(t.length===0)return null;const l=r("tenant"),o=i=>{const d=a.find(u=>u.id===i);return(d==null?void 0:d.name)||"Unknown User"},c=i=>{const d=l.find(u=>u.value===i);return(d==null?void 0:d.label)||i};return e.jsxs("div",{className:"rounded-lg border border-orange-200 bg-orange-50 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Users,{className:"h-4 w-4 text-orange-600"}),e.jsxs("span",{className:"text-sm font-medium text-orange-800",children:["Updating Access (",t.length,")"]})]}),e.jsx("div",{className:"space-y-2",children:t.map(i=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:o(i.id)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c(i.currentRole)}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx(s.Badge,{variant:"default",className:"text-xs",children:c(i.newRole)})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",onClick:()=>n(i.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},i.id))})]})}function dt(t,a={}){const{enabled:n=!0,eventType:r="mousedown"}=a,l=I.useRef(null);return I.useEffect(()=>{const o=c=>{const i=c.target;l.current&&l.current.contains(i)||i instanceof Element&&(i.closest("[data-radix-popper-content-wrapper]")||i.closest("[data-radix-select-content]")||i.closest("[data-radix-popover-content]")||i.closest("[data-radix-dropdown-menu-content]")||i.closest("[data-radix-tooltip-content]")||i.closest('[role="listbox"]')||i.closest('[role="option"]')||i.closest('[role="combobox"]'))||i instanceof Element&&i.hasAttribute("data-radix-")||t()};return n&&document.addEventListener(r,o),()=>{document.removeEventListener(r,o)}},[t,n,r]),l}function je(t,a){var n;return((n=a.find(r=>r.value===t))==null?void 0:n.label)||t}function tn(t){return["POWER_USER","ADMIN","EDITOR"].includes(t)}function ut(t){return"tenantId"in t&&t.tenantId?"tenant":"organization"}function an(t,a,n){const r=ut(t),l=(n==null?void 0:n.type)||"organization";if(!(!a||!a.shares))if(l==="organization")if(r==="organization"){if("specificOrgUsers"in a.shares)return(a.shares.specificOrgUsers||[]).find(i=>i.orgUserId===t.id)}else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id);else return(a.shares.specificTenantUsers||[]).find(i=>i.tenantUserId===t.id)}function nn({user:t}){return ut(t)==="tenant"?e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:t.role==="POWER_USER"?"Power User":"Viewer"}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:t.role==="ADMIN"?"Admin":t.role==="POWER_USER"?"Power User":"Viewer"})}function rn({user:t,userShare:a,usersToUpdate:n,currentUser:r,getRoleOptions:l,handleUpdateAccess:o}){if(!(a!=null&&a.role))return null;const c=tn((r==null?void 0:r.type)||""),i=n.some(h=>h.id===t.id),d=n.find(h=>h.id===t.id),u=d?d.newRole:a==null?void 0:a.role,m=l(t.type);return a?e.jsx("div",{className:"flex items-center gap-2",children:c?e.jsx(ss,{currentRole:u,onRoleChange:h=>{o(t.id,a.role,h)},roleOptions:m,disabled:!c,allowDropdown:c,className:i?"border-orange-300 bg-orange-100":""}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:je(u,m)})}):e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:"Unknown"})}function ln({hasAccess:t,isUserRemoving:a,isSelected:n,hasAccessFromAPI:r}){return e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t&&!a&&e.jsxs(s.Badge,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[e.jsx(s.Eye,{className:"mr-1 h-3 w-3"}),"Has Access"]}),a&&e.jsxs(s.Badge,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[e.jsx(s.X,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),n&&!r&&e.jsxs(s.Badge,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[e.jsx(Ye,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function on({isUserRemoving:t,isSelected:a,hasAccess:n,isRemoving:r,isSharing:l}){return e.jsxs(e.Fragment,{children:[t&&e.jsx("span",{className:"text-xs font-medium text-red-600",children:r?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"}),a&&!n&&e.jsx("span",{className:"text-xs font-medium text-blue-600",children:l?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Sharing..."]}):"Will share"})]})}function cn({existingShares:t,allUsers:a,getRoleOptions:n,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in t.shares){const c=t.shares,i=c.specificOrgUsers||[],d=c.specificTenantUsers||[],u=c.orgWide||[],m=c.orgUsersOnly||[],h=c.allTenantsOnly||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",i.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((f,g)=>{var x,v;const j=((x=a.find(k=>k.id===f.orgUserId))==null?void 0:x.name)||"Unknown User",p=((v=a.find(k=>k.id===f.orgUserId))==null?void 0:v.type)||"",b=je(f.role,n(p));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((f,g)=>{var x,v;const j=((x=a.find(k=>k.id===f.tenantUserId))==null?void 0:x.name)||"Unknown User",p=((v=a.find(k=>k.id===f.tenantUserId))==null?void 0:v.type)||"",b=je(f.role,n(p));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((f,g)=>{const j=je(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children: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((f,g)=>{const j=je(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children: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((f,g)=>{const j=je(f.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children: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=a.find(p=>p.id===d.tenantUserId))==null?void 0:g.name)||"Unknown User",h=((j=a.find(p=>p.id===d.tenantUserId))==null?void 0:j.type)||"",f=je(d.role,n(h));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:m}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:f})]},u)}),c.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",c.length-3," more users"]})]})]}),i.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:i.map((d,u)=>{const m=je(d.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},u)})})]}),!c.length&&!i.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const o=t.shares.specificTenantUsers||[],c=t.shares.tenantWide||[];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"font-medium",children:"Current Access"}),e.jsxs("div",{className:"space-y-2",children:[o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",o.length,")"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[o.slice(0,3).map((i,d)=>{var f,g;const u=((f=a.find(j=>j.id===i.tenantUserId))==null?void 0:f.name)||"Unknown User",m=((g=a.find(j=>j.id===i.tenantUserId))==null?void 0:g.type)||"",h=je(i.role,n(m));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"truncate text-muted-foreground",children:u}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},d)}),o.length>3&&e.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),c.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),e.jsx("div",{className:"grid grid-cols-1 gap-1",children:c.map((i,d)=>{const u=je(i.role,n(""));return e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},d)})})]}),!o.length&&!c.length&&e.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function dn({isInitialLoading:t,searchQuery:a,availableUsers:n}){return t?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(s.LoaderCircle,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):n.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:a?"No users found matching your search.":"No users available to share with."}):null}function un({user:t,userShare:a,isUserRemoving:n,hasAccess:r,hasAccessFromAPI:l,isSelected:o,selectedUser:c,roleOptions:i,currentUser:d,usersToUpdate:u,handleUserToggle:m,handleRemoveAccess:h,handleUpdateAccess:f,handleUserRoleChange:g}){return e.jsxs("div",{className:s.cn("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!n?"border border-green-200 bg-green-50":n?"border border-red-200 bg-red-50":o?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[e.jsx(s.Checkbox,{checked:l?!n:o,disabled:t.id===(d==null?void 0:d.id),onCheckedChange:()=>{l?n?m(t.id):h(t.id):m(t.id)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:t.name}),e.jsx(nn,{user:t})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?e.jsx(ss,{currentRole:a==null?void 0:a.role,onRoleChange:j=>f(t.id,a.role,j),roleOptions:i,disabled:!1,allowDropdown:!0}):e.jsx(rn,{user:t,userShare:a,usersToUpdate:u,currentUser:d,getRoleOptions:()=>i,handleUpdateAccess:f}),o&&!l&&e.jsx("div",{onClick:j=>j.stopPropagation(),children:e.jsx(ss,{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:n,isSelected:o,hasAccessFromAPI:l}),e.jsx(on,{isUserRemoving:n,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function mt({existingShares:t,isInitialLoading:a,isSearching:n,getRoleOptions:r,allUsers:l=[],currentUser:o,handleUserToggle:c,handleUserRoleChange:i,handleRemoveAccess:d,handleUpdateAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),g=s.useShareSearchQuery(),j=s.useShareManagementActions(),p=c||(N=>{const S=m.some(D=>D.id===N),y=h.includes(N);S?j.removeSelectedUser(N):y?j.removeUserFromRemove(N):j.addSelectedUser({id:N,role:"VIEWER"})}),b=i||j.updateSelectedUserRole,x=d||j.addUserToRemove,v=u||((N,S,y)=>{j.addUserToUpdate({id:N,currentRole:S,newRole:y})}),k=l,L=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:l,getRoleOptions:r,currentUser:o})})]})})]}),(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(N=>({id:N.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:a,isSearching:n,searchQuery:g,availableUsers:k||[]}),!a&&!n&&(k==null?void 0:k.length)>0&&k.map(N=>{const S=t?an(N,t,o):void 0,y=L.includes(N.id),D=!!S,C=D&&!y,B=m.some(T=>T.id===N.id),w=m.find(T=>T.id===N.id),F=r(N.type);return e.jsx(un,{user:N,userShare:S,isUserRemoving:y,hasAccess:C,hasAccessFromAPI:D,isSelected:B,selectedUser:w,roleOptions:F,currentUser:o,usersToUpdate:f,handleUserToggle:p,handleRemoveAccess:x,handleUpdateAccess:v,handleUserRoleChange:b},N.id)})]})]})}function ht({shareType:t,onShareTypeChange:a,currentUser:n,options:r}){const l=(n==null?void 0:n.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.RadioGroup,{value:t,onValueChange:a,className:`grid grid-cols-${r.length} gap-4`,children:r.map(o=>e.jsxs("div",{children:[e.jsx(s.RadioGroupItem,{value:o.value,id:o.value,className:"peer sr-only",disabled:o.disabled}),e.jsxs(s.Label,{htmlFor:o.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${o.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[o.icon||e.jsx(Be,{className:"mb-3 h-6 w-6"}),e.jsxs("div",{className:"space-y-1 text-center",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:o.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o.description})]})]})]},o.value))}),!l&&r.some(o=>o.value==="all_users")&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only admins, authors, power users, and super admins can share with all users."})]})}const Te=()=>[{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:a,isSharing:n,onUpdateAccess:r,allUsersToUpdate:l=null,allUsersToRemove:o=!1,isUpdating:c=!1,isRemoving:i=!1}){const d=s.useShareCurrentMode(),u=Te().filter(v=>v.value==="VIEWER"||v.value==="EDITOR"||v.value==="CONTRIBUTOR"),m=a.role!=="NONE"?a.role:"NONE",h=l?l.newRole:m,f=a.role!=="NONE"&&!o&&(!l||l.newRole===m),g=l!==null&&l.newRole!==m,j=o,p=m==="NONE"||!m,b=v=>{switch(v){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"})}},x=v=>{r(m,v)};return e.jsx("div",{className:"space-y-4",children:e.jsxs(s.Card,{className:s.cn("pb-6",g&&!j&&!p?"border-orange-300 bg-orange-50":f?"border-green-300 bg-green-50":j||p?"border-destructive bg-destructive/10":""),children:[e.jsxs(s.CardHeader,{children:[e.jsxs(s.CardTitle,{className:"flex items-center gap-2 text-base",children:[e.jsx(s.Users,{className:"h-5 w-5"}),"Share with All"," ",d==="allOrgUsers"?"Organization":d==="allTenantUsers"?"Tenant":d==="specificOrgUsers"?"Org":"Tenant"," ","Users",f&&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||p)&&e.jsx(s.Badge,{variant:"destructive",className:"ml-2",children:"No Access"})]}),e.jsx(s.CardDescription,{children:j||p?"No access for all users.":"This will share the dashboard with all users in your "+((t==null?void 0:t.type)==="organization"?"organization":"tenant")+". Select an access level below."})]}),e.jsx(s.CardContent,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Select Access Level:"}),e.jsxs(s.HoverCard,{children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-4 w-4 p-0 text-muted-foreground hover:text-foreground",children:e.jsx(s.Info,{className:"h-3 w-3"})})}),e.jsx(s.HoverCardContent,{className:"w-80",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Share with All Users"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["This action will share the dashboard with all users in your"," ",(t==null?void 0:t.type)==="organization"?"organization":"tenant",". Users will receive the selected access level."]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Viewer:"})," Can view the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Editor:"})," Can view and edit the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Contributor:"})," Can view, edit, and share the dashboard"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"None:"})," No access for all users"]})]})]})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:u.map(v=>e.jsxs(s.Button,{variant:h===v.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>x(v.value),disabled:n||c||i,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[b(v.value),e.jsx("span",{className:"font-medium",children:v.label})]}),e.jsx("p",{className:"text-left text-xs text-muted-foreground",children:v.description})]},v.value))})]})})]})})}function xt({currentUser:t,currentShare:a,isSharing:n,isUpdating:r,isRemoving:l,onUpdateAccess:o,onRemoveAccess:c,allUsersToUpdate:i,allUsersToRemove:d}){const u=p=>p==="OWNER"?"CONTRIBUTOR":p,h=a?{role:u(a.role)}:{role:"NONE"},f=i?{currentRole:u(i.currentRole),newRole:u(i.newRole)}:null,g=(p,b)=>{o(p,b)},j=()=>{c()};return e.jsx(mn,{currentUser:t,currentShare:h,isSharing:n,isUpdating:r,isRemoving:l,onUpdateAccess:g,onRemoveAccess:j,allUsersToUpdate:f,allUsersToRemove:d})}const hn=async(t,a={})=>{const n={};return a.search&&(n.search=a.search),a.type&&(n.type=a.type),a.active!==void 0&&(n.active=a.active.toString()),a.tenantId&&(n.tenantId=a.tenantId),a.limit&&(n.limit=a.limit.toString()),a.offset&&(n.offset=a.offset.toString()),a.page&&(n.page=a.page.toString()),a.pageSize&&(n.pageSize=a.pageSize.toString()),await s.getRequest("https://semaphor.cloud/api/management/v1/unified-users",t,n)};function xn(t={}){var o,c,i;const{authToken:a,tokenProps:n}=s.useSemaphorContext(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),l=s.useQuery({queryKey:["unified-users",t],queryFn:()=>hn((a==null?void 0:a.accessToken)||"",t),enabled:!!(a!=null&&a.accessToken)&&!!r,retry:(d,u)=>u instanceof Error&&u.message.includes("401")||u instanceof Error&&u.message.includes("403")?!1:d<2,retryDelay:d=>Math.min(1e3*2**d,3e4)});return{users:((o=l.data)==null?void 0:o.users)||[],userContext:(c=l.data)==null?void 0:c.userContext,total:((i=l.data)==null?void 0:i.total)||0,isLoading:l.isLoading,isError:l.isError,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function De(t){const{debouncedSearchQuery:a,resourceId:n,resourceType:r=s.ResourceType.DASHBOARD,userType:l,tenantId:o}=t,c=I.useMemo(()=>({search:a,active:!0,...l?{type:l}:{},...l==="tenant"&&o?{tenantId:o}:{}}),[a,l,o]),{users:i,isLoading:d,isError:u}=xn(c),m=s.useResourceShares(r,n);return{allUsers:i,isLoadingUsers:d,isErrorLoadingUsers:u,existingShares:m.data,isLoadingShares:m.isLoading,isErrorLoadingShares:m.isError,isFetchingShares:m.isFetching}}function pn({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var te,X;const i=s.useShareSelectedTab(),d=s.useShareSelectedTenant(),{searchQuery:u,setSearchQuery:m,debouncedSearchQuery:h}=s.useShareSearchWithDebounce(),f=s.useShareSelectedUsers(),g=s.useShareUsersToRemove(),j=s.useShareUsersToUpdate(),p=s.useShareCurrentMode(),b=s.useShareOrgWideRole(),x=s.useShareManagementActions(),[v,k]=I.useState("specific_users"),L=()=>{if(i==="org")return"organization";if(i==="tenant")return"tenant"},N=()=>{if(i==="tenant"&&d)return d},{allUsers:S,existingShares:y,isLoadingUsers:D}=De({debouncedSearchQuery:h,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:L(),tenantId:N()});I.useEffect(()=>{x.setCurrentContext("org-tab"),x.setCurrentMode(v==="all_users"?"allOrgUsers":"specificOrgUsers")},[x,v]);const C=$=>{var _,J;const H=$;if(k(H),r==null||r(H),x.setCurrentContext("org-tab"),H==="specific_users")x.setCurrentMode("specificOrgUsers");else if(H==="all_users"){x.setCurrentMode("allOrgUsers");const z=(J=(_=y==null?void 0:y.shares)==null?void 0:_.orgUsersOnly)==null?void 0:J[0];z&&z.role!==void 0&&x.setOrgWideRole(z.role)}},B=S.filter($=>$.name.toLowerCase().includes(u.toLowerCase())||$.email.toLowerCase().includes(u.toLowerCase())),w=S.filter($=>f.some(H=>H.id===$.id)),F=$=>{var z,U;const H=f.some(Z=>Z.id===$),_=g.includes($),J=(U=(z=y==null?void 0:y.shares)==null?void 0:z.specificOrgUsers)==null?void 0:U.some(Z=>Z.orgUserId===$);H?x.removeSelectedUser($):_?x.removeUserFromRemove($):J||x.addSelectedUser({id:$,role:"VIEWER"})},T=($,H)=>{x.updateSelectedUserRole($,H)},E=$=>{x.addUserToRemove($),x.removeSelectedUser($)},A=$=>{x.removeUserFromRemove($)},R=$=>{x.removeUserFromUpdate($)},M=($,H)=>{x.setOrgWideRole(H)},O=()=>{x.setOrgWideRole((P==null?void 0:P.role)||"NONE")},P=(X=(te=y==null?void 0:y.shares)==null?void 0:te.orgUsersOnly)==null?void 0:X[0];I.useEffect(()=>{v==="all_users"&&P&&P.role!==void 0&&x.setOrgWideRole(P.role)},[v,P,x]);const K=D,Y=!1;return n?e.jsxs(e.Fragment,{children:[e.jsx(ht,{shareType:v,onShareTypeChange:C,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:e.jsx(Be,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(n==null?void 0:n.type)==="organization"?"organization":"tenant"} users`,icon:e.jsx(s.Users,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),v==="specific_users"?e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(lt,{value:u,onChange:m}),e.jsx(ot,{selectedUsers:f,selectedUserObjects:w,onRemove:F,onRoleChange:T,getRoleOptions:Te}),e.jsx(it,{usersToRemove:g,allUsers:B,onRemove:A}),e.jsx(ct,{usersToUpdate:j,allUsers:B,onRemove:R,getRoleOptions:Te}),e.jsx(mt,{existingShares:y,isInitialLoading:K,isSearching:Y,resource:t,onShare:()=>{},getRoleOptions:Te,allUsers:B,currentUser:n,handleUserToggle:F,handleUserRoleChange:T,handleRemoveAccess:E,handleUpdateAccess:($,H,_)=>{x.addUserToUpdate({id:$,currentRole:H,newRole:_})}})]}):e.jsx("div",{className:"mt-3",children:e.jsx(xt,{currentUser:n,currentShare:P,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:M,onRemoveAccess:O,allUsersToUpdate:p==="allOrgUsers"&&b!==((P==null?void 0:P.role)||"NONE")?{currentRole:(P==null?void 0:P.role)||"NONE",newRole:b}:null,allUsersToRemove:p==="allOrgUsers"&&(P==null?void 0:P.role)===void 0})})]}):null}function Vs({resource:t,resourceType:a,currentUser:n,onShareTabTypeChange:r,isSharing:l=!1,isUpdating:o=!1,isRemoving:c=!1}){var z;const{searchQuery:i,debouncedSearchQuery:d,setSearchQuery:u}=s.useShareSearchWithDebounce(),m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate(),g=s.useShareCurrentMode(),j=s.useShareTenantWideRole(),p=s.useShareAllTenantsRole(),b=s.useShareSelectedTenant(),x=s.useShareManagementActions(),{data:v,isLoading:k}=s.useTenants({enabled:(n==null?void 0:n.type)==="organization"}),[L,N]=I.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");I.useEffect(()=>{(n==null?void 0:n.type)==="tenant"?(x.setCurrentContext("tenant-dialog"),x.setCurrentMode("specificTenantUsers")):(x.setCurrentContext("tenant-tab"),x.setCurrentMode("allTenants"))},[x,n==null?void 0:n.type]);const S=U=>{var le,V,se,ne;N(U);let Z;if(U==="specific_tenant_users"?Z="specific_users":U==="all_tenant_users"||U==="all_tenants"?Z="all_users":Z="specific_users",r==null||r(Z),(n==null?void 0:n.type)==="tenant"?(x.setCurrentContext("tenant-dialog"),U==="specific_tenant_users"?x.setCurrentMode("specificTenantUsers"):U==="all_tenant_users"&&(x.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&x.setSelectedTenant(n.tenantId))):(x.setCurrentContext("tenant-tab"),U==="specific_tenant_users"?x.setCurrentMode("specificTenantUsers"):U==="all_tenant_users"?x.setCurrentMode("allTenantUsers"):U==="all_tenants"&&x.setCurrentMode("allTenants")),U==="all_tenant_users"){const q=(V=(le=C==null?void 0:C.shares)==null?void 0:le.tenantWide)==null?void 0:V[0];q&&q.role!==void 0&&x.setTenantWideRole(q.role)}else if(U==="all_tenants"){const q=(ne=(se=C==null?void 0:C.shares)==null?void 0:se.allTenantsOnly)==null?void 0:ne[0];q&&q.role!==void 0&&x.setAllTenantsRole(q.role)}},y=U=>{x.setSelectedTenant(U)},{allUsers:D,existingShares:C,isLoadingUsers:B,isErrorLoadingUsers:w,isLoadingShares:F,isErrorLoadingShares:T}=De({debouncedSearchQuery:d,resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:b}),E=U=>{var se,ne;const Z=m.some(q=>q.id===U),le=h.includes(U),V=(ne=(se=C==null?void 0:C.shares)==null?void 0:se.specificTenantUsers)==null?void 0:ne.some(q=>q.tenantUserId===U);Z?x.removeSelectedUser(U):le?x.removeUserFromRemove(U):V||x.addSelectedUser({id:U,role:"VIEWER"})},A=(U,Z)=>{x.updateSelectedUserRole(U,Z)},R=U=>{x.addUserToRemove(U),x.removeSelectedUser(U)},M=U=>{x.removeUserFromRemove(U)},O=U=>{x.removeUserFromUpdate(U)},P=(U,Z,le)=>{x.addUserToUpdate({id:U,currentRole:Z,newRole:le})},K=(U,Z)=>{L==="all_tenant_users"?x.setTenantWideRole(Z):L==="all_tenants"&&x.setAllTenantsRole(Z)},Y=()=>{L==="all_tenant_users"?x.setTenantWideRole("VIEWER"):L==="all_tenants"&&x.setAllTenantsRole("VIEWER")},X=(()=>{var U,Z,le,V;return g==="allTenants"?(Z=(U=C==null?void 0:C.shares)==null?void 0:U.allTenantsOnly)==null?void 0:Z[0]:g==="allTenantUsers"?(V=(le=C==null?void 0:C.shares)==null?void 0:le.tenantWide)==null?void 0:V[0]:null})();I.useEffect(()=>{var U,Z,le,V;if(L==="all_tenant_users"){const se=(Z=(U=C==null?void 0:C.shares)==null?void 0:U.tenantWide)==null?void 0:Z[0];se&&se.role!==void 0&&x.setTenantWideRole(se.role)}else if(L==="all_tenants"){const se=(V=(le=C==null?void 0:C.shares)==null?void 0:le.allTenantsOnly)==null?void 0:V[0];se&&se.role!==void 0&&x.setAllTenantsRole(se.role)}},[L,C,x]);const $=D.filter(U=>m.some(Z=>Z.id===U.id)),H=B||F,_=w||T,J=()=>(n==null?void 0:n.type)==="tenant"||L==="all_tenants"?!0:b&&(L==="specific_tenant_users"||L==="all_tenant_users");return e.jsxs(e.Fragment,{children:[_&&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"})]})}),!_&&n&&e.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[e.jsx(ht,{shareType:L,onShareTypeChange:S,currentUser:n,options:(n==null?void 0:n.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:e.jsx(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(Be,{className:"mb-3 h-6 w-6 text-orange-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:e.jsx(Fs,{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(Be,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(n==null?void 0:n.type)==="organization"&&(L==="specific_tenant_users"||L==="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:b||"",onValueChange:y,disabled:k,children:[e.jsx(s.SelectTrigger,{className:"w-full",children:e.jsx(s.SelectValue,{placeholder:k?"Loading tenants...":"Select a tenant..."})}),e.jsx(s.SelectContent,{className:"z-[51]",children:(z=v==null?void 0:v.tenants)==null?void 0:z.map(U=>e.jsx(s.SelectItem,{value:U.id,children:U.name},U.id))})]})]}),J()?e.jsx(e.Fragment,{children:L==="specific_tenant_users"?e.jsxs("div",{className:"space-y-4",children:[e.jsx(lt,{value:i,onChange:u}),e.jsx(ot,{selectedUsers:m,selectedUserObjects:$,onRemove:U=>E(U),onRoleChange:A,getRoleOptions:Te}),e.jsx(it,{usersToRemove:h,allUsers:D,onRemove:M}),e.jsx(ct,{usersToUpdate:f,allUsers:D,onRemove:O,getRoleOptions:Te}),e.jsx(mt,{existingShares:C,isInitialLoading:!!H,isSearching:!1,resource:t,onShare:()=>{},getRoleOptions:Te,allUsers:D,currentUser:n,handleUserToggle:E,handleUserRoleChange:A,handleRemoveAccess:R,handleUpdateAccess:P})]}):L==="all_tenant_users"||L==="all_tenants"?e.jsx("div",{className:"mt-6",children:e.jsx(xt,{currentUser:n,currentShare:X,isSharing:l,isUpdating:o,isRemoving:c,onUpdateAccess:K,onRemoveAccess:Y,allUsersToUpdate:g==="allTenantUsers"&&((X==null?void 0:X.role)===void 0||j!==X.role)||g==="allTenants"&&((X==null?void 0:X.role)===void 0||p!==X.role)?{currentRole:(X==null?void 0:X.role)||"VIEWER",newRole:g==="allTenantUsers"?j:p}:null,allUsersToRemove:g==="allTenantUsers"&&(X==null?void 0:X.role)===void 0||g==="allTenants"&&(X==null?void 0:X.role)===void 0})}):null}):(n==null?void 0:n.type)==="organization"&&(L==="specific_tenant_users"||L==="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(Fs,{className:"mx-auto mb-2 h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant to continue"})]})})]})]})}const pt=()=>{const t=s.useShareCurrentContext(),a=s.useShareCurrentMode(),n=s.useShareSelectedUsers(),r=s.useShareUsersToRemove(),l=s.useShareUsersToUpdate(),o=s.useShareSelectedTenant(),c=s.useShareOrgWideRole(),i=s.useShareAllTenantsRole(),d=s.useShareTenantWideRole(),u=I.useMemo(()=>()=>s.buildShareData({currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}),[t,a,n,r,l,o,c,i,d]),m=I.useMemo(()=>f=>s.validateShareData(f),[]),h=I.useMemo(()=>{if(!t||!a)return!1;switch(t){case"org-tab":return a==="specificOrgUsers"?n.length>0||r.length>0||l.length>0:!0;case"tenant-tab":if(a==="allTenantUsers"){if(!o)return!1}else if(a==="specificTenantUsers")return o?n.length>0||r.length>0||l.length>0:!1;return!0;case"tenant-dialog":return a==="specificTenantUsers"?n.length>0||r.length>0||l.length>0:!0}return!1},[t,a,n,r,l,o]);return{buildShareData:u,validateShareData:m,isCurrentStateValid:h,currentContext:t,currentMode:a,selectedUsers:n,usersToRemove:r,usersToUpdate:l,selectedTenant:o,orgWideRole:c,allTenantsRole:i,tenantWideRole:d}};function _s({resource:t,existingShares:a,isSharing:n,isRemoving:r,isUpdating:l,onShare:o,onClose:c,shareTabType:i,currentAllUsersShare:d,onRemoveAccess:u}){const m=s.useShareSelectedUsers(),h=s.useShareUsersToRemove(),f=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const g=s.useShareSelectedTenant();s.useShareSelectedTab();const j=s.useShareOrgWideRole(),p=s.useShareAllTenantsRole(),b=s.useShareTenantWideRole(),{buildShareData:x,validateShareData:v,isCurrentStateValid:k}=pt(),L=n||r||l,N=()=>{var B,w,F,T;if(L)return"Updating...";if(i==="specific_users"){if(m.length===0&&h.length===0&&f.length===0)return"Select users to share with";const E=m.length+h.length+f.length;return E===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${E} user${E!==1?"s":""}`:h.length>0&&m.length===0&&f.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&f.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:f.length>0&&m.length===0&&h.length===0?`Update access for ${f.length} user${f.length!==1?"s":""}`:`Update access for ${E} user${E!==1?"s":""}`}else if(i==="all_users"){if(!d||d.role===void 0)return"Share with All Users";const E=d.role;return j===E?"Remove Access":"Update Access"}else if(i==="all_tenants"){const E=(w=(B=a==null?void 0:a.shares)==null?void 0:B.allTenantsOnly)==null?void 0:w[0];if(!E||E.role===void 0)return"Share with All Tenants";const A=E.role;return p===A?"Remove Access":"Update Access"}else if(i==="all_tenant_users"){const E=(T=(F=a==null?void 0:a.shares)==null?void 0:F.tenantWide)==null?void 0:T[0];if(!E||E.role===void 0)return"Share with All Tenant Users";const A=E.role;return b===A?"Remove Access":"Update Access"}else if(i==="specific_tenant_users"){if(m.length===0&&h.length===0&&f.length===0)return"Select users to share with";const E=m.length+h.length+f.length;return E===0?"Select users to share with":m.length>0&&h.length>0?`Update access for ${E} user${E!==1?"s":""}`:h.length>0&&m.length===0&&f.length===0?`Remove access for ${h.length} user${h.length!==1?"s":""}`:m.length>0&&h.length===0&&f.length===0?`Share with ${m.length} user${m.length!==1?"s":""}`:f.length>0&&m.length===0&&h.length===0?`Update access for ${f.length} user${f.length!==1?"s":""}`:`Update access for ${E} user${E!==1?"s":""}`}return"Share"},S=()=>L||!t||i==="all_tenant_users"&&!g||i==="specific_tenant_users"&&!g?!0:!k,y=()=>{const B=x();B&&v(B)&&o(B)},D=()=>{var B,w,F,T;if(i==="all_users")if(!d||d.role===void 0){const E=x();E&&v(E)&&o(E)}else{const E=d.role;if(j===E)u==null||u();else{const R=x();if(R&&v(R)){const M={...R,updateAccess:!0};o(M)}}}else if(i==="all_tenants"){const E=(w=(B=a==null?void 0:a.shares)==null?void 0:B.allTenantsOnly)==null?void 0:w[0];if(!E||E.role===void 0){const A=x();A&&v(A)&&o(A)}else{const A=E.role;if(p===A)u==null||u();else{const M=x();if(M&&v(M)){const O={...M,updateAccess:!0};o(O)}}}}else if(i==="all_tenant_users"){const E=(T=(F=a==null?void 0:a.shares)==null?void 0:F.tenantWide)==null?void 0:T[0];if(!E||E.role===void 0){const A=x();A&&v(A)&&o(A)}else{const A=E.role;if(b===A)u==null||u();else{const M=x();if(M&&v(M)){const O={...M,updateAccess:!0};o(O)}}}}},C=()=>{var B,w,F,T;if(i==="all_users"){if(!d||d.role===void 0)return"default";const E=d.role;return j===E?"destructive":"default"}else if(i==="all_tenants"){const E=(w=(B=a==null?void 0:a.shares)==null?void 0:B.allTenantsOnly)==null?void 0:w[0];if(!E||E.role===void 0)return"default";const A=E.role;return p===A?"destructive":"default"}else if(i==="all_tenant_users"){const E=(T=(F=a==null?void 0:a.shares)==null?void 0:F.tenantWide)==null?void 0:T[0];if(!E||E.role===void 0)return"default";const A=E.role;return b===A?"destructive":"default"}return"default"};return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:c,disabled:L,children:"Close"}),(i==="specific_users"||i==="specific_tenant_users")&&e.jsx(e.Fragment,{children:(m.length>0||h.length>0||f.length>0)&&e.jsxs(s.Button,{onClick:y,disabled:!t||L,variant:"default",children:[L?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!L&&N()]})}),(i==="all_users"||i==="all_tenants"||i==="all_tenant_users")&&e.jsxs(s.Button,{onClick:D,disabled:S(),variant:C(),children:[L?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"}),!L&&N()]})]})}function fn({resource:t,isSharing:a,isRemoving:n,isUpdating:r,onShare:l,onClose:o,shareTabType:c,currentAllUsersShare:i}){const d=s.useShareSelectedUsers(),u=s.useShareUsersToRemove(),m=s.useShareUsersToUpdate();s.useShareCurrentMode(),s.useShareCurrentContext();const h=s.useShareTenantWideRole();s.useShareSelectedTenant();const{buildShareData:f,validateShareData:g,isCurrentStateValid:j}=pt(),p=a||n||r,b=()=>{if(p)return"Updating...";if(c==="specific_users"){if(d.length===0&&u.length===0&&m.length===0)return"Select users to share with";const N=d.length+u.length+m.length;return N===0?"Select users to share with":d.length>0&&u.length>0?`Update access for ${N} user${N!==1?"s":""}`:u.length>0&&d.length===0&&m.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:d.length>0&&u.length===0&&m.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:m.length>0&&d.length===0&&u.length===0?`Update access for ${m.length} user${m.length!==1?"s":""}`:`Update access for ${N} user${N!==1?"s":""}`}else if(c==="all_users"){if(!i||i.role==="NONE")return"Share with All Users";const N=i.role;return h===N?"Remove Access":"Update Access"}return"Share"},x=()=>p||!t?!0:!j,v=()=>{const N=f();N&&g(N)&&l(N)},k=()=>{if(!i||i.role==="NONE"){const N=f();N&&g(N)&&l(N)}else{const N=i.role;if(h===N){const y=f();if(y&&g(y)){const D={...y,removeAccess:!0};l(D)}}else{const y=f();if(y&&g(y)){const D={...y,updateAccess:!0};l(D)}}}},L=()=>!i||i.role==="NONE"?"default":"destructive";return e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:o,disabled:p,children:"Close"}),c==="specific_users"&&e.jsx(e.Fragment,{children:(d.length>0||u.length>0||m.length>0)&&e.jsxs(s.Button,{onClick:v,disabled:!t||p,variant:"default",children:[p?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!p&&b()]})}),c==="all_users"&&e.jsxs(s.Button,{onClick:k,disabled:x(),variant:L(),children:[p?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):e.jsx(Ye,{className:"mr-2 h-4 w-4"}),!p&&b()]})]})}function ft({resource:t,resourceType:a,isSharing:n,isRemoving:r,isUpdating:l,onClose:o,onShare:c,onRemoveAccess:i}){var y,D,C,B;const{currentUser:d}=s.useCurrentUserInfo(),[u,m]=I.useState("specific_users"),[h,f]=I.useState("specific_users"),g=s.useShareManagementActions(),j=s.useShareSelectedTab(),p=s.useShareCurrentMode(),{existingShares:b}=De({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"tenant"}),{existingShares:x}=De({debouncedSearchQuery:"",resourceId:(t==null?void 0:t.id)||"",resourceType:a,userType:"organization"}),v=(D=(y=b==null?void 0:b.shares)==null?void 0:y.tenantWide)==null?void 0:D[0],k=(B=(C=x==null?void 0:x.shares)==null?void 0:C.orgUsersOnly)==null?void 0:B[0],L=()=>{if(j==="org")return h;switch(p){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},N=I.useCallback(()=>{g.resetShareState(),o()},[g,o]),S=(d==null?void 0:d.type)==="organization";return e.jsx(s.Dialog,{open:!0,onOpenChange:N,children:e.jsxs(s.DialogContent,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ye,{className:"h-5 w-5"}),' Share "',t==null?void 0:t.title,'"']})}),e.jsx(s.DialogDescription,{children:S?"Share this resource with org users or tenant users. As a super admin, you can share with all users.":"Share this resource with other users in your tenant."})]}),S?e.jsxs(s.Tabs,{value:j,onValueChange:w=>{const F=w;g.setSelectedTab(F),g.resetUserSelections()},className:"mb-4 min-h-0 flex-1",children:[e.jsxs(s.TabsList,{className:"mb-2 grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"org",children:"Org Users"}),e.jsx(s.TabsTrigger,{value:"tenant",children:"Tenant Users"})]}),e.jsx(s.TabsContent,{value:"org",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(pn,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:f,isSharing:n,isUpdating:l,isRemoving:r})})}),e.jsx(s.TabsContent,{value:"tenant",className:"min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(Vs,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:w=>m(w),isSharing:n,isUpdating:l,isRemoving:r})})})]}):e.jsx("div",{className:"mb-4 min-h-0 flex-1 overflow-hidden",children:e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx(Vs,{resource:t,resourceType:a,currentUser:d,onShareTabTypeChange:w=>m(w),isSharing:n,isUpdating:l,isRemoving:r})})}),e.jsx("div",{className:"mt-auto flex-shrink-0",children:S?j==="org"?e.jsx(_s,{resource:t,existingShares:x,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:h,currentAllUsersShare:k,onRemoveAccess:i}):e.jsx(_s,{resource:t,existingShares:b,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:L(),currentAllUsersShare:v,onRemoveAccess:i}):e.jsx(fn,{resource:t,isSharing:n,isRemoving:r,isUpdating:l,onShare:c,onClose:o,shareTabType:u,currentAllUsersShare:v,onRemoveAccess:i})})]})})}function pe(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function we(t,a,n){return{resourceType:t,resourceId:a,data:{shares:n}}}function gt(t,a,n){const{resourceType:r,resourceId:l,shareMutation:o,removeMutation:c,existingShares:i,resetUserSelections:d}=a;if(l)switch(t.context){case"org-tab":if(t.mode==="allOrgUsers"){const u=pe(r,l,[{scope:"org_users_only",role:t.orgWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificOrgUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const f=pe(r,l,u.map(g=>({scope:"specific_org_user",orgUserId:g.id,role:g.role})));o(f,{onSuccess:()=>{d()}})}if(m&&m.length>0){const f=we(r,l,m.map(g=>{var p,b;const j=(b=(p=i==null?void 0:i.shares)==null?void 0:p.specificOrgUsers)==null?void 0:b.find(x=>x.orgUserId===g);return{scope:"specific_org_user",orgUserId:g,role:(j==null?void 0:j.role)||"VIEWER"}}));c(f,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(f=>{const g=pe(r,l,[{scope:"specific_org_user",orgUserId:f.id,role:f.newRole}]);o(g,{onSuccess:()=>{d()}})})}break;case"tenant-tab":if(t.mode==="allTenants"){const u=pe(r,l,[{scope:"all_tenants_only",role:t.allTenantsRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="allTenantUsers"){const u=pe(r,l,[{scope:"all_tenant_users",tenantId:t.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h,tenantId:f}=t;if(m&&m.length>0){const g=we(r,l,m.map(j=>{var b,x;const p=(x=(b=i==null?void 0:i.shares)==null?void 0:b.specificTenantUsers)==null?void 0:x.find(v=>v.tenantUserId===j);return{scope:"specific_tenant_user",tenantUserId:j,tenantId:f,role:(p==null?void 0:p.role)||"VIEWER"}}));c(g,{onSuccess:()=>{d()}})}if(h&&h.length>0&&h.forEach(g=>{const j=pe(r,l,[{scope:"specific_tenant_user",tenantUserId:g.id,tenantId:f,role:g.newRole}]);o(j,{onSuccess:()=>{d()}})}),u&&u.length>0){const g=pe(r,l,u.map(j=>({scope:"specific_tenant_user",tenantUserId:j.id,tenantId:f,role:j.role})));o(g,{onSuccess:()=>{d()}})}}break;case"tenant-dialog":if(t.mode==="allTenantUsers")if(t.removeAccess){const u=we(r,l,[{scope:"all_tenant_users",role:"VIEWER"}]);c(u,{onSuccess:()=>{d()}})}else if(t.updateAccess){const u=pe(r,l,[{scope:"all_tenant_users",tenantId:n==null?void 0:n.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else{const u=pe(r,l,[{scope:"all_tenant_users",tenantId:n==null?void 0:n.tenantId,role:t.tenantWideRole}]);o(u,{onSuccess:()=>{d()}})}else if(t.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:m,usersToUpdate:h}=t;if(u&&u.length>0){const f=pe(r,l,u.map(g=>({scope:"specific_tenant_user",tenantUserId:g.id,role:g.role})));o(f,{onSuccess:()=>{d()}})}if(m&&m.length>0){const f=we(r,l,m.map(g=>{var p,b;const j=(b=(p=i==null?void 0:i.shares)==null?void 0:p.specificTenantUsers)==null?void 0:b.find(x=>x.tenantUserId===g);return{scope:"specific_tenant_user",tenantUserId:g,role:(j==null?void 0:j.role)||"VIEWER"}}));c(f,{onSuccess:()=>{d()}})}h&&h.length>0&&h.forEach(f=>{const g=pe(r,l,[{scope:"specific_tenant_user",tenantUserId:f.id,role:f.newRole}]);o(g,{onSuccess:()=>{d()}})})}break}}function jt(t,a,n,r){var u,m,h,f,g,j;const{resourceType:l,resourceId:o,removeMutation:c,existingShares:i,resetUserSelections:d}=r;if(o)if(t.length>0){const p=we(l,o,t.map(b=>{var v,k;const x=(k=(v=i==null?void 0:i.shares)==null?void 0:v.specificTenantUsers)==null?void 0:k.find(L=>L.tenantUserId===b);return{scope:"specific_tenant_user",tenantUserId:b,role:(x==null?void 0:x.role)||"VIEWER"}}));c(p,{onSuccess:()=>{d()},onError:b=>{console.error("Remove access failed:",b)}})}else{const p=a==="tenant"&&n==="allTenants",b=a==="tenant"&&n==="allTenantUsers";if(p){const x=(m=(u=i==null?void 0:i.shares)==null?void 0:u.allTenantsOnly)==null?void 0:m[0];if(x){const v=we(l,o,[{scope:"all_tenants_only",role:x.role}]);c(v,{onSuccess:()=>{d()},onError:k=>{console.error("Remove all-tenants access failed:",k)}})}}else if(b){const x=(f=(h=i==null?void 0:i.shares)==null?void 0:h.tenantWide)==null?void 0:f[0];if(x){const v=we(l,o,[{scope:"all_tenant_users",role:x.role}]);c(v,{onSuccess:()=>{d()},onError:k=>{console.error("Remove all-tenant-users access failed:",k)}})}}else{const x=(j=(g=i==null?void 0:i.shares)==null?void 0:g.orgUsersOnly)==null?void 0:j[0];if(x){const v=we(l,o,[{scope:"org_users_only",role:x.role}]);c(v,{onSuccess:()=>{d()},onError:k=>{console.error("Remove org-wide access failed:",k)}})}}}}function gn(t,a,n){const r=s.useShareManagementActions(),l=s.useShareUsersToRemove(),o=s.useShareSelectedTab(),c=s.useShareCurrentMode(),{currentUser:i}=s.useCurrentUserInfo(),{existingShares:d}=De({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),u=I.useCallback(()=>{r.resetUserSelections()},[r]),m=I.useCallback(f=>{if(!t)return;const g={resourceType:s.ResourceType.DASHBOARD,resourceId:t,shareMutation:a,removeMutation:n,existingShares:d,resetUserSelections:u};gt(f,g,i)},[t,a,n,d,u,i]),h=I.useCallback(()=>{if(!t)return;const f={resourceType:s.ResourceType.DASHBOARD,resourceId:t,removeMutation:n,existingShares:d,resetUserSelections:u};jt(l,o||"",c||"",f)},[t,a,n,d,u,l,o,c]);return{handleShareSubmit:m,handleRemoveAccess:h}}function jn(t,a,n){const{currentUser:r}=s.useCurrentUserInfo(),l=s.useShareManagementActions(),o=s.useShareUsersToRemove(),c=s.useShareSelectedTab(),i=s.useShareCurrentMode(),{existingShares:d}=De({debouncedSearchQuery:"",resourceId:t||"",resourceType:s.ResourceType.VISUAL,userType:"tenant"}),u=I.useCallback(()=>{l.resetUserSelections()},[l]),m=I.useCallback(f=>{if(!t)return;const g={resourceType:s.ResourceType.VISUAL,resourceId:t,shareMutation:a,removeMutation:n,existingShares:d,resetUserSelections:u};gt(f,g,r)},[t,a,n,d,u,r]),h=I.useCallback(()=>{if(!t)return;const f={resourceType:s.ResourceType.VISUAL,resourceId:t,removeMutation:n,existingShares:d,resetUserSelections:u};jt(o,c||"",i||"",f)},[t,a,n,d,u,o,c,i]);return{handleShareSubmit:m,handleRemoveAccess:h}}function bn(t){const a=t.toUpperCase().indexOf("WHERE"),n=t.toUpperCase().indexOf("GROUP BY"),r=t.toUpperCase().indexOf("LIMIT"),l=t.toUpperCase().indexOf("ORDER BY");let o=t.length;if(l!==-1&&(o=l),r!==-1&&r<o&&(o=r),a!==-1){const c=t.substring(0,a),i=t.substring(a);return`${c} {{ filters | where }} AND ${i.substring(6)}`}else if(n!==-1){const c=t.substring(0,n),i=t.substring(n);return`${c} {{ filters | where }} ${i}`}else{const c=t.substring(0,o),i=t.substring(o);return console.log("beforeClause",c),console.log("afterClause",i),i?`${c} {{ filters | where }} ${i}`:`${c.replace(/;$/,"")} {{ filters | where }}`}}function Ns(t){const[a,n]=I.useState(null),[r,l]=I.useState(null);return I.useEffect(()=>{if(!t||t.trim()===""){n(null),l(null);return}(async()=>{try{if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid URL format: ${t}`);try{new URL(t)}catch{throw new Error(`Invalid URL: ${t}`)}const i=`${t.endsWith("/")?t:`${t}/`}index.js`;try{if(!(await fetch(i,{method:"HEAD"})).ok)throw new Error(`Module not found at ${i}`)}catch{}const d=await import(i);if(typeof d.useChartStore!="function")throw new Error("useChartStore is not a function");n(()=>d.useChartStore),l(null)}catch(c){const i=c instanceof Error?c.message:"Unknown error";console.error("Failed to load remote chart store:",i),l(i),n(null)}})()},[t]),a}function yn(t,a){if(t.length===0)return"";if(a){const n=t.find(r=>r.id===a);if(n){const r=n.tabTitle;if(r=="All__Header")return t[0].id;if(r&&r.endsWith("__Header")){const o=r.split("__")[0],c=t.find(i=>i.tabTitle===o);return c?c.id:t[0].id}return a}}return t[0].id}async function Us(t,a,n){if(!t||!a)throw new Error("Missing auth token or visual ID");const r=["resource-by-id","visual",a],l=n.getQueryData(r);if(l)return console.log("Using cached visual data for:",a),{data:l,fromCache:!0};console.log("Fetching visual data from network for:",a);const o=s.ue.loading("Loading visual...",{position:"top-center"});try{const c=await fetch(`https://semaphor.cloud/api/management/v1/visuals/${a}`,{headers:{Authorization:`Bearer ${t}`}});if(!c.ok)throw new Error("Failed to load visual");const i=await c.json();return n.setQueryData(r,i),s.ue.dismiss(o),{data:i,fromCache:!1}}catch(c){throw s.ue.dismiss(o),c}}function vn(t,a,n,r,l){const o=t.frameObject;a(o);const c=o.cards.find(i=>i.id===o.activeCardId);c&&n(c),r(!0),l(!0)}function Nn(){var f;const{setCardSql:t}=s.useEditorActions(),a=s.useEditorStore(g=>g.frame),n=s.useEditorStore(g=>g.card),r=Ns(((f=n.customCardPreferences)==null?void 0:f.url)||""),l=s.useEditorStore(g=>g.selectedSchemaName),o=s.useEditorStore(g=>g.selectedDatamodelId),c=s.useEditorStore(g=>g.selectedDatabaseName),i=s.useEditorStore(g=>g.selectedTableName),d=s.useEditorStore(g=>g.selectedConnectionId),u=s.useEditorStore(g=>g.isShowingVisual),m=n.sql;return{getUpdatedFrame:I.useCallback(()=>{var x;let g=m;m&&!m.includes("{{")&&(g=bn(m),t(g));const j=(x=r==null?void 0:r.getState())==null?void 0:x.settings,p={...n,dataSource:n.dataSource||{mode:"directSource"},lastSelectedSchema:l,lastSelectedDatamodelId:o,lastSelectedDatabase:c,lastSelectedTable:i,connectionId:d,sql:g,customCfg:u?n.customCfg:null,preferences:n.preferences,...j&&{customCardPreferences:{...n.customCardPreferences,settings:j}}},b=a.cards.map(v=>v.id===n.id?p:v);return{...a,cards:b,activeCardId:yn(b,a.activeCardId)}},[n,a,u,l,o,c,i,d,t,r,m])}}function Cs(){const{authToken:t}=s.useSemaphorContext(),a=s.useQueryClient(),n=s.useSelectedVisual(),{selectVisual:r}=s.useManagementActions(),{setFrame:l,setCard:o}=s.useEditorActions(),{setIsDashboardEditing:c,setIsVisualEditing:i,setSelectedFrameId:d,addFrame:u,setIsDashboardPanelOpen:m}=s.useDashboardActions(),h=s.useDashboardStore(p=>p.selectedSheetId),f=s.useVisualById((n==null?void 0:n.id)||"",{enabled:!!(n!=null&&n.id)&&!!(t!=null&&t.accessToken)}),g=I.useCallback(async p=>{try{r(p);const{data:b,fromCache:x}=await Us((t==null?void 0:t.accessToken)||"",p.id,a);return vn(b,l,o,c,i),{success:!0,fromCache:x}}catch(b){return console.error("Error editing visual:",b),{success:!1,error:"Failed to load visual for editing"}}},[t==null?void 0:t.accessToken,a,r,l,o,c,i]),j=I.useCallback(async p=>{try{if(r(p),!h)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:b,fromCache:x}=await Us((t==null?void 0:t.accessToken)||"",p.id,a),v=b.frameObject;if(!v)return{success:!1,error:"Visual has no frame data"};const k={...v,id:s.v4()};return u(h,k,"end"),c(!0),d(k.id),m(!1),{success:!0,fromCache:x}}catch(b){return console.error("Error adding visual:",b),{success:!1,error:"Failed to add visual to dashboard"}}},[t==null?void 0:t.accessToken,a,r,h,u,c,d,m]);return{visual:f.data,isLoading:f.isLoading,isError:f.isError,error:f.error,handleEditLibraryVisual:g,handleAddLibraryVisual:j,getUpdatedFrame:Nn().getUpdatedFrame,refetch:f.refetch}}function Cn(){const[t,a]=I.useState(""),[n,r]=I.useState(!1),[l,o]=I.useState(""),[c,i]=I.useState(""),[d,u]=I.useState(!1),[m,h]=I.useState(null),[f,g]=I.useState(!1),[j,p]=I.useState(null),[b,x]=I.useState(null),{setIsDashboardEditing:v,setIsVisualEditing:k}=s.useDashboardActions(),{handleEditLibraryVisual:L,handleAddLibraryVisual:N}=Cs(),{resources:S,isLoading:y,isError:D,createResource:C,updateResource:B,deleteResource:w,duplicateResource:F,shareResource:T,isCreating:E,isDeleting:A,removeResourceShares:R,isSharing:M,isRemovingShares:O,isUpdatingShares:P}=s.useVisualManagement(()=>{g(!1),p(null)},()=>{r(!1),o(""),i("")}),{handleShareSubmit:K,handleRemoveAccess:Y}=jn((m==null?void 0:m.id)||null,T,R);s.useCurrentUserInfo();const te=S.filter(W=>{var re,ie;return((re=W==null?void 0:W.title)==null?void 0:re.toLowerCase().includes(t.toLowerCase()))||((ie=W==null?void 0:W.description)==null?void 0:ie.toLowerCase().includes(t.toLowerCase()))}),X=W=>new Date(W).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),$=()=>{l.trim()&&C({title:l,description:c,isPrivate:!1})},H=W=>{p(W),g(!0)},_=()=>{j&&w(j.id)},{startUpdating:J,stopUpdating:z,isUpdating:U}=s.useResourceUpdateState(),Z=(W,re)=>{const ie=re.title!==void 0?"title":"description";J(W,ie),B({resourceId:W,data:re},{onSuccess:()=>{z(W,ie)},onError:()=>{z(W,ie)}})},le=W=>{x(W),F(W,{onSettled:()=>x(null)})},V=W=>{L(W)},se=W=>{N(W)},ne=W=>{const re=S.find(ie=>ie.id===W);re&&B({resourceId:W,data:{isPrivate:!re.isPrivate}})},q=W=>{h(W),u(!0)};return s.useShareUsersToRemove(),s.useShareManagementActions(),De({debouncedSearchQuery:"",resourceId:(m==null?void 0:m.id)||"",resourceType:s.ResourceType.VISUAL,userType:"tenant"}),y?e.jsx(rt,{}):D?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[e.jsx("div",{className:"px-1",children:n?e.jsxs(s.Card,{className:"border-dashed p-4 pb-2",children:[e.jsx(s.CardHeader,{className:"px-0 pb-3 pt-0",children:e.jsx(s.CardTitle,{className:"text-sm",children:"New Visual"})}),e.jsxs(s.CardContent,{className:"space-y-3 px-0 pb-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",className:"text-xs",children:"Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:W=>o(W.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:W=>i(W.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:$,size:"sm",className:"h-7 text-xs",disabled:!l.trim()||E,children:E?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{r(!1),o(""),i("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:E,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>r(!0),className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",disabled:E,children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),E?"Creating...":"Create New Visual"]})}),S&&S.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:W=>a(W.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:te.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"mb-3",children:e.jsx(ns,{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"]})]}):te.map(W=>e.jsx(sn,{visual:W,onAddVisual:se,onEditVisual:V,onUpdateVisual:Z,onDeleteClick:H,onDuplicateVisual:le,onTogglePrivacy:ne,onShareVisual:q,isDeleting:A,isDuplicating:b===W.id,isTitleUpdating:U(W.id,"title"),isDescriptionUpdating:U(W.id,"description"),formatDate:X},W.id))})}),d&&m&&e.jsx(ft,{resource:m,resourceType:s.ResourceType.VISUAL,onShare:K,isSharing:M,isRemoving:O,isUpdating:P,onClose:()=>{u(!1),h(null)},onRemoveAccess:Y}),e.jsx(s.AlertDialog,{open:f,onOpenChange:W=>{!W&&A||(g(W),W||p(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:A,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:W=>{W.preventDefault(),W.stopPropagation(),_()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:A,children:A?"Deleting...":"Delete"})]})]})})]})}function Sn({dashboard:t,isDeleting:a,isDuplicating:n,isTitleUpdating:r=!1,isDescriptionUpdating:l=!1,onLoadDashboard:o,onUpdateDashboard:c,onDeleteClick:i,onDuplicateDashboard:d,onShareDashboard:u,formatDate:m,onDashboardItemClick:h}){var S,y,D;const{selectDashboard:f}=s.useManagementActions(),g=s.useIsDashboardSelected(t.id),{isConsoleMode:j}=s.useDashboardPreferences(),[p,b]=I.useState(!1),[x,v]=I.useState(!1),k=s.useDashboardStore(C=>C.actions.setIsDashboardPanelOpen);I.useEffect(()=>{n?(b(!0),v(!0)):x&&(b(!1),v(!1))},[n,x]);const L=()=>e.jsx(s.ChartColumn,{className:"h-4 w-4"}),N=()=>{f(t),o(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:N,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:L()}),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:C=>c==null?void 0:c(t.id,{title:C}),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:C=>c==null?void 0:c(t.id,{description:C}),isEditable:t.permissions.canEdit&&g,isPending:l,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:C=>C.stopPropagation(),children:e.jsxs(s.DropdownMenu,{modal:!1,open:p,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:C=>{C.preventDefault(),C.stopPropagation(),d(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsx(e.Fragment,{children:e.jsxs(s.DropdownMenuItem,{onClick:C=>{C.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:C=>{C.stopPropagation(),i(t),k(!1)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((S=t.ownership.createdBy)==null?void 0:S.type)==="tenant"||((y=t.ownership.createdBy)==null?void 0:y.type)==="organization"&&j)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Be,{className:"h-3 w-3"}),e.jsx("span",{children:((D=t.ownership.createdBy)==null?void 0:D.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 wn({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 Dn(t){const[a,n]=I.useState(""),[r,l]=I.useState(!1),[o,c]=I.useState(""),[i,d]=I.useState(""),[u,m]=I.useState(!1),[h,f]=I.useState(null),[g,j]=I.useState(!1),[p,b]=I.useState(null),[x,v]=I.useState(null),k=s.useManagementStore(Q=>Q.lastSelectedDashboard),L=s.useManagementStore(Q=>Q.selectedDashboard),N=s.useManagementStore(Q=>Q.actions.selectDashboard),S=s.useManagementStore(Q=>Q.actions.clearSelectedDashboard);s.useShareManagementActions(),s.useShareUsersToRemove(),s.useShareSelectedTab(),s.useShareCurrentMode();const{tokenProps:y,id:D}=s.useSemaphorContext(),{permissions:C}=s.useRoleAwareDisplayPreferences(),{resources:B,isLoading:w,isError:F,createResource:T,updateResource:E,deleteResource:A,duplicateResource:R,isCreating:M,isDeleting:O,isSharing:P,isRemovingShares:K,isUpdatingShares:Y,shareResource:te,removeResourceShares:X}=s.useDashboardManagement(()=>{j(!1);const Q=p==null?void 0:p.id;b(null),(L==null?void 0:L.id)===Q&&(!(y!=null&&y.dashboard_id)&&!D?S():k&&k.id!==Q&&N(k))},()=>{l(!1),c(""),d("")}),{handleShareSubmit:$,handleRemoveAccess:H}=gn((h==null?void 0:h.id)||null,te,X),{currentUser:_}=s.useCurrentUserInfo(),J=B.filter(Q=>{var oe,ee;return((oe=Q==null?void 0:Q.title)==null?void 0:oe.toLowerCase().includes(a.toLowerCase()))||((ee=Q==null?void 0:Q.description)==null?void 0:ee.toLowerCase().includes(a.toLowerCase()))}),z=Q=>new Date(Q).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),U=()=>{o.trim()&&T({title:o,description:i,isPrivate:!1})},Z=Q=>{var oe;(oe=t.onLoadDashboard)==null||oe.call(t,Q)},le=Q=>{b(Q),j(!0)},V=()=>{p&&A(p.id)},se=Q=>{v(Q),R(Q,{onSettled:()=>v(null)})},{startUpdating:ne,stopUpdating:q,isUpdating:W}=s.useResourceUpdateState(),re=(Q,oe)=>{const ee=oe.title!==void 0?"title":"description";ne(Q,ee),E({resourceId:Q,data:oe},{onSuccess:()=>{q(Q,ee)},onError:()=>{q(Q,ee)}})},ie=Q=>{const oe=B.find(ee=>ee.id===Q);oe&&E({resourceId:Q,data:{isPrivate:!oe.isPrivate}})},he=Q=>{f(Q),_==null||_.type,m(!0)};return De({debouncedSearchQuery:"",resourceId:(h==null?void 0:h.id)||"",resourceType:s.ResourceType.DASHBOARD,userType:"tenant"}),w?e.jsx(rt,{}):F?e.jsx(wn,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"mt-1 flex h-full flex-1 flex-col gap-3 px-4",children:[C.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:o,onChange:Q=>c(Q.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:Q=>d(Q.target.value),className:"h-7 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(s.Button,{onClick:U,size:"sm",className:"h-7 text-xs",disabled:!o.trim()||M,children:M?"Creating...":"Create"}),e.jsx(s.Button,{onClick:()=>{l(!1),c(""),d("")},variant:"outline",size:"sm",className:"h-7 text-xs",disabled:M,children:"Cancel"})]})]})]}):e.jsxs(s.Button,{onClick:()=>l(!0),className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",disabled:M,children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),M?"Creating...":"Create New Dashboard"]})}),B&&B.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:a,onChange:Q=>n(Q.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:J.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:a?"No dashboards found":"No dashboards yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:a?"Try adjusting your search":C.canCreateDashboards?"Create your first dashboard to get started":"No dashboards have been shared with you yet"}),C.canCreateDashboards&&!a&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>l(!0),children:[e.jsx(s.Plus,{className:"h-4 w-4 mr-2"}),"Create Dashboard"]})]}):J.map(Q=>e.jsx(Sn,{dashboard:Q,isDeleting:O,isDuplicating:x===Q.id,isTitleUpdating:W(Q.id,"title"),isDescriptionUpdating:W(Q.id,"description"),onLoadDashboard:Z,onEditDashboard:t.onEditDashboard,onUpdateDashboard:re,onDeleteClick:le,onDuplicateDashboard:se,onTogglePrivacy:ie,onShareDashboard:he,formatDate:z,onDashboardItemClick:t.onDashboardItemClick},Q.id))})}),u&&h&&e.jsx(ft,{resource:h,resourceType:s.ResourceType.DASHBOARD,onShare:$,isSharing:P,isRemoving:K,isUpdating:Y,onClose:()=>{m(!1),f(null)},onRemoveAccess:H}),e.jsx(s.AlertDialog,{open:g,onOpenChange:Q=>{!Q&&O||(j(Q),Q||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 "',p==null?void 0:p.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:O,children:"Cancel"}),e.jsx(s.AlertDialogAction,{onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),V()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:O,children:O?"Deleting...":"Delete"})]})]})})]})}function bt({isOpen:t,onClose:a,className:n,onDashboardItemClick:r}){s.useDashboardStore(b=>b.dashboard);const{setDashboard:l,addSheet:o}=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),f=d.canAccessVisuals?m:"dashboards",g=dt(a,{enabled:t}),j=b=>{},p=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",n),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:a,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:f,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(Dn,{onLoadDashboard:j,onEditDashboard:p,onDashboardItemClick:r})}),d.canAccessVisuals&&e.jsx(s.TabsContent,{value:"visuals",className:"flex-1 mt-4",children:e.jsx(Cn,{})})]})})]})})}function kn(){var se,ne;const{authToken:t,tokenProps:a,id:n}=s.useSemaphorContext(),{isLocalDev:r}=s.useDashboardPreferences(),{permissions:l}=s.useRoleAwareDisplayPreferences(),o=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),f=s.useEditorStore(q=>q.selectedConnectionId),[g,j]=I.useState(!1),p=s.useDashboardStore(q=>q.isDashboardPanelOpen),b=s.useDashboardStore(q=>q.actions.setIsDashboardPanelOpen),x=s.useDashboardStore(q=>q.filterValues),v=s.useDashboardStore(q=>q.isVisualEditing),k=s.useManagementStore(q=>q.selectedDashboard),L=s.useManagementStore(q=>q.initialDashboard),N=k?(ne=k==null?void 0:k.permissions)==null?void 0:ne.canEdit:(se=L==null?void 0:L.permissions)==null?void 0:se.canEdit,S=s.useDashboardStore(q=>q.showFilters),y=s.useDashboardStore(q=>q.showDashboardJSON),D=s.useDashboardStore(q=>q.onSaveFunction),C=s.useDashboardStore(q=>q.actions.setShowFilters),{addFrame:B,setSelectedFrameId:w}=s.useDashboardStore(q=>q.actions),{getSelectedSheet:F,setIsDashboardEditing:T,setShowDashboardJSON:E}=s.useDashboardStore(q=>q.actions),A=F(),{setInitialDashboard:R,clearSelectedDashboard:M}=s.useManagementStore(q=>q.actions),{resources:O}=s.useResourceManagement(s.ResourceType.DASHBOARD);I.useEffect(()=>{if(O&&O.length>0){const q=u==null?void 0:u.id;if(q){const W=O.find(re=>re.id===q);W&&R(W)}}},[O,u==null?void 0:u.id,R]);const P=a.orgUserId||a.tenantId,K=m&&!v&&P&&N;function Y(){var ie,he;const q=h.dataSource;if(q)return q;const W=(he=(ie=u.aiContext)==null?void 0:ie.selectedEntities)==null?void 0:he[0],re=W==null?void 0:W.type;if(W)return{connectionId:W.connectionId,connectionType:W.connectionType,type:re,selectedEntities:[W]}}const te=()=>{if(!m||!A)return;const W={dataSource:Y(),mode:"explorer",connectionId:f,id:s.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},re={id:s.v4(),cards:[W],activeCardId:W.id};B(A.id,re),w(re.id)},X=()=>{T(!0)},[$,H]=I.useState(!1),_=s.useUpdateResource(s.ResourceType.DASHBOARD);async function J(){const q=es(u);H(!0);const W={template:q};_.mutate({resourceId:q.id,data:W},{onSuccess:()=>{H(!1),s.ue.success("Dashboard saved!")},onError:()=>{H(!1),s.ue.error("Failed to save dashboard")}})}async function z(){if(j(!0),!i||!d)return;const q=es(u),W=JSON.stringify(q),re={...d,template:W,filterValues:x};await js(re,t==null?void 0:t.accessToken),s.ue.success("Lens saved"),D==null||D(q),j(!1)}if(v)return null;const U=(d==null?void 0:d.name)||u.title,le=O&&O.length>0&&(a.orgUserId||a.tenantId&&a.endUserId&&a.endUserEmail),V=k&&!(a!=null&&a.dashboard_id)&&!n;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:[le&&e.jsxs(e.Fragment,{children:[V&&e.jsx(s.IconButton,{"aria-label":"Dashboard Hub",tooltip:"Back to Dashboard Hub",onClick:()=>M(),className:"h-7 p-2",children:e.jsx(s.House,{className:"h-4 w-4"})}),e.jsx(s.IconButton,{"aria-label":"Manage Dashboards",tooltip:o?"Manage Dashboards":"Select a dashboard to continue",onClick:()=>b(!0),className:"h-7 p-2",buttonProps:{disabled:!o},children:e.jsx(Ea,{className:"h-4 w-4"})})]}),!v&&o&&e.jsx(s.Label,{children:U})]}),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(Va,{className:"h-4 w-4"})}),!v&&o&&e.jsx(en,{}),!v&&o&&e.jsx(nt,{}),m&&!v&&P&&r&&o&&e.jsx(Xa,{}),!v&&P&&r&&o&&e.jsx(Za,{}),m&&!v&&P&&d&&r&&o&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"secondary",disabled:g,onClick:z,size:"sm",children:[e.jsx(gs,{className:"mr-2 h-4 w-4"}),"Save Lens"]}),m&&!v&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",size:"sm",disabled:!m,onClick:te,children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!v&&!m&&l.canEdit&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:X,size:"sm",children:[e.jsx(s.Pencil,{className:"mr-2 h-4 w-4"}),"Edit"]}),m&&!v&&o&&e.jsxs(s.Button,{variant:"outline",className:"h-7 p-2",onClick:()=>{T(!1),E(!1)},children:[e.jsx(s.Cross2Icon,{className:"mr-2 h-4 w-4"}),"Close"]}),K&&o&&e.jsxs(s.Button,{className:"h-7 p-2",variant:"outline",disabled:$,onClick:J,size:"sm",children:[$?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(gs,{className:"mr-2 h-4 w-4"}),$?"Saving...":"Save"]}),!S&&!v&&m&&l.canUseFilters&&o&&e.jsx(s.Button,{className:"h-7 p-2",variant:"outline",onClick:()=>C(!0),size:"sm",children:e.jsx(s.Filter,{className:"h-4 w-4"})}),!v&&m&&r&&o&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(s.Button,{className:"h-7 p-2",onClick:()=>E(!y),size:"sm",variant:"ghost",children:e.jsx(Oe,{className:"h-4 w-4"})})}),!v&&r&&e.jsx(Wa,{}),!v&&e.jsx(bt,{isOpen:p,onClose:()=>b(!1)})]})]})}function Tn({name:t,items:a,value:n,onChange:r,isLoading:l,isError:o,refetch:c,className:i,icon:d,showNone:u=!1}){const m=ke.useRef(null),[h,f]=ke.useState(!1),[g,j]=ke.useState("100%"),p=u?[...a||[],{id:"none",name:"None"}]:a;ke.useLayoutEffect(()=>{m.current&&j(m.current.offsetWidth)},[]);function b(){var v;return l?"Loading...":o?"Error":n?(v=a==null?void 0:a.find(k=>k.id===n))==null?void 0:v.name:`Select ${t}`}function x(v,k){r(k),f(!1)}return e.jsxs(s.Popover,{open:h,onOpenChange:f,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{ref:m,variant:"outline",role:"combobox","aria-expanded":h,className:s.cn("flex h-9 w-full justify-between",i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d&&e.jsx("div",{className:"mr-2",children:d}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children: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(et,{className:s.cn("size-3.5 opacity-50",l&&"animate-spin")})})]}),e.jsxs(s.CommandList,{children:[e.jsxs(s.CommandEmpty,{children:["No ",t==null?void 0:t.toLowerCase()," found."]}),e.jsx(s.CommandGroup,{children:p==null?void 0:p.map(v=>e.jsx(s.CommandItem,{className:"overflow-x-auto",value:v.name,onSelect:k=>x(k,v.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Check,{className:s.cn("size-4",n===v.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:v.name,children:v.name})]})},v.id))})]})]})})]})}function Re({title:t,items:a,value:n,isLoading:r,isError:l,refetch:o,onChange:c,showNone:i=!1,className:d,disabled:u=!1,type:m="combobox"}){const h=r?"Loading...":l?"Error":n;function f(){if(t==="Connection")return e.jsx(Fa,{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...":l?"Error":`Select ${t}`})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[r?e.jsx(s.SelectLabel,{children:"Loading..."}):e.jsxs(s.SelectLabel,{className:"flex items-center justify-between gap-2",children:[t,e.jsx(et,{className:s.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:o})]}),e.jsxs(e.Fragment,{children:[i&&e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),a&&a.map((p,b)=>e.jsx(s.SelectItem,{value:p.id,children:p.name},b))]}),(r||l)&&e.jsx(s.SelectItem,{value:h,children:h})]})})]})}function j(){return e.jsx(Tn,{icon:f(),items:a,value:h,onChange:c||(()=>{}),isLoading:r,isError:l,refetch:o,name:t,showNone:i})}return e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:m==="select"?g():j()})})}function En({column:t}){const[a,n]=I.useState(!1),r=s.useEditorStore(p=>p.selectedTableName),l=s.useEditorStore(p=>p.selectedSchemaName),o=s.useEditorStore(p=>p.selectedDatabaseName),c=s.useEditorStore(p=>p.selectedDatamodelId),i=s.useEditorStore(p=>p.sqlGen),{modelItems:d,connectionType:u}=s.useEditorAside(),m=s.useEditorStore(p=>p.actions.setSqlGen),h=s.useEditorStore(p=>p.actions.setCardSql),f=s.useEditorStore(p=>p.actions.setRunSql);function g(p,b){var L;const x=s.createSqlGenConfig(p,i,b),v=(L=d==null?void 0:d.find(N=>N.id===c))==null?void 0:L.name;m(x);const k=s.getSql(x,s.fmt(l||""),s.fmt(r),v||"",u,o||"");k&&(h(k),f(!0)),n(!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:a,onOpenChange:n,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(s.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:j()})]})}function In({dataType:t}){const a=s.getDataType(t);return a==="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(fe,{className:"h-3 w-3"})}):a==="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(Ne,{className:"h-3 w-3"})}):a==="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"})}):a==="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(Me,{className:"h-3 w-3"})}):a==="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(Oe,{className:"h-3 w-3"})}):a==="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"})}):a==="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($e,{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(fe,{className:"h-3 w-3"})})}function is({column:t,className:a}){return e.jsxs("div",{className:s.cn("flex min-h-8 grow items-center gap-2 px-3 py-[6px] text-sm",a),children:[e.jsx(In,{dataType:t.data_type}),e.jsx("span",{children:t.column_name})]})}function An({id:t,children:a,type:n="column"}){const{attributes:r,listeners:l,setNodeRef:o,transform:c}=s.useDraggable({id:t,data:{type:n}}),i=c?{translate:s.CSS.Translate.toString(c),transform:s.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:o,style:i,...l,...r,children:a})}function Mn({onClick:t,column:a}){const n=s.useDndStore(m=>m.activeId),r=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.groupByColumns}),l=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.metricColumns}),o=s.useEditorStore(m=>{var h;return(h=m.card.queryConfig)==null?void 0:h.filterColumns});function c(m){return i(m)||d(m)||u(m)}function i(m){return r==null?void 0:r.some(h=>h.name===m.column_name)}function d(m){return l==null?void 0:l.some(h=>h.name===m.column_name)}function u(m){return o==null?void 0:o.some(h=>h.name===m.column_name)}return e.jsxs("div",{onClick:()=>t(a),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(a)}),children:[n===a.column_name&&e.jsx(s.DragOverlay,{children:e.jsx(is,{column:a,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),n===a.column_name&&e.jsx("div",{className:"absolute inset-0",children:n===a.column_name&&e.jsx(is,{column:a})}),e.jsx(An,{id:a.column_name,type:"column",children:e.jsx(is,{column:a})})]})}const cs={id:"__placeholder__",role:"groupby",type:"string"},ds={id:"__placeholder__",role:"groupby",type:"string"},us={id:"__placeholder__",role:"metric",type:"number"},ms={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},yt={id:"__placeholder__"},Ee="droppable-group-by",Ie="droppable-metrics",Ae="droppable-pivot-by",ts="sortable-group-by",bs="sortable-metrics",as="sortable-pivot-by",ys="droppable-filters",vs="sortable-filters",Ss="sortable-order-by";function Ln(){const t=s.useDndStore(E=>E.insertIndex),a=s.useEditorStore(E=>{var A;return((A=E.card.queryConfig)==null?void 0:A.groupByColumns)||[]}),n=s.useEditorStore(E=>{var A;return((A=E.card.queryConfig)==null?void 0:A.metricColumns)||[]}),r=s.useEditorStore(E=>{var A;return((A=E.card.queryConfig)==null?void 0:A.filterColumns)||[]}),l=s.useEditorStore(E=>{var A;return((A=E.card.queryConfig)==null?void 0:A.orderBy)||[]}),o=s.useEditorStore(E=>{var A;return((A=E.card.queryConfig)==null?void 0:A.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:i,setPreviewGroupByColumns:d,setPreviewMetricColumns:u,setPreviewFilterColumns:m,setPreviewPivotColumns:h}=s.useDndActions(),{setGroupByColumns:f,setMetricColumns:g,setFilterColumns:j,setOrderByColumns:p,setPivotByColumns:b}=s.useEditorActions(),{columns:x}=s.useDataColumns(),{formattedTableName:v}=s.useEditorAside(),k=s.useSensors(s.useSensor(s.MouseSensor,{activationConstraint:{distance:1}})),L=E=>{var M;const{active:A,over:R}=E;if(((M=A.data.current)==null?void 0:M.type)==="column"&&R){const O=R.id,P=x.find(X=>X.column_name===A.id);if(!P)return;const K=s.isNumberDataType(P.data_type),Y=s.isTextDataType(P.data_type),te=s.isDateDataType(P.data_type);if(Y||te){if(a.some($=>$.id===O)){const $=a.findIndex(_=>_.id===O);c($);const H=a.filter(_=>_.id!==cs.id);H.splice($,0,cs),d(H)}else if(R.id===Ee){c(a.length);const $=[...a,cs];d($),u(n),m(r)}}if(Y||te){if(o.some($=>$.id===O)){const $=o.findIndex(_=>_.id===O);c($);const H=o.filter(_=>_.id!==ds.id);H.splice($,0,ds),h(H)}else if(R.id===Ae){c(o.length);const $=[...o,ds];h($),d(a),u(n),m(r)}}if(K||Y){if(n.some($=>$.id===O)){console.log("isOverMetricSortable",O);const $=n.findIndex(_=>_.id===O);c($);const H=n.filter(_=>_.id!==us.id);H.splice($,0,us),u(H)}else if(R.id===Ie){c(n.length);const $=[...n,us];u($),m(r),d(a),h(o)}}if(S(P)){if(r.some($=>$.id===O)){const $=r.findIndex(_=>_.id===O);c($);const H=r.filter(_=>_.id!==ms.id);H.splice($,0,ms),m(H)}else if(R.id===ys){c(r.length);const $=[...r,ms];m($),u(n),d(a),h(o)}}}else d(a),u(n),m(r),h(o)};function N(E){i(E.active.id),c(null),d(a),u(n),m(r),h(o)}function S(E){return!r.some(A=>A.name===E.column_name)}function y(E,A="SUM"){const{column_name:R,data_type:M}=E,O=[...n],P=t!==null?t:n.length,K={...E,id:be(R),name:R,label:qe(R,A),type:M,role:"metric",aggregate:A};O.splice(P,0,K),g(O)}function D(E){const A=s.isTextDataType(E.data_type);s.isDateDataType(E.data_type);const R=[...o],M=t!==null?t:o.length;let O;A?O={...E,id:be(E.column_name),name:E.column_name,type:E.data_type,role:"groupby"}:O={...E,id:be(E.column_name),name:E.column_name,type:E.data_type,role:"groupby",label:Fe(E.column_name,"month"),granularity:"month"},R.splice(M,0,O),b(R)}function C(E){const A=s.isTextDataType(E.data_type);s.isDateDataType(E.data_type);const R=[...a],M=t!==null?t:a.length;let O;A?O={...E,id:be(E.column_name),name:E.column_name,type:E.data_type,role:"groupby"}:O={...E,id:be(E.column_name),name:E.column_name,type:E.data_type,role:"groupby",label:Fe(E.column_name,"month"),granularity:"month"},R.splice(M,0,O),f(R)}function B(E){const A=[...r],R=t!==null?t:r.length,M={...E,id:be(E.column_name),name:E.column_name,type:E.data_type,sql:s.getDefaultFilterSql(E.data_type,v,s.fmt(E.column_name)),role:"filter"};A.splice(R,0,M),j(A)}function w(E){var O,P,K,Y,te,X,$,H;const{active:A,over:R}=E,M=A.data.current;if((M==null?void 0:M.type)==="column"&&R){const _=x.find(Z=>Z.column_name===A.id);if(!_)return;const J=s.isNumberDataType(_.data_type),z=s.isTextDataType(_.data_type),U=s.isDateDataType(_.data_type);(z||U)&&(R.id===Ee||((O=R.data.current)==null?void 0:O.type)===ts)&&C(_),(z||U)&&(R.id===Ae||((P=R.data.current)==null?void 0:P.type)===as)?D(_):(J||z)&&(R.id===Ie||((K=R.data.current)==null?void 0:K.type)===bs)?(J&&y(_),z&&y(_,"COUNT")):S(_)&&(R.id===ys||((Y=R.data.current)==null?void 0:Y.type)===vs)&&B(_)}if(R&&((te=R.data.current)==null?void 0:te.type)===ts&&a.some(_=>_.id===A.id)){const _=a.findIndex(z=>z.id===A.id),J=a.findIndex(z=>z.id===R.id);if(_!==-1&&J!==-1&&_!==J){const z=[...a],[U]=z.splice(_,1);z.splice(J,0,U),f(z)}}if(R&&((X=R.data.current)==null?void 0:X.type)===as&&o.some(_=>_.id===A.id)){const _=o.findIndex(z=>z.id===A.id),J=o.findIndex(z=>z.id===R.id);if(_!==-1&&J!==-1&&_!==J){const z=[...o],[U]=z.splice(_,1);z.splice(J,0,U),b(z)}}if(R&&(($=R.data.current)==null?void 0:$.type)===bs&&n.some(_=>_.id===A.id)){const _=n.findIndex(z=>z.id===A.id),J=n.findIndex(z=>z.id===R.id);if(_!==-1&&J!==-1&&_!==J){const z=[...n],[U]=z.splice(_,1);z.splice(J,0,U),g(z)}}if(R&&((H=R.data.current)==null?void 0:H.type)===vs&&r.some(_=>_.id===A.id)){const _=r.findIndex(z=>z.id===A.id),J=r.findIndex(z=>z.id===R.id);if(_!==-1&&J!==-1&&_!==J){const z=[...r],[U]=z.splice(_,1);z.splice(J,0,U),j(z)}}F(E),i(null),c(null),d(a),u(n),m(r),h(o)}function F(E){const{active:A,over:R}=E,M=A.data.current;if((M==null?void 0:M.type)===Ss&&R){const O=l.findIndex(K=>Ve(K.columnId)===A.id),P=l.findIndex(K=>Ve(K.columnId)===R.id);if(O!==-1&&P!==-1&&O!==P){const K=[...l],[Y]=K.splice(O,1);K.splice(P,0,Y),p(K)}}}function T(){i(null),c(null),d(a),u(n),m(r)}return{handleDragOver:L,handleDragEnd:w,handleDragStart:N,handleDragCancel:T,sensors:k}}function be(t){return`${t}-${s.v4()}`}function qe(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Ve(t){return`${Ss}-${t}`}function Fe(t,a){const n=s.toTitleCase(t.replace(/_/g," "));switch(a){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function Rn({dataType:t}){const a=s.getDataType(t);return a==="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(fe,{className:"h-3 w-3"})}):a==="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(Ne,{className:"h-3 w-3"})}):a==="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"})}):a==="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(Me,{className:"h-3 w-3"})}):a==="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(Oe,{className:"h-3 w-3"})}):a==="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"})}):a==="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($e,{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(fe,{className:"h-3 w-3"})})}function On({schemaName:t,tableName:a,columns:n,status:r}){const[l,o]=I.useState(""),[c,i]=I.useState("all"),d=s.useEditorStore(O=>O.sqlGen),u=s.useEditorStore(O=>O.isDevMode);s.useEditorStore(O=>O.selectedConnectionId);const m=s.useEditorStore(O=>{var P,K;return(K=(P=O.card)==null?void 0:P.queryConfig)==null?void 0:K.metricColumns});s.useEditorStore(O=>{var P,K;return(K=(P=O.card)==null?void 0:P.queryConfig)==null?void 0:K.groupByColumns});const h=s.useEditorStore(O=>O.selectedDatabaseName);s.useEditorStore(O=>O.selectedSchemaName),s.useEditorStore(O=>O.selectedTableName);const f=s.useEditorStore(O=>O.selectedDatamodelId);s.useDashboardStore(O=>O.dashboard.aiScopeTables);const{addToAIScope:g,removeFromAIScope:j}=s.useDashboardActions(),{addColumnToMetricColumns:p,addColumnToGroupBy:b,setCardSql:x,setRunSql:v,setSqlGen:k,setIsShowingVisual:L}=s.useEditorActions(),{connectionType:N,modelItems:S,selectedDatamodelName:y}=s.useEditorAside();function D(O){var P;if(u){const K=s.createSqlGenConfig(O,d);k(K);const Y=(P=S==null?void 0:S.find(X=>X.id===f))==null?void 0:P.name,te=s.getSql(K,s.fmt(t),s.fmt(a),Y||"",N,h||"");te&&(x(te),v(!0))}if(!u){if(s.isTextDataType(O.data_type))if(m&&m.length>0){const K={...O,role:"groupby",id:be(O.column_name),name:O.column_name,type:O.data_type};b(K)}else{const K={...O,role:"metric",id:be(O.column_name),name:O.column_name,label:qe(O.column_name,"COUNT"),type:O.data_type,aggregate:"COUNT"};p(K)}if(s.isDateDataType(O.data_type)){const K={...O,role:"groupby",id:be(O.column_name),name:O.column_name,type:O.data_type,label:Fe(O.column_name,"month"),granularity:"month"};b(K)}if(s.isNumberDataType(O.data_type)){const K={...O,role:"metric",id:be(O.column_name),name:O.column_name,label:qe(O.column_name,"SUM"),type:O.data_type,aggregate:"SUM"};p(K)}}}function C(){const O=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:y,connectionType:N,databaseName:h||""});L(!1);const P=N==="MSSQL"?`SELECT top 10 * FROM ${O}`:`SELECT * FROM ${O} LIMIT 10`;x(P),v(!0)}function B(){const O=s.getFormattedTableNameForQuery({schemaName:t,tableName:a,modelName:y,connectionType:N,databaseName:h||""});x(`SELECT COUNT(*) as count FROM ${O}`),v(!0)}const w=(n==null?void 0:n.filter(O=>O.column_name.toLowerCase().includes(l.toLowerCase())))||[],F=O=>s.isNumberDataType(O.data_type)?"number":"text",T=c==="all"?w:w.filter(O=>F(O)===c),E=w.filter(O=>F(O)==="text").length,A=w.filter(O=>F(O)==="number").length;function R(O){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:()=>D(O),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rn,{dataType:O.data_type}),e.jsx("span",{children:O.column_name})]}),e.jsx("div",{onClick:P=>P.stopPropagation(),className:"flex items-center justify-end",children:s.isNumberDataType(O.data_type)&&e.jsx(En,{column:O})})]}):e.jsx(Mn,{onClick:D,column:O})}function M(){return e.jsxs("div",{className:"flex grow gap-2",children:[e.jsxs(s.Button,{disabled:r!=="Success",onClick:C,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(Ta,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(s.Button,{disabled:r!=="Success",onClick:B,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(st,{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((O,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:M()}),n&&n.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:l,onChange:O=>o(O.target.value)})]}),w.length>0&&e.jsx(s.Tabs,{defaultValue:"all",value:c,onValueChange:O=>i(O),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:w.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:E})]}),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:A})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-4 pt-3",children:[T.length===0&&l&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',l,'"']}),T.length===0&&!l&&c!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",c," fields found"]}),e.jsx("div",{className:"flex flex-col gap-1",children:T==null?void 0:T.map(O=>e.jsx("div",{children:R(O)},O.column_name))}),e.jsx(s.ScrollBar,{orientation:"vertical"}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function vt({ColumnsComponent:t,type:a}){var ee;const[n,r]=I.useState(!1),l=s.useEditorStore(ae=>ae.card),o=s.useEditorStore(ae=>ae.selectedConnectionId),c=s.useDashboardStore(ae=>ae.showFilters),i=s.useEditorStore(ae=>ae.selectedDatamodelId),d=s.useEditorStore(ae=>ae.selectedDatabaseName),u=s.useEditorStore(ae=>ae.selectedSchemaName),m=s.useEditorStore(ae=>ae.selectedTableName),h=s.useEditorStore(ae=>ae.isDevMode),{setSelectedTableName:f,setIsDevMode:g,setCardSql:j}=s.useEditorActions(),{connectionItems:p,modelItems:b,schemaItems:x,databaseItems:v,tableItems:k,columns:L,isConnectionsLoading:N,isModelsLoading:S,isConnectionsError:y,isModelsError:D,isDatabasesLoadingOrFetching:C,isDatabaseError:B,isSchemaLoadingOrFetching:w,isSchemaError:F,isColumnsError:T,isColumnsLoadingOrFetching:E,isTableLoadingOrFetching:A,isTableError:R,connectionType:M,isNonDbConnection:O,refetchDatabases:P,refetchModels:K,refetchSchemas:Y,refetchTables:te,refetchColumns:X,refetchConnections:$,handleConnectionChange:H,handleDatabaseChange:_,handleSchemaChange:J,handleDatamodelChange:z,handleTableChange:U,tableName:Z,schemaName:le}=s.useEditorAside(),{data:V,refetch:se}=s.useDashboardCardQuery(l);function ne(){return t?t(le,Z,L):e.jsx(On,{schemaName:le,tableName:Z,columns:L,status:E?"Loading...":T?"Error":"Success"})}function q(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function W(ae){ae===!0?V&&(j(V.userSql),setTimeout(()=>{se()},100)):j(""),g(ae)}function re(){if(!o||M==="S3"||M==="API")return null;if(!i||i==="none")return e.jsx(Re,{refetch:P,showNone:!0,onChange:_,isError:B,isLoading:C,items:v,value:d||"",title:"Database",type:"combobox"})}function ie(){if(o&&!O&&(!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 he(){if(!o||M==="S3"||M==="API")return null;if(!d||d==="none")return e.jsx(Re,{refetch:K,showNone:!0,onChange:z,isError:D,isLoading:S,items:b,value:i||"",title:"Model",type:"combobox"})}function Q(){return!o||M==="S3"||M==="API"||!d||d==="none"?null:e.jsx(Re,{refetch:Y,onChange:J,isError:F,isLoading:w,items:x,value:u||"",title:"Schema",type:"combobox"})}function oe(){function ae(){let ue=!1;return M==="API"?(ue=!1,ue):((M==="S3"||o&&d&&d!=="none"&&u)&&(ue=!0),ue)}return ae()?e.jsx(Re,{refetch:te,onChange:U,isError:R,items:k,isLoading:A,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":n,"px-4 py-4":!n}),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(!n),size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:n?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),!n&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Re,{refetch:$,items:p,title:"Connection",value:o||"",onChange:H,isLoading:N,isError:y,type:"combobox",connectionTooltip:((ee=p==null?void 0:p.find(ae=>ae.id===o))==null?void 0:ee.type)||""}),re(),ie(),he(),Q(),oe()]})]}),ne(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:a==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:h,onCheckedChange:W,id:"dev-mode"}),e.jsx(s.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(s.Button,{onClick:q,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:a,onSendFeedback:n,className:r,showFeedbackButton:l=!0}){const[o,c]=I.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:[a&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:o?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),l&&n&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:n,children:[e.jsx(Ma,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),a&&e.jsx(s.Collapsible,{open:o,onOpenChange:c,children:e.jsx(s.CollapsibleContent,{className:"space-y-2",children:e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Error SQL Query"}),e.jsx(s.CopyButton,{text:a,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:a,language:"sql"})})]})})})]})]})})}function Ct({sql:t,error:a,errorSql:n,onDebugWithAssistant:r}){const l=s.useEditorStore(u=>u.isDevMode),{setIsDevMode:o,setCardSql:c,setRunSql:i}=s.useEditorActions();function d(){o(!l),c(t),setTimeout(()=>{i(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-3",children:[e.jsxs(s.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(Nt,{error:a,errorSql:n,showFeedbackButton:!1}),!a&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"",children:e.jsx(s.CodeHighlighter,{code:t,language:"sql"})})})]}),!l&&t&&!a&&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"]}),a&&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:a,errorSql:n,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:a?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(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:n,sql:t,error:a,onDebugWithAssistant:r})})]})}function Bn(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:a}=s.useTheme(),n=s.useDashboardStore(p=>p.theme),r=s.useEditorStore(p=>p.frame),l=s.useEditorStore(p=>p.card),o=s.useEditorStore(p=>p.activeTabCardId),c=s.Le(),{refetch:i}=s.useDashboardCardQuery(l),{updateCardTab:d,setRunSql:u}=s.useEditorActions(),m=I.useRef(),h=I.useRef({}),f=r.cards.find(p=>p.id===o),g=I.useCallback(()=>{let p="";return t==="python"&&(p=(f==null?void 0:f.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(p=(f==null?void 0:f.sql)||""),p},[t,f]);I.useEffect(()=>{if(o&&l.id&&l.id!==o){if(m.current&&c){const p=m.current.getModel();p&&(h.current[l.id]=p);let b=h.current[o];if(!b){const x=g();b=c.editor.createModel(x,t),h.current[o]=b}m.current.setModel(b)}d(o,l),u(!0)}},[o,l,d,c,u,t,g]),I.useEffect(()=>{if(!c)return;const p=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",b=n==="system"?p:n;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")},[a,n,c]),I.useEffect(()=>{const p=m.current;p&&c&&l&&p.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return i(),!1})},[c,i,l]);function j(p,b){if(m.current=p,!h.current[l.id]){const x=p.getModel(),v=g();h.current[l.id]=x||(b==null?void 0:b.editor.createModel(v,t))||p.getModel()}p.setModel(h.current[l.id])}return{handleEditorDidMount:j}}function Fn(){const t=s.useEditorStore(c=>c.card.sql),a=s.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=wt("sql");function o(c){n(c),s.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:o,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function Pn(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=wt("python");function r(l){a(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function zn({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 ws({variant:t="outline"}){var c;const{setCardSql:a}=s.useEditorActions();s.useEditorStore(i=>i.frame);const n=s.useEditorStore(i=>i.card);Ns(((c=n.customCardPreferences)==null?void 0:c.url)||""),s.useEditorStore(i=>i.selectedSchemaName),s.useEditorStore(i=>i.selectedDatamodelId),s.useEditorStore(i=>i.selectedDatabaseName),s.useEditorStore(i=>i.selectedTableName),s.useEditorStore(i=>i.selectedConnectionId),s.useEditorStore(i=>i.isShowingVisual),n.sql;const r=s.useEditorStore(i=>i.onSave),{getUpdatedFrame:l}=Cs();function o(){const i=l();r==null||r(i)}return e.jsxs(s.Button,{onClick:o,className:"h-8",size:"sm",variant:t,children:[e.jsx(s.Check,{className:"mr-2 size-4 font-bold"}),"Accept"]})}function Vn(){const t=s.useQueryClient(),[a,n]=I.useState(!1),r=s.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{setIsVisualEditing:l}=s.useDashboardActions(),{getUpdatedFrame:o}=Cs(),c=s.useSelectedVisual(),i=s.useUpdateVisualMutation(),d=()=>{const u=o();if(!(c!=null&&c.id)){s.ue.error("No visual selected");return}n(!0),i.mutate({visualId:c.id,data:{frameObject:u}},{onSuccess:()=>{n(!1),l(!1),r(!0),s.ue.success("Visual updated successfully"),t.invalidateQueries({queryKey:["resource-by-id","visual",c.id],exact:!0})},onError:()=>{n(!1),s.ue.error("Failed to update visual")}})};return e.jsxs(s.Button,{onClick:d,className:"h-8",size:"sm",children:[a&&e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-4 animate-spin font-bold"})," Saving"]}),!a&&e.jsxs(e.Fragment,{children:[e.jsx(gs,{className:"mr-2 size-4 font-bold"}),"Save"]})]})}function Ds(){const{setTempQueryData:t,setSqlGen:a}=s.useEditorActions(),n=s.useQueryClient(),r=s.useEditorStore(d=>d.tempQueryData),l=s.useEditorStore(d=>d.onClose),o=s.useEditorStore(d=>d.card),{queryKey:c}=s.useDashboardCardQuery(o);function i(){if(r){const{queryKey:d,queryData:u}=r;d&&u&&n.setQueryData(d,u)}a({}),l==null||l()}return e.jsxs(s.Button,{onClick:i,className:"h-8",size:"sm",variant:"outline",children:[e.jsx(s.X,{className:"mr-2 size-4"}),"Close"]})}function rs(){const{setTempQueryData:t}=s.useEditorActions(),a=s.useQueryClient(),n=s.useEditorStore(b=>b.isDevMode),r=s.useEditorStore(b=>b.tempQueryData),l=s.useEditorStore(b=>b.card),{queryKey:o}=s.useDashboardCardQuery(l),{setCardSql:c,setSqlGen:i,setCardPython:d,setCardCustomCfg:u,setCardPreferences:m,updateDataSource:h,clearQueryConfig:f,setCardConfig:g,setCardType:j}=s.useEditorActions();function p(){const b=a.getQueryData(o);r!=null&&r.queryData||t({queryKey:o,queryData:b}),a.setQueryData(o,null),a.removeQueries({queryKey:o,exact:!0}),n&&h(s.EMPTY_DATA_SOURCE),c(""),i({}),f(),g(void 0),d(""),u(""),m({}),j("bar")}return e.jsxs(s.Button,{onClick:p,className:"h-8",size:"sm",variant:"secondary",children:[e.jsx(s.SquarePen,{className:"mr-2 size-4"}),"Clear"]})}function _n(){const t=s.useQueryClient(),[a,n]=I.useState(!1),[r,l]=I.useState(!1);s.useEditorStore(Y=>Y.frame);const o=s.useEditorStore(Y=>Y.card);s.useEditorStore(Y=>Y.isShowingVisual),s.useEditorStore(Y=>Y.selectedConnectionId),s.useEditorStore(Y=>Y.tempQueryData),s.useEditorStore(Y=>Y.selectedDatabaseName),s.useEditorStore(Y=>Y.selectedDatamodelId),s.useEditorStore(Y=>Y.selectedSchemaName);const c=s.useEditorStore(Y=>Y.showAIDialog);s.useEditorStore(Y=>Y.selectedTableName);const i=s.useEditorStore(Y=>{var te;return(te=Y==null?void 0:Y.card)==null?void 0:te.sql}),d=s.useEditorStore(Y=>{var te;return(te=Y==null?void 0:Y.card)==null?void 0:te.python}),{sheetFilterValues:u}=s.useSheetFilterValues(),{setCardCustomCfg:m,setQueryResultColumns:h,setCardSql:f,setTempQueryData:g,setPythonStdOut:j,setCardPreferences:p,setCardType:b,setCardPython:x,runAssistant:v,setShowAIDialog:k}=s.useEditorActions();s.useEditorStore(Y=>Y.onSave),s.useEditorStore(Y=>Y.onClose),s.useEditorStore(Y=>Y.actions.setSqlGen);const L=s.useEditorStore(Y=>Y.runSql),N=s.useEditorStore(Y=>Y.actions.setRunSql),S=s.useEditorStore(Y=>Y.actions.setIsSqlRunning),{data:y,isLoading:D,isFetching:C,isSuccess:B,isError:w,error:F,errorSql:T,queryKey:E,refetch:A,errorMessage:R}=s.useDashboardCardQuery(o);I.useEffect(()=>{if(y&&(y.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),j((y==null?void 0:y.output)||""),y.records.length>0)){const{dimensionKeys:Y}=s.getKeys(y.records);h(Y)}},[y,h,j]),I.useEffect(()=>{(D||C)&&S(!0),(w||B)&&S(!1),w&&(h([]),j(""))},[D,C,y,j,w,B,S,h,F]),I.useEffect(()=>{L&&(t.getQueryData(E)||A(),N(!1))},[L,A,N,E,t]);async function M(){const Y=`Can you help me debug this query?
332
332
 
333
333
  Error:
334
334