react-semaphor 0.0.522 → 0.0.523

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.
@@ -353,7 +353,7 @@
353
353
  *
354
354
  * This source code is licensed under the ISC license.
355
355
  * See the LICENSE file in the root directory of this source tree.
356
- */const Ft=t.createLucideIcon("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);function at(s){var a;return{...s,sheets:(a=s==null?void 0:s.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(o=>{var i;return{...o,cards:(i=o.cards)==null?void 0:i.map(c=>zt(c))}})}})}}function zt(s){return{...s,customCfg:bn(s.customCfg),data:[]}}function bn(s){var a,n;return s?{...s,data:{...s==null?void 0:s.data,labels:[],datasets:(n=(a=s==null?void 0:s.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function vn(s,a,n,r){if(!r)return null;const o=JSON.stringify(a);return await t.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:s,template:o,filterValues:n,operation:"create"})}async function $e(s,a){if(!a)return null;const{id:n,template:r,filterValues:o,isDefault:i,shared:c}=s;return await t.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:o,isDefault:i,shared:c,operation:"update"})}async function Nn(s,a){return a?await t.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:s}):null}function Cn(){const[s,a]=L.useState(""),[n,r]=L.useState(!1),o=t.useDashboardStore(p=>p.lenses),{setLenses:i,setSelectedLensId:c}=t.useDashboardActions(),[d,l]=L.useState(!1),[h,u]=L.useState(!1),m=t.useDashboardStore(p=>p.dashboard),j=t.useDashboardStore(p=>p.filterValues),{authToken:v}=t.useSemaphorContext();async function C(){l(!0);const p=at(m),D=await vn(s,p,j,v==null?void 0:v.accessToken);D&&(i([...o||[],D]),c(D.id),u(!1)),l(!1)}return e.jsxs(t.Dialog,{open:h,onOpenChange:u,children:[e.jsx(t.DialogTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(t.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Create Lens"}),e.jsx(t.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(t.Label,{className:"text-right",children:"Name"}),e.jsx(t.Input,{value:s,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(t.DialogFooter,{children:e.jsx(t.Button,{size:"sm",variant:"outline",type:"submit",onClick:C,disabled:d,children:d?"Creating...":"Add"})})]})]})}function Sn(){const[s,a]=L.useState(!1),n=t.useDashboardStore(u=>u.lenses),r=t.useDashboardStore(u=>u.selectedLensId),{setLenses:o,setSelectedLensId:i}=t.useDashboardActions(),{authToken:c}=t.useSemaphorContext();async function d(u){i(u)}async function l(u){if(await Nn(u,c==null?void 0:c.accessToken)){const j=n==null?void 0:n.filter(v=>v.id!==u);o(j||[]),i("original")}}async function h(u){const m=n==null?void 0:n.map(C=>C.id===u.id?{...C,isDefault:!u.isDefault}:{...C,isDefault:!1});o(m||[]);const j={...u,isDefault:!u.isDefault};await $e(j,c==null?void 0:c.accessToken);const v=n==null?void 0:n.find(C=>C.isDefault);if(v&&v.id!==u.id){const C={...v,isDefault:!1};await $e(C,c==null?void 0:c.accessToken)}}return e.jsxs(t.DropdownMenu,{open:s,onOpenChange:a,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(Xs,{className:"h-4 w-4"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(t.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuRadioGroup,{value:r,onValueChange:d,children:[e.jsx(t.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(u=>e.jsxs(t.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:u.id,children:[e.jsx("p",{children:u.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(t.House,{onClick:m=>{m.preventDefault(),h(u)},className:t.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!u.isDefault,"text-green-500":u.isDefault}),strokeWidth:1.5}),e.jsx(t.Cross2Icon,{onClick:m=>{m.preventDefault(),l(u.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},u.id))]})]})]})}function Pt(){var i;const s=t.useDashboardStore.getState().authToken,a=t.useDashboardStore.getState().theme,n=t.useDashboardStore.getState().filterValues,r=(i=t.useDashboardStore.getState().dashboard)==null?void 0:i.title,o=t.useDashboardStore.getState().selectedSheetId;return{authToken:s,theme:a||"light",filterValues:n,dashboardTitle:r||"",selectedSheetId:o||""}}async function Rt(){const s=t.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:o,selectedSheetId:i}=Pt();if(s)return;const c=new URLSearchParams;c.set("token",(a==null?void 0:a.accessToken)||""),c.set("theme",n),c.set("filterValues",JSON.stringify(r)),c.set("selectedSheetId",i||"");const d=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(c.toString())}`;t.useDashboardStore.setState({isDownloadingPdf:!0});const u=(await(await fetch(d,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,m=document.createElement("a");m.href=u;const j=`${o}-${new Date().toISOString()}.pdf`;m.download=j,m.click(),t.useDashboardStore.setState({isDownloadingPdf:!1})}function wn({iconClassName:s}){const{authToken:a}=t.useSemaphorContext();t.useDashboardStore(o=>{var i;return(i=o.dashboard)==null?void 0:i.title}),t.useDashboardStore(o=>o.theme),t.useDashboardStore(o=>o.filterValues);const n=t.useDashboardStore(o=>o.isDownloadingPdf);async function r(){await Rt()}return e.jsx(t.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:n?e.jsx(t.LoaderCircle,{className:t.cn("size-3.5 animate-spin",s)}):e.jsx(t.Download,{className:t.cn("size-4",s)})})}function se({defaultValue:s,label:a,options:n,value:r,onValueChange:o,className:i,icon:c,showPlaceholderLabel:d=!0}){return e.jsxs(t.Select,{defaultValue:s,value:r,onValueChange:o,children:[e.jsx(t.SelectTrigger,{className:t.cn("w-full focus:ring-0 focus:ring-offset-0",i),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),d&&e.jsx(t.SelectValue,{placeholder:a})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:a}),n.map(l=>e.jsx(t.SelectItem,{value:l.value,children:l.label},l.value))]})})]})}const Nt=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function Vt({triggerButtonClassName:s}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:o,error:i,isDeleting:c}=kn(),[d,l]=L.useState(""),[h,u]=L.useState(Nt[0].value),[m,j]=L.useState("06:00"),[v,C]=L.useState("");return e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Schedule Dashboard",className:t.cn("h-7 p-2",s),children:e.jsx(t.Clock,{className:"size-4"})})}),e.jsx(t.PopoverContent,{align:"end",className:"w-80",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Subscription"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribe to receive dashboard via email"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"email",children:"Email"}),e.jsx(t.Input,{id:"email",value:d,onChange:p=>l(p.target.value),className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"subject",children:"Subject"}),e.jsx(t.Input,{id:"subject",placeholder:"Monthly Sales Report",value:v,onChange:p=>{C(p.target.value.replace(/[^a-zA-Z0-9\s-_]/g,""))},className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"frequency",children:"Frequency"}),e.jsx(se,{className:"col-span-2 h-8",label:"Select Frequency",options:Nt,value:h,onValueChange:p=>u(p)})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"time",children:"Time"}),e.jsx(t.Input,{id:"time",type:"time",value:m,onChange:p=>j(p.target.value),className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsx("div",{className:"mt-2 flex justify-end",children:e.jsxs(t.Button,{onClick:async()=>{await n({email:d,frequency:h,time:m,subject:v}),j("00:00"),l(""),C("")},className:"h-8 p-2",disabled:o==="loading"||!d,children:[o==="loading"&&e.jsx(t.LoaderCircle,{className:"mr-2 size-4 animate-spin"}),o==="success"&&e.jsx(t.Check,{className:"mr-2 size-4"}),o==="error"&&e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{children:e.jsx(It,{className:"mr-2 size-4 text-destructive"})}),e.jsx(t.TooltipContent,{children:e.jsx("p",{children:i})})]}),"Schedule"]})}),a&&a.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(t.Separator,{className:"my-2"}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Subscriptions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active email subscriptions"})]}),t.isDevEnv]})}),e.jsx("div",{className:"grid gap-2",children:a==null?void 0:a.map(p=>e.jsxs("div",{className:"group grid grid-cols-5 gap-3",children:[e.jsx("div",{className:"col-span-3 text-sm",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"boder-border rounded-md border bg-muted px-2 py-1",children:[t.titleCase(p.frequency)," "]}),e.jsx(t.Label,{children:p.time})]})}),e.jsxs("div",{className:"col-span-2 flex items-center justify-end gap-4",children:[e.jsx(Ct,{tooltip:`Next Run: ${new Date(p.nextRun).toLocaleString()} ${p.timezone}`,children:e.jsx(qs,{className:"size-3.5"})}),e.jsx(Ct,{tooltip:`${p.endUserEmail}`,children:e.jsx(on,{className:"size-3.5"})}),c===p.id?e.jsx(t.LoaderCircle,{className:"size-3.5 animate-spin"}):e.jsx(t.Trash2,{onClick:()=>r(p.id),className:"size-3.5 cursor-pointer"})]})]},p.id))})]})]})]})})]})})}const Ct=({children:s,tooltip:a})=>e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:s}),e.jsx(t.TooltipContent,{children:a})]})});function kn(){const[s,a]=L.useState("idle"),[n,r]=L.useState(""),[o,i]=L.useState(null),c=t.useDashboardStore(O=>O.authToken),d=t.useDashboardStore(O=>O.dashboard.id),l=t.useDashboardStore(O=>O.dashboard.title),{endUserId:h}=t.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),u="https://semaphor.cloud/api/v1/subscriptions/get",m={dashboardId:d,endUserId:h},{data:j,isLoading:v,isError:C,isFetching:p,refetch:D}=t.useQuery({queryKey:["subscriptions",d,h],queryFn:()=>t.getRequest(u,(c==null?void 0:c.accessToken)||"",m),enabled:!!(c!=null&&c.accessToken)&&!!d&&!!h});async function f({email:O,subject:I,frequency:k,time:N}){const{authToken:S,...w}=Pt(),E=Intl.DateTimeFormat().resolvedOptions().timeZone,g={email:O,frequency:k,time:N,timezone:E,endUserId:h,endUserEmail:O,subject:I||l||"Scheduled Dashboard",dashboardId:d,dashboardParams:w};a("loading");const x="https://semaphor.cloud/api/v1/subscriptions/create";try{const B=await t.postRequestRegular(x,(S==null?void 0:S.accessToken)||"",{...g});a("success"),r(""),D(),setTimeout(()=>{a("idle")},2e3)}catch(B){console.error(B),a("error"),r(B.message)}}async function y(O){const I="https://semaphor.cloud/api/v1/subscriptions/delete";i(O);try{await t.postRequestRegular(I,(c==null?void 0:c.accessToken)||"",{id:O}),D(),setTimeout(()=>{i(null)},2e3)}catch(k){console.error(k),i(null),a("error"),r(k.message)}}return{data:j,isLoading:v,isFetching:p,isError:C,isDeleting:o,refetch:D,handleScheduleSubscription:f,handleDeleteSubscription:y,status:s,error:n}}function En(){const{authToken:s}=t.useSemaphorContext();t.useDashboardStore(g=>g.theme);const a=t.useDashboardStore(g=>g.lenses),n=t.useDashboardStore(g=>g.selectedLensId),r=a==null?void 0:a.find(g=>g.id===n),o=t.useDashboardStore(g=>g.dashboard);t.useDashboardStore(g=>g.selectedSheetId);const i=t.useDashboardStore(g=>g.isDashboardEditing),c=t.useEditorStore(g=>g.selectedConnectionId),[d,l]=L.useState(!1),h=t.useDashboardStore(g=>g.filterValues),u=t.useDashboardStore(g=>g.isVisualEditing),m=t.useDashboardStore(g=>g.showFilters);t.useDashboardStore(g=>g.showDashboardJSON);const j=t.useDashboardStore(g=>g.onSaveFunction),v=t.useDashboardStore(g=>g.actions.setShowFilters),{addFrame:C,setSelectedFrameId:p}=t.useDashboardStore(g=>g.actions),{getSelectedSheet:D,setIsDashboardEditing:f,setShowDashboardJSON:y}=t.useDashboardStore(g=>g.actions),O=D(),{tenantId:I,endUserId:k}=L.useMemo(()=>t.getTenantAndEndUserId(s==null?void 0:s.accessToken),[s==null?void 0:s.accessToken]),N=L.useMemo(()=>I||k,[I,k]),S=()=>{if(!i||!O)return;const g={mode:"explorer",connectionId:c,id:t.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},x={id:t.v4(),cards:[g],activeCardId:g.id};C(O.id,x),p(x.id)},w=()=>{f(!0)};async function E(){if(l(!0),!n||!r)return;const g=at(o),x=JSON.stringify(g),B={...r,template:x,filterValues:h};await $e(B,s==null?void 0:s.accessToken),t.ue.success("Lens saved"),j==null||j(g),l(!1)}return u?null:e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-1 pl-3 pr-2",role:"dashboard-controls",children:[!u&&e.jsx("div",{className:"flex items-center gap-3",children:e.jsx(t.Label,{children:r==null?void 0:r.name})}),e.jsxs("div",{className:"flex gap-2",children:[!1,!u&&e.jsx(wn,{}),!u&&e.jsx(Vt,{}),i&&!u&&N&&e.jsx(Cn,{}),!u&&N&&e.jsx(Sn,{}),i&&!u&&e.jsxs(t.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!i,onClick:S,children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!i&&e.jsx(t.Button,{variant:"ghost",className:"h-7 p-2",onClick:w,size:"sm",children:e.jsx(t.Pencil,{className:"h-4 w-4"})}),i&&!u&&e.jsx(t.IconButton,{className:"h-7 p-2",onClick:()=>{f(!1),y(!1)},children:e.jsx(t.Cross2Icon,{className:"h-4 w-4"})}),i&&!u&&N&&e.jsx(t.Button,{className:"h-7 p-2",variant:"ghost",disabled:d,onClick:E,size:"sm",children:e.jsx(pn,{className:"h-4 w-4"})}),!m&&!u&&i&&e.jsx(t.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>v(!0),size:"sm",children:e.jsx(t.Filter,{className:"h-4 w-4"})}),!u&&i&&!1,!u&&!1]})]})}function Dn({name:s,items:a,value:n,onChange:r,isLoading:o,isError:i,refetch:c,className:d,icon:l,showNone:h=!1}){const u=he.useRef(null),[m,j]=he.useState(!1),[v,C]=he.useState("100%"),p=h?[...a||[],{id:"none",name:"None"}]:a;he.useLayoutEffect(()=>{u.current&&C(u.current.offsetWidth)},[]);function D(){var y;return o?"Loading...":i?"Error":n?(y=a==null?void 0:a.find(O=>O.id===n))==null?void 0:y.name:`Select ${s}`}function f(y,O){r(O),j(!1)}return e.jsxs(t.Popover,{open:m,onOpenChange:j,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{ref:u,variant:"outline",role:"combobox","aria-expanded":m,className:t.cn("flex h-9 w-full justify-between",d),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[l&&e.jsx("div",{className:"mr-2",children:l}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:D()})]}),e.jsx(t.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-full p-0",style:{minWidth:v},children:e.jsxs(t.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(t.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(t.IconButton,{className:"h-7",onClick:c,children:e.jsx(At,{className:t.cn("size-3.5 opacity-50",o&&"animate-spin")})})]}),e.jsxs(t.CommandList,{children:[e.jsxs(t.CommandEmpty,{children:["No ",s==null?void 0:s.toLowerCase()," found."]}),e.jsx(t.CommandGroup,{children:p==null?void 0:p.map(y=>e.jsx(t.CommandItem,{className:"overflow-x-auto",value:y.name,onSelect:O=>f(O,y.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Check,{className:t.cn("size-4",n===y.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:y.name,children:y.name})]})},y.id))})]})]})})]})}function ye({title:s,items:a,value:n,isLoading:r,isError:o,refetch:i,onChange:c,showNone:d=!1,className:l,disabled:h=!1,type:u="combobox"}){const m=r?"Loading...":o?"Error":n;function j(){if(s==="Connection")return e.jsx(mn,{className:"size-4"});if(s==="Database")return e.jsx(t.Database,{className:"size-4"});if(s==="Schema")return e.jsx(un,{className:"size-4"});if(s==="Table")return e.jsx(Oe,{className:"size-4"});if(s==="Model")return e.jsx(zs,{className:"size-4"})}function v(){return e.jsxs(t.Select,{disabled:h,value:m,onValueChange:c,children:[e.jsx(t.SelectTrigger,{className:t.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",l),children:e.jsx(t.SelectValue,{placeholder:r?"Loading...":o?"Error":`Select ${s}`})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[r?e.jsx(t.SelectLabel,{children:"Loading..."}):e.jsxs(t.SelectLabel,{className:"flex items-center justify-between gap-2",children:[s,e.jsx(At,{className:t.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:i})]}),e.jsxs(e.Fragment,{children:[d&&e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),a&&a.map((p,D)=>e.jsx(t.SelectItem,{value:p.id,children:p.name},D))]}),(r||o)&&e.jsx(t.SelectItem,{value:m,children:m})]})})]})}function C(){return e.jsx(Dn,{icon:j(),items:a,value:m,onChange:c||(()=>{}),isLoading:r,isError:o,refetch:i,name:s,showNone:d})}return e.jsx(t.TooltipProvider$1,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:u==="select"?v():C()})})}function Tn({column:s}){const[a,n]=L.useState(!1),r=t.useEditorStore(p=>p.selectedTableName),o=t.useEditorStore(p=>p.selectedSchemaName),i=t.useEditorStore(p=>p.selectedDatabaseName),c=t.useEditorStore(p=>p.selectedDatamodelId),d=t.useEditorStore(p=>p.sqlGen),{modelItems:l,connectionType:h}=t.useEditorAside(),u=t.useEditorStore(p=>p.actions.setSqlGen),m=t.useEditorStore(p=>p.actions.setCardSql),j=t.useEditorStore(p=>p.actions.setRunSql);function v(p,D){var I;const f=t.createSqlGenConfig(p,d,D),y=(I=l==null?void 0:l.find(k=>k.id===c))==null?void 0:I.name;u(f);const O=t.getSql(f,t.fmt(o||""),t.fmt(r),y||"",h,i||"");O&&(m(O),j(!0)),n(!1)}function C(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>v(s,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>v(s,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>v(s,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>v(s,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>v(s,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(t.HoverCard,{openDelay:0,open:a,onOpenChange:n,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx(t.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(t.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:C()})]})}function rt({column:s}){return e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger$1,{className:"shrink-0",asChild:!0,children:t.isTextDataType(s.data_type)?e.jsx(t.TextIcon,{className:"size-3 text-muted-foreground"}):t.isNumberDataType(s.data_type)?e.jsx(Ze,{className:"size-3 text-muted-foreground"}):t.isDateDataType(s.data_type)?e.jsx(t.Calendar,{className:"size-3 text-muted-foreground"}):t.isBooleanDataType(s.data_type)?e.jsx(Bt,{className:"size-3 text-muted-foreground"}):s.data_type.startsWith("json")?e.jsx(Ps,{className:"size-3 text-muted-foreground"}):e.jsx(t.QuestionMarkIcon,{className:"size-3 text-muted-foreground"})}),e.jsx(t.TooltipContent,{children:e.jsx("p",{className:"text-xs",children:s.data_type})})]})}function Fe({column:s,className:a}){return e.jsxs("div",{className:t.cn("flex min-h-8 grow items-center space-x-2 px-2 text-sm",a),children:[e.jsx(rt,{column:s}),e.jsx("span",{children:s.column_name})]})}function In({id:s,children:a,type:n="column"}){const{attributes:r,listeners:o,setNodeRef:i,transform:c}=t.useDraggable({id:s,data:{type:n}}),d=c?{translate:t.CSS.Translate.toString(c),transform:t.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:i,style:d,...o,...r,children:a})}function Mn({onClick:s,column:a}){const n=t.useDndStore(u=>u.activeId),r=t.useEditorStore(u=>{var m;return(m=u.card.queryConfig)==null?void 0:m.groupByColumns}),o=t.useEditorStore(u=>{var m;return(m=u.card.queryConfig)==null?void 0:m.metricColumns}),i=t.useEditorStore(u=>{var m;return(m=u.card.queryConfig)==null?void 0:m.filterColumns});function c(u){return d(u)||l(u)||h(u)}function d(u){return r==null?void 0:r.some(m=>m.name===u.column_name)}function l(u){return o==null?void 0:o.some(m=>m.name===u.column_name)}function h(u){return i==null?void 0:i.some(m=>m.name===u.column_name)}return e.jsxs("div",{onClick:()=>s(a),className:t.cn("relative grow overflow-x-hidden overflow-y-hidden rounded-md active:border active:border-dashed active:border-muted-foreground",{"bg-muted-foreground/10":c(a)}),children:[n===a.column_name&&e.jsx(t.DragOverlay,{children:e.jsx(Fe,{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(Fe,{column:a})}),e.jsx(In,{id:a.column_name,type:"column",children:e.jsx(Fe,{column:a})})]})}const ze={id:"__placeholder__",role:"groupby",type:"string"},Pe={id:"__placeholder__",role:"groupby",type:"string"},Re={id:"__placeholder__",role:"metric",type:"number"},Ve={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},qt={id:"__placeholder__"},xe="droppable-group-by",pe="droppable-metrics",fe="droppable-pivot-by",De="sortable-group-by",Je="sortable-metrics",Te="sortable-pivot-by",He="droppable-filters",Ye="sortable-filters",ot="sortable-order-by";function An(){const s=t.useDndStore(T=>T.insertIndex),a=t.useEditorStore(T=>{var b;return((b=T.card.queryConfig)==null?void 0:b.groupByColumns)||[]}),n=t.useEditorStore(T=>{var b;return((b=T.card.queryConfig)==null?void 0:b.metricColumns)||[]}),r=t.useEditorStore(T=>{var b;return((b=T.card.queryConfig)==null?void 0:b.filterColumns)||[]}),o=t.useEditorStore(T=>{var b;return((b=T.card.queryConfig)==null?void 0:b.orderBy)||[]}),i=t.useEditorStore(T=>{var b;return((b=T.card.queryConfig)==null?void 0:b.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:d,setPreviewGroupByColumns:l,setPreviewMetricColumns:h,setPreviewFilterColumns:u,setPreviewPivotColumns:m}=t.useDndActions(),{setGroupByColumns:j,setMetricColumns:v,setFilterColumns:C,setOrderByColumns:p,setPivotByColumns:D}=t.useEditorActions(),{columns:f}=t.useDataColumns(),{formattedTableName:y}=t.useEditorAside(),O=t.useSensors(t.useSensor(t.MouseSensor,{activationConstraint:{distance:1}})),I=T=>{var F;const{active:b,over:M}=T;if(((F=b.data.current)==null?void 0:F.type)==="column"&&M){const P=M.id,V=f.find(q=>q.column_name===b.id);if(!V)return;const z=t.isNumberDataType(V.data_type),U=t.isTextDataType(V.data_type),R=t.isDateDataType(V.data_type);if(U||R){if(a.some(H=>H.id===P)){const H=a.findIndex(G=>G.id===P);c(H);const Q=a.filter(G=>G.id!==ze.id);Q.splice(H,0,ze),l(Q)}else if(M.id===xe){c(a.length);const H=[...a,ze];l(H),h(n),u(r)}}if(U||R){if(i.some(H=>H.id===P)){const H=i.findIndex(G=>G.id===P);c(H);const Q=i.filter(G=>G.id!==Pe.id);Q.splice(H,0,Pe),m(Q)}else if(M.id===fe){c(i.length);const H=[...i,Pe];m(H),l(a),h(n),u(r)}}if(z||U){if(n.some(H=>H.id===P)){console.log("isOverMetricSortable",P);const H=n.findIndex(G=>G.id===P);c(H);const Q=n.filter(G=>G.id!==Re.id);Q.splice(H,0,Re),h(Q)}else if(M.id===pe){c(n.length);const H=[...n,Re];h(H),u(r),l(a),m(i)}}if(N(V)){if(r.some(H=>H.id===P)){const H=r.findIndex(G=>G.id===P);c(H);const Q=r.filter(G=>G.id!==Ve.id);Q.splice(H,0,Ve),u(Q)}else if(M.id===He){c(r.length);const H=[...r,Ve];u(H),h(n),l(a),m(i)}}}else l(a),h(n),u(r),m(i)};function k(T){d(T.active.id),c(null),l(a),h(n),u(r),m(i)}function N(T){return!r.some(b=>b.name===T.column_name)}function S(T,b="SUM"){const{column_name:M,data_type:F}=T,P=[...n],V=s!==null?s:n.length,z={...T,id:re(M),name:M,label:Ce(M,b),type:F,role:"metric",aggregate:b};P.splice(V,0,z),v(P)}function w(T){const b=t.isTextDataType(T.data_type);t.isDateDataType(T.data_type);const M=[...i],F=s!==null?s:i.length;let P;b?P={...T,id:re(T.column_name),name:T.column_name,type:T.data_type,role:"groupby"}:P={...T,id:re(T.column_name),name:T.column_name,type:T.data_type,role:"groupby",label:be(T.column_name,"month"),granularity:"month"},M.splice(F,0,P),D(M)}function E(T){const b=t.isTextDataType(T.data_type);t.isDateDataType(T.data_type);const M=[...a],F=s!==null?s:a.length;let P;b?P={...T,id:re(T.column_name),name:T.column_name,type:T.data_type,role:"groupby"}:P={...T,id:re(T.column_name),name:T.column_name,type:T.data_type,role:"groupby",label:be(T.column_name,"month"),granularity:"month"},M.splice(F,0,P),j(M)}function g(T){const b=[...r],M=s!==null?s:r.length,F={...T,id:re(T.column_name),name:T.column_name,type:T.data_type,sql:t.getDefaultFilterSql(T.data_type,y,t.fmt(T.column_name)),role:"filter"};b.splice(M,0,F),C(b)}function x(T){var P,V,z,U,R,q,H,Q;const{active:b,over:M}=T,F=b.data.current;if((F==null?void 0:F.type)==="column"&&M){const G=f.find(te=>te.column_name===b.id);if(!G)return;const $=t.isNumberDataType(G.data_type),J=t.isTextDataType(G.data_type),X=t.isDateDataType(G.data_type);(J||X)&&(M.id===xe||((P=M.data.current)==null?void 0:P.type)===De)&&E(G),(J||X)&&(M.id===fe||((V=M.data.current)==null?void 0:V.type)===Te)?w(G):($||J)&&(M.id===pe||((z=M.data.current)==null?void 0:z.type)===Je)?($&&S(G),J&&S(G,"COUNT")):N(G)&&(M.id===He||((U=M.data.current)==null?void 0:U.type)===Ye)&&g(G)}if(M&&((R=M.data.current)==null?void 0:R.type)===De&&a.some(G=>G.id===b.id)){const G=a.findIndex(J=>J.id===b.id),$=a.findIndex(J=>J.id===M.id);if(G!==-1&&$!==-1&&G!==$){const J=[...a],[X]=J.splice(G,1);J.splice($,0,X),j(J)}}if(M&&((q=M.data.current)==null?void 0:q.type)===Te&&i.some(G=>G.id===b.id)){const G=i.findIndex(J=>J.id===b.id),$=i.findIndex(J=>J.id===M.id);if(G!==-1&&$!==-1&&G!==$){const J=[...i],[X]=J.splice(G,1);J.splice($,0,X),D(J)}}if(M&&((H=M.data.current)==null?void 0:H.type)===Je&&n.some(G=>G.id===b.id)){const G=n.findIndex(J=>J.id===b.id),$=n.findIndex(J=>J.id===M.id);if(G!==-1&&$!==-1&&G!==$){const J=[...n],[X]=J.splice(G,1);J.splice($,0,X),v(J)}}if(M&&((Q=M.data.current)==null?void 0:Q.type)===Ye&&r.some(G=>G.id===b.id)){const G=r.findIndex(J=>J.id===b.id),$=r.findIndex(J=>J.id===M.id);if(G!==-1&&$!==-1&&G!==$){const J=[...r],[X]=J.splice(G,1);J.splice($,0,X),C(J)}}B(T),d(null),c(null),l(a),h(n),u(r),m(i)}function B(T){const{active:b,over:M}=T,F=b.data.current;if((F==null?void 0:F.type)===ot&&M){const P=o.findIndex(z=>Ne(z.columnId)===b.id),V=o.findIndex(z=>Ne(z.columnId)===M.id);if(P!==-1&&V!==-1&&P!==V){const z=[...o],[U]=z.splice(P,1);z.splice(V,0,U),p(z)}}}function A(){d(null),c(null),l(a),h(n),u(r)}return{handleDragOver:I,handleDragEnd:x,handleDragStart:k,handleDragCancel:A,sensors:O}}function re(s){return`${s}-${t.v4()}`}function Ce(s,a){const n=t.toTitleCase(s.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 Ne(s){return`${ot}-${s}`}function be(s,a){const n=t.toTitleCase(s.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 Ln({schemaName:s,tableName:a,columns:n,status:r}){const o=t.useEditorStore(b=>b.sqlGen),i=t.useEditorStore(b=>b.isDevMode),c=t.useEditorStore(b=>b.selectedConnectionId),d=t.useEditorStore(b=>{var M,F;return(F=(M=b.card)==null?void 0:M.queryConfig)==null?void 0:F.metricColumns});t.useEditorStore(b=>{var M,F;return(F=(M=b.card)==null?void 0:M.queryConfig)==null?void 0:F.groupByColumns});const l=t.useEditorStore(b=>b.selectedDatabaseName),h=t.useEditorStore(b=>b.selectedSchemaName),u=t.useEditorStore(b=>b.selectedTableName),m=t.useEditorStore(b=>b.selectedDatamodelId),j=t.useDashboardStore(b=>b.dashboard.aiScopeTables),{addToAIScope:v,removeFromAIScope:C}=t.useDashboardActions(),{addColumnToMetricColumns:p,addColumnToGroupBy:D,setCardSql:f,setRunSql:y,setSqlGen:O,setIsShowingVisual:I}=t.useEditorActions(),{connectionType:k,modelItems:N,selectedDatamodelName:S}=t.useEditorAside();function w(b){var M;if(i){const F=t.createSqlGenConfig(b,o);O(F);const P=(M=N==null?void 0:N.find(z=>z.id===m))==null?void 0:M.name,V=t.getSql(F,t.fmt(s),t.fmt(a),P||"",k,l||"");V&&(f(V),y(!0))}if(!i){if(t.isTextDataType(b.data_type))if(d&&d.length>0){const F={...b,role:"groupby",id:re(b.column_name),name:b.column_name,type:b.data_type};D(F)}else{const F={...b,role:"metric",id:re(b.column_name),name:b.column_name,label:Ce(b.column_name,"COUNT"),type:b.data_type,aggregate:"COUNT"};p(F)}if(t.isDateDataType(b.data_type)){const F={...b,role:"groupby",id:re(b.column_name),name:b.column_name,type:b.data_type,label:be(b.column_name,"month"),granularity:"month"};D(F)}if(t.isNumberDataType(b.data_type)){const F={...b,role:"metric",id:re(b.column_name),name:b.column_name,label:Ce(b.column_name,"SUM"),type:b.data_type,aggregate:"SUM"};p(F)}}}function E(b){b===!0&&(u||S)&&c?(v({connectionId:c,connectionType:k==="S3"||k==="API"?"DuckDb":k||"",databaseName:l||"",schemaName:h||"",tableName:u||"",datamodelName:t.resolveDatamodelName(S),datamodelId:m||""}),t.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(C({connectionId:c||"",connectionType:k||"",tableName:u||"",datamodelName:t.resolveDatamodelName(S),datamodelId:m||"",databaseName:l||"",schemaName:h||""}),t.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function g(){const b=t.getFormattedTableNameForQuery({schemaName:s,tableName:a,modelName:S,connectionType:k,databaseName:l||""});I(!1);const M=k==="MSSQL"?`SELECT top 10 * FROM ${b}`:`SELECT * FROM ${b} LIMIT 10`;f(M),y(!0)}function x(){const b=t.getFormattedTableNameForQuery({schemaName:s,tableName:a,modelName:S,connectionType:k,databaseName:l||""});f(`SELECT COUNT(*) as count FROM ${b}`),y(!0)}function B(){return(j==null?void 0:j.find(b=>b.connectionId===c&&(b.tableName===u||b.datamodelName===S)))!==void 0}function A(b){return i?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>w(b),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(rt,{column:b}),e.jsx("span",{children:b.column_name})]}),e.jsx("div",{onClick:M=>M.stopPropagation(),className:"flex items-center justify-end",children:t.isNumberDataType(b.data_type)&&e.jsx(Tn,{column:b})})]}):e.jsx(Mn,{onClick:w,column:b})}function T(){return e.jsxs(e.Fragment,{children:[e.jsxs(t.Toggle,{title:`${B()?"Remove from":"Add to"} Assistant Scope`,pressed:B(),onPressedChange:E,variant:"outline",className:t.cn("h-9 px-2",{}),children:[e.jsx(t.Plus,{className:t.cn("mr-1 size-4",{"text-green-400":B(),"text-muted-foreground":!B()})}),"AI"]}),e.jsxs(t.Button,{disabled:r!=="Success",onClick:g,size:"sm",variant:"secondary",className:"flex",children:[r!=="Success"?e.jsx(t.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(rn,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(t.Button,{disabled:r!=="Success",onClick:x,size:"sm",variant:"secondary",className:"w-full",children:[r!=="Success"?e.jsx(t.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(Lt,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-6",children:Array.from({length:3}).map((b,M)=>e.jsx(t.Skeleton,{className:"h-7 w-full"},M))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[i&&e.jsx("div",{className:"mx-2 flex items-center justify-center gap-2",children:T()}),e.jsxs(t.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-2 py-0",children:[e.jsx("div",{className:"flex flex-col gap-1",children:n==null?void 0:n.map(b=>e.jsx("div",{className:t.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:A(b)},b.column_name))}),e.jsx(t.ScrollBar,{orientation:"vertical"}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function _t({ColumnsComponent:s,type:a}){var me;const n=t.useEditorStore(W=>W.card),r=t.useEditorStore(W=>W.selectedConnectionId),o=t.useDashboardStore(W=>W.showFilters),i=t.useEditorStore(W=>W.selectedDatamodelId),c=t.useEditorStore(W=>W.selectedDatabaseName),d=t.useEditorStore(W=>W.selectedSchemaName),l=t.useEditorStore(W=>W.selectedTableName),h=t.useEditorStore(W=>W.isDevMode),{setSelectedTableName:u,setIsDevMode:m,setCardSql:j}=t.useEditorActions(),{connectionItems:v,modelItems:C,schemaItems:p,databaseItems:D,tableItems:f,columns:y,isConnectionsLoading:O,isModelsLoading:I,isConnectionsError:k,isModelsError:N,isDatabasesLoadingOrFetching:S,isDatabaseError:w,isSchemaLoadingOrFetching:E,isSchemaError:g,isColumnsError:x,isColumnsLoadingOrFetching:B,isTableLoadingOrFetching:A,isTableError:T,connectionType:b,isNonDbConnection:M,refetchDatabases:F,refetchModels:P,refetchSchemas:V,refetchTables:z,refetchColumns:U,refetchConnections:R,handleConnectionChange:q,handleDatabaseChange:H,handleSchemaChange:Q,handleDatamodelChange:G,handleTableChange:$,tableName:J,schemaName:X}=t.useEditorAside(),{data:te,refetch:ne}=t.useDashboardCardQuery(n);function le(){return s?s(X,J,y):e.jsx(Ln,{schemaName:X,tableName:J,columns:y,status:B?"Loading...":x?"Error":"Success"})}function oe(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function ce(W){W===!0?te&&(j(te.userSql),setTimeout(()=>{ne()},100)):j(""),m(W)}function ie(){if(!r||b==="S3"||b==="API")return null;if(!i||i==="none")return e.jsx(ye,{refetch:F,showNone:!0,onChange:H,isError:w,isLoading:S,items:D,value:c||"",title:"Database",type:"combobox"})}function _(){if(r&&!M&&(!c||c==="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(t.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(t.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(t.Separator,{})})]})}function K(){if(!r||b==="S3"||b==="API")return null;if(!c||c==="none")return e.jsx(ye,{refetch:P,showNone:!0,onChange:G,isError:N,isLoading:I,items:C,value:i||"",title:"Model",type:"combobox"})}function ae(){return!r||b==="S3"||b==="API"||!c||c==="none"?null:e.jsx(ye,{refetch:V,onChange:Q,isError:g,isLoading:E,items:p,value:d||"",title:"Schema",type:"combobox"})}function de(){function W(){let Z=!1;return b==="API"?(Z=!1,Z):((b==="S3"||r&&c&&c!=="none"&&d)&&(Z=!0),Z)}return W()?e.jsx(ye,{refetch:z,onChange:$,isError:T,items:f,isLoading:A,value:l||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:t.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!o}),children:[e.jsxs("section",{className:"space-y-3 px-6 py-4",children:[e.jsx(ye,{refetch:R,items:v,title:"Connection",value:r||"",onChange:q,isLoading:O,isError:k,type:"combobox",connectionTooltip:((me=v==null?void 0:v.find(W=>W.id===r))==null?void 0:me.type)||""}),ie(),_(),K(),ae(),de()]}),le(),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(t.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:h,onCheckedChange:ce,id:"dev-mode"}),e.jsx(t.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(t.Button,{onClick:oe,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(cn,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function Gt({error:s,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[o,i]=L.useState(!1),c=L.useRef(null),d=L.useRef(!1);function l(){s&&!d.current&&navigator.clipboard.writeText(s)}function h(j){(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),l())}function u(){const j=window.getSelection();if(j&&j.toString().trim()!==""){const v=j.toString();navigator.clipboard.writeText(v),i(!0),d.current=!0,setTimeout(()=>{i(!1),d.current=!1},1e3)}else d.current=!1}function m(){i(!1),d.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${a}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(t.CopyButton,{text:s,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${n}`,onClick:l,onKeyDown:h,onMouseUp:u,onMouseDown:m,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:s}),o&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function $t({sql:s,error:a,onDebugWithAssistant:n}){const r=t.useEditorStore(l=>l.isDevMode),{setIsDevMode:o,setCardSql:i,setRunSql:c}=t.useEditorActions();function d(){o(!r),i(s),setTimeout(()=>{c(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-2",children:[e.jsxs(t.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(Gt,{error:a}),s&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"rounded-md",children:e.jsx(t.CodeHighlighter,{code:s,language:"sql"})})})]}),!r&&s&&e.jsxs(t.Button,{onClick:d,variant:"secondary",size:"sm",children:[e.jsx(Ks,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&n&&e.jsxs(t.Button,{onClick:n,size:"sm",variant:"secondary",children:[e.jsx(en,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function Jt({sql:s,error:a,onDebugWithAssistant:n}){return e.jsxs(t.HoverCard,{openDelay:a?0:500,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(It,{className:"h-4 w-4 text-red-500"}):e.jsx(t.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(t.HoverCardContent,{align:"start",className:"flex w-[600px]",children:e.jsx($t,{sql:s,error:a,onDebugWithAssistant:n})})]})}var Ht={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},St=L.createContext&&L.createContext(Ht),On=["attr","size","title"];function Bn(s,a){if(s==null)return{};var n=Fn(s,a),r,o;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(o=0;o<i.length;o++)r=i[o],!(a.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Fn(s,a){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(a.indexOf(r)>=0)continue;n[r]=s[r]}return n}function Ie(){return Ie=Object.assign?Object.assign.bind():function(s){for(var a=1;a<arguments.length;a++){var n=arguments[a];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(s[r]=n[r])}return s},Ie.apply(this,arguments)}function wt(s,a){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);a&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(s,o).enumerable})),n.push.apply(n,r)}return n}function Me(s){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?wt(Object(n),!0).forEach(function(r){zn(s,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(n)):wt(Object(n)).forEach(function(r){Object.defineProperty(s,r,Object.getOwnPropertyDescriptor(n,r))})}return s}function zn(s,a,n){return a=Pn(a),a in s?Object.defineProperty(s,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):s[a]=n,s}function Pn(s){var a=Rn(s,"string");return typeof a=="symbol"?a:a+""}function Rn(s,a){if(typeof s!="object"||!s)return s;var n=s[Symbol.toPrimitive];if(n!==void 0){var r=n.call(s,a);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(s)}function Yt(s){return s&&s.map((a,n)=>L.createElement(a.tag,Me({key:n},a.attr),Yt(a.child)))}function ge(s){return a=>L.createElement(Vn,Ie({attr:Me({},s.attr)},a),Yt(s.child))}function Vn(s){var a=n=>{var{attr:r,size:o,title:i}=s,c=Bn(s,On),d=o||n.size||"1em",l;return n.className&&(l=n.className),s.className&&(l=(l?l+" ":"")+s.className),L.createElement("svg",Ie({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,c,{className:l,style:Me(Me({color:s.color||n.color},n.style),s.style),height:d,width:d,xmlns:"http://www.w3.org/2000/svg"}),i&&L.createElement("title",null,i),s.children)};return St!==void 0?L.createElement(St.Consumer,null,n=>a(n)):a(Ht)}function qn(s){return ge({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:[]}]})(s)}function Kt(s){const{theme:a}=t.useTheme(),n=t.useDashboardStore(p=>p.theme),r=t.useEditorStore(p=>p.frame),o=t.useEditorStore(p=>p.card),i=t.useEditorStore(p=>p.activeTabCardId),c=t.Le(),{refetch:d}=t.useDashboardCardQuery(o),{updateCardTab:l,setRunSql:h}=t.useEditorActions(),u=L.useRef(),m=L.useRef({}),j=r.cards.find(p=>p.id===i),v=L.useCallback(()=>{let p="";return s==="python"&&(p=(j==null?void 0:j.python)||t.PYTHON_DEFAULT_CODE),s==="sql"&&(p=(j==null?void 0:j.sql)||""),p},[s,j]);L.useEffect(()=>{if(i&&o.id&&o.id!==i){if(u.current&&c){const p=u.current.getModel();p&&(m.current[o.id]=p);let D=m.current[i];if(!D){const f=v();D=c.editor.createModel(f,s),m.current[i]=D}u.current.setModel(D)}l(i,o),h(!0)}},[i,o,l,c,h,s,v]),L.useEffect(()=>{if(!c)return;const p=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",D=n==="system"?p:n;c.editor.defineTheme("default",{base:D==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":D==="light"?"#ffffff":t.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[a,n,c]),L.useEffect(()=>{const p=u.current;p&&c&&o&&p.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return d(),!1})},[c,d,o]);function C(p,D){if(u.current=p,!m.current[o.id]){const f=p.getModel(),y=v();m.current[o.id]=f||(D==null?void 0:D.editor.createModel(y,s))||p.getModel()}p.setModel(m.current[o.id])}return{handleEditorDidMount:C}}function _n(){const s=t.useEditorStore(c=>c.card.sql),a=t.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=t.useEditorActions(),{handleEditorDidMount:o}=Kt("sql");function i(c){n(c),t.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!s&&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(t.Ft,{theme:"default",className:"pt-3",onChange:i,value:s||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:o})]})}function Gn(){const s=t.useEditorStore(o=>o.card.python),{setCardPython:a}=t.useEditorActions(),{handleEditorDidMount:n}=Kt("python");function r(o){a(o)}return e.jsx(t.Ft,{className:"pt-3",theme:"default",onChange:r,value:s||t.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function $n({jsonString:s}){return e.jsx(t.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:s,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function Jn(){const s=t.useQueryClient(),[a,n]=L.useState(!1),[r,o]=L.useState(!1);t.useEditorStore(z=>z.frame);const i=t.useEditorStore(z=>z.card);t.useEditorStore(z=>z.isShowingVisual),t.useEditorStore(z=>z.selectedConnectionId),t.useEditorStore(z=>z.tempQueryData),t.useEditorStore(z=>z.selectedDatabaseName),t.useEditorStore(z=>z.selectedDatamodelId),t.useEditorStore(z=>z.selectedSchemaName);const c=t.useEditorStore(z=>z.showAIDialog);t.useEditorStore(z=>z.selectedTableName);const d=t.useEditorStore(z=>{var U;return(U=z==null?void 0:z.card)==null?void 0:U.sql}),l=t.useEditorStore(z=>{var U;return(U=z==null?void 0:z.card)==null?void 0:U.python}),{sheetFilterValues:h}=t.useSheetFilterValues(),{setCardCustomCfg:u,setQueryResultColumns:m,setCardSql:j,setTempQueryData:v,setPythonStdOut:C,setCardPreferences:p,setCardType:D,setCardPython:f,runAssistant:y,setShowAIDialog:O}=t.useEditorActions();t.useEditorStore(z=>z.onSave),t.useEditorStore(z=>z.onClose),t.useEditorStore(z=>z.actions.setSqlGen);const I=t.useEditorStore(z=>z.runSql),k=t.useEditorStore(z=>z.actions.setRunSql),N=t.useEditorStore(z=>z.actions.setIsSqlRunning),{data:S,isLoading:w,isFetching:E,isSuccess:g,isError:x,error:B,queryKey:A,refetch:T,errorMessage:b}=t.useDashboardCardQuery(i);L.useEffect(()=>{if(S&&(S.rowLimitExceeded&&t.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),C((S==null?void 0:S.output)||""),S.records.length>0)){const{dimensionKeys:z}=t.getKeys(S.records);m(z)}},[S,m,C]),L.useEffect(()=>{(w||E)&&N(!0),(x||g)&&N(!1),x&&(m([]),C(""))},[w,E,S,C,x,g,N,m,B]),L.useEffect(()=>{I&&(s.getQueryData(A)||T(),k(!1))},[I,T,k,A,s]);async function M(){const z=`Can you help me debug this query in the current table scope?
356
+ */const Ft=t.createLucideIcon("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);function at(s){var a;return{...s,sheets:(a=s==null?void 0:s.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(o=>{var i;return{...o,cards:(i=o.cards)==null?void 0:i.map(c=>zt(c))}})}})}}function zt(s){return{...s,customCfg:bn(s.customCfg),data:[]}}function bn(s){var a,n;return s?{...s,data:{...s==null?void 0:s.data,labels:[],datasets:(n=(a=s==null?void 0:s.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function vn(s,a,n,r){if(!r)return null;const o=JSON.stringify(a);return await t.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:s,template:o,filterValues:n,operation:"create"})}async function $e(s,a){if(!a)return null;const{id:n,template:r,filterValues:o,isDefault:i,shared:c}=s;return await t.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:o,isDefault:i,shared:c,operation:"update"})}async function Nn(s,a){return a?await t.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:s}):null}function Cn(){const[s,a]=L.useState(""),[n,r]=L.useState(!1),o=t.useDashboardStore(p=>p.lenses),{setLenses:i,setSelectedLensId:c}=t.useDashboardActions(),[d,l]=L.useState(!1),[h,u]=L.useState(!1),m=t.useDashboardStore(p=>p.dashboard),y=t.useDashboardStore(p=>p.filterValues),{authToken:v}=t.useSemaphorContext();async function C(){l(!0);const p=at(m),D=await vn(s,p,y,v==null?void 0:v.accessToken);D&&(i([...o||[],D]),c(D.id),u(!1)),l(!1)}return e.jsxs(t.Dialog,{open:h,onOpenChange:u,children:[e.jsx(t.DialogTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(t.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Create Lens"}),e.jsx(t.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(t.Label,{className:"text-right",children:"Name"}),e.jsx(t.Input,{value:s,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(t.DialogFooter,{children:e.jsx(t.Button,{size:"sm",variant:"outline",type:"submit",onClick:C,disabled:d,children:d?"Creating...":"Add"})})]})]})}function Sn(){const[s,a]=L.useState(!1),n=t.useDashboardStore(u=>u.lenses),r=t.useDashboardStore(u=>u.selectedLensId),{setLenses:o,setSelectedLensId:i}=t.useDashboardActions(),{authToken:c}=t.useSemaphorContext();async function d(u){i(u)}async function l(u){if(await Nn(u,c==null?void 0:c.accessToken)){const y=n==null?void 0:n.filter(v=>v.id!==u);o(y||[]),i("original")}}async function h(u){const m=n==null?void 0:n.map(C=>C.id===u.id?{...C,isDefault:!u.isDefault}:{...C,isDefault:!1});o(m||[]);const y={...u,isDefault:!u.isDefault};await $e(y,c==null?void 0:c.accessToken);const v=n==null?void 0:n.find(C=>C.isDefault);if(v&&v.id!==u.id){const C={...v,isDefault:!1};await $e(C,c==null?void 0:c.accessToken)}}return e.jsxs(t.DropdownMenu,{open:s,onOpenChange:a,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(Xs,{className:"h-4 w-4"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(t.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuRadioGroup,{value:r,onValueChange:d,children:[e.jsx(t.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(u=>e.jsxs(t.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:u.id,children:[e.jsx("p",{children:u.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(t.House,{onClick:m=>{m.preventDefault(),h(u)},className:t.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!u.isDefault,"text-green-500":u.isDefault}),strokeWidth:1.5}),e.jsx(t.Cross2Icon,{onClick:m=>{m.preventDefault(),l(u.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},u.id))]})]})]})}function Pt(){var i;const s=t.useDashboardStore.getState().authToken,a=t.useDashboardStore.getState().theme,n=t.useDashboardStore.getState().filterValues,r=(i=t.useDashboardStore.getState().dashboard)==null?void 0:i.title,o=t.useDashboardStore.getState().selectedSheetId;return{authToken:s,theme:a||"light",filterValues:n,dashboardTitle:r||"",selectedSheetId:o||""}}async function Rt(){const s=t.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:o,selectedSheetId:i}=Pt();if(s)return;const c=new URLSearchParams;c.set("token",(a==null?void 0:a.accessToken)||""),c.set("theme",n),c.set("filterValues",JSON.stringify(r)),c.set("selectedSheetId",i||"");const d=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(c.toString())}`;t.useDashboardStore.setState({isDownloadingPdf:!0});const u=(await(await fetch(d,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,m=document.createElement("a");m.href=u;const y=`${o}-${new Date().toISOString()}.pdf`;m.download=y,m.click(),t.useDashboardStore.setState({isDownloadingPdf:!1})}function wn({iconClassName:s}){const{authToken:a}=t.useSemaphorContext();t.useDashboardStore(o=>{var i;return(i=o.dashboard)==null?void 0:i.title}),t.useDashboardStore(o=>o.theme),t.useDashboardStore(o=>o.filterValues);const n=t.useDashboardStore(o=>o.isDownloadingPdf);async function r(){await Rt()}return e.jsx(t.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:n?e.jsx(t.LoaderCircle,{className:t.cn("size-3.5 animate-spin",s)}):e.jsx(t.Download,{className:t.cn("size-4",s)})})}function se({defaultValue:s,label:a,options:n,value:r,onValueChange:o,className:i,icon:c,showPlaceholderLabel:d=!0}){return e.jsxs(t.Select,{defaultValue:s,value:r,onValueChange:o,children:[e.jsx(t.SelectTrigger,{className:t.cn("w-full focus:ring-0 focus:ring-offset-0",i),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),d&&e.jsx(t.SelectValue,{placeholder:a})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:a}),n.map(l=>e.jsx(t.SelectItem,{value:l.value,children:l.label},l.value))]})})]})}const Nt=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function Vt({triggerButtonClassName:s}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:o,error:i,isDeleting:c}=kn(),[d,l]=L.useState(""),[h,u]=L.useState(Nt[0].value),[m,y]=L.useState("06:00"),[v,C]=L.useState("");return e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Schedule Dashboard",className:t.cn("h-7 p-2",s),children:e.jsx(t.Clock,{className:"size-4"})})}),e.jsx(t.PopoverContent,{align:"end",className:"w-80",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Subscription"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribe to receive dashboard via email"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"email",children:"Email"}),e.jsx(t.Input,{id:"email",value:d,onChange:p=>l(p.target.value),className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"subject",children:"Subject"}),e.jsx(t.Input,{id:"subject",placeholder:"Monthly Sales Report",value:v,onChange:p=>{C(p.target.value.replace(/[^a-zA-Z0-9\s-_]/g,""))},className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"frequency",children:"Frequency"}),e.jsx(se,{className:"col-span-2 h-8",label:"Select Frequency",options:Nt,value:h,onValueChange:p=>u(p)})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"time",children:"Time"}),e.jsx(t.Input,{id:"time",type:"time",value:m,onChange:p=>y(p.target.value),className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsx("div",{className:"mt-2 flex justify-end",children:e.jsxs(t.Button,{onClick:async()=>{await n({email:d,frequency:h,time:m,subject:v}),y("00:00"),l(""),C("")},className:"h-8 p-2",disabled:o==="loading"||!d,children:[o==="loading"&&e.jsx(t.LoaderCircle,{className:"mr-2 size-4 animate-spin"}),o==="success"&&e.jsx(t.Check,{className:"mr-2 size-4"}),o==="error"&&e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{children:e.jsx(It,{className:"mr-2 size-4 text-destructive"})}),e.jsx(t.TooltipContent,{children:e.jsx("p",{children:i})})]}),"Schedule"]})}),a&&a.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(t.Separator,{className:"my-2"}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Subscriptions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active email subscriptions"})]}),t.isDevEnv]})}),e.jsx("div",{className:"grid gap-2",children:a==null?void 0:a.map(p=>e.jsxs("div",{className:"group grid grid-cols-5 gap-3",children:[e.jsx("div",{className:"col-span-3 text-sm",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"boder-border rounded-md border bg-muted px-2 py-1",children:[t.titleCase(p.frequency)," "]}),e.jsx(t.Label,{children:p.time})]})}),e.jsxs("div",{className:"col-span-2 flex items-center justify-end gap-4",children:[e.jsx(Ct,{tooltip:`Next Run: ${new Date(p.nextRun).toLocaleString()} ${p.timezone}`,children:e.jsx(qs,{className:"size-3.5"})}),e.jsx(Ct,{tooltip:`${p.endUserEmail}`,children:e.jsx(on,{className:"size-3.5"})}),c===p.id?e.jsx(t.LoaderCircle,{className:"size-3.5 animate-spin"}):e.jsx(t.Trash2,{onClick:()=>r(p.id),className:"size-3.5 cursor-pointer"})]})]},p.id))})]})]})]})})]})})}const Ct=({children:s,tooltip:a})=>e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:s}),e.jsx(t.TooltipContent,{children:a})]})});function kn(){const[s,a]=L.useState("idle"),[n,r]=L.useState(""),[o,i]=L.useState(null),c=t.useDashboardStore(O=>O.authToken),d=t.useDashboardStore(O=>O.dashboard.id),l=t.useDashboardStore(O=>O.dashboard.title),{endUserId:h}=t.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),u="https://semaphor.cloud/api/v1/subscriptions/get",m={dashboardId:d,endUserId:h},{data:y,isLoading:v,isError:C,isFetching:p,refetch:D}=t.useQuery({queryKey:["subscriptions",d,h],queryFn:()=>t.getRequest(u,(c==null?void 0:c.accessToken)||"",m),enabled:!!(c!=null&&c.accessToken)&&!!d&&!!h});async function f({email:O,subject:I,frequency:k,time:N}){const{authToken:S,...w}=Pt(),E=Intl.DateTimeFormat().resolvedOptions().timeZone,g={email:O,frequency:k,time:N,timezone:E,endUserId:h,endUserEmail:O,subject:I||l||"Scheduled Dashboard",dashboardId:d,dashboardParams:w};a("loading");const x="https://semaphor.cloud/api/v1/subscriptions/create";try{const B=await t.postRequestRegular(x,(S==null?void 0:S.accessToken)||"",{...g});a("success"),r(""),D(),setTimeout(()=>{a("idle")},2e3)}catch(B){console.error(B),a("error"),r(B.message)}}async function j(O){const I="https://semaphor.cloud/api/v1/subscriptions/delete";i(O);try{await t.postRequestRegular(I,(c==null?void 0:c.accessToken)||"",{id:O}),D(),setTimeout(()=>{i(null)},2e3)}catch(k){console.error(k),i(null),a("error"),r(k.message)}}return{data:y,isLoading:v,isFetching:p,isError:C,isDeleting:o,refetch:D,handleScheduleSubscription:f,handleDeleteSubscription:j,status:s,error:n}}function En(){const{authToken:s}=t.useSemaphorContext();t.useDashboardStore(g=>g.theme);const a=t.useDashboardStore(g=>g.lenses),n=t.useDashboardStore(g=>g.selectedLensId),r=a==null?void 0:a.find(g=>g.id===n),o=t.useDashboardStore(g=>g.dashboard);t.useDashboardStore(g=>g.selectedSheetId);const i=t.useDashboardStore(g=>g.isDashboardEditing),c=t.useEditorStore(g=>g.selectedConnectionId),[d,l]=L.useState(!1),h=t.useDashboardStore(g=>g.filterValues),u=t.useDashboardStore(g=>g.isVisualEditing),m=t.useDashboardStore(g=>g.showFilters);t.useDashboardStore(g=>g.showDashboardJSON);const y=t.useDashboardStore(g=>g.onSaveFunction),v=t.useDashboardStore(g=>g.actions.setShowFilters),{addFrame:C,setSelectedFrameId:p}=t.useDashboardStore(g=>g.actions),{getSelectedSheet:D,setIsDashboardEditing:f,setShowDashboardJSON:j}=t.useDashboardStore(g=>g.actions),O=D(),{tenantId:I,endUserId:k}=L.useMemo(()=>t.getTenantAndEndUserId(s==null?void 0:s.accessToken),[s==null?void 0:s.accessToken]),N=L.useMemo(()=>I||k,[I,k]),S=()=>{if(!i||!O)return;const g={mode:"explorer",connectionId:c,id:t.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},x={id:t.v4(),cards:[g],activeCardId:g.id};C(O.id,x),p(x.id)},w=()=>{f(!0)};async function E(){if(l(!0),!n||!r)return;const g=at(o),x=JSON.stringify(g),B={...r,template:x,filterValues:h};await $e(B,s==null?void 0:s.accessToken),t.ue.success("Lens saved"),y==null||y(g),l(!1)}return u?null:e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-1 pl-3 pr-2",role:"dashboard-controls",children:[!u&&e.jsx("div",{className:"flex items-center gap-3",children:e.jsx(t.Label,{children:r==null?void 0:r.name})}),e.jsxs("div",{className:"flex gap-2",children:[!1,!u&&e.jsx(wn,{}),!u&&e.jsx(Vt,{}),i&&!u&&N&&e.jsx(Cn,{}),!u&&N&&e.jsx(Sn,{}),i&&!u&&e.jsxs(t.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!i,onClick:S,children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!i&&e.jsx(t.Button,{variant:"ghost",className:"h-7 p-2",onClick:w,size:"sm",children:e.jsx(t.Pencil,{className:"h-4 w-4"})}),i&&!u&&e.jsx(t.IconButton,{className:"h-7 p-2",onClick:()=>{f(!1),j(!1)},children:e.jsx(t.Cross2Icon,{className:"h-4 w-4"})}),i&&!u&&N&&e.jsx(t.Button,{className:"h-7 p-2",variant:"ghost",disabled:d,onClick:E,size:"sm",children:e.jsx(pn,{className:"h-4 w-4"})}),!m&&!u&&i&&e.jsx(t.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>v(!0),size:"sm",children:e.jsx(t.Filter,{className:"h-4 w-4"})}),!u&&i&&!1,!u&&!1]})]})}function Dn({name:s,items:a,value:n,onChange:r,isLoading:o,isError:i,refetch:c,className:d,icon:l,showNone:h=!1}){const u=he.useRef(null),[m,y]=he.useState(!1),[v,C]=he.useState("100%"),p=h?[...a||[],{id:"none",name:"None"}]:a;he.useLayoutEffect(()=>{u.current&&C(u.current.offsetWidth)},[]);function D(){var j;return o?"Loading...":i?"Error":n?(j=a==null?void 0:a.find(O=>O.id===n))==null?void 0:j.name:`Select ${s}`}function f(j,O){r(O),y(!1)}return e.jsxs(t.Popover,{open:m,onOpenChange:y,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{ref:u,variant:"outline",role:"combobox","aria-expanded":m,className:t.cn("flex h-9 w-full justify-between",d),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[l&&e.jsx("div",{className:"mr-2",children:l}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:D()})]}),e.jsx(t.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-full p-0",style:{minWidth:v},children:e.jsxs(t.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(t.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(t.IconButton,{className:"h-7",onClick:c,children:e.jsx(At,{className:t.cn("size-3.5 opacity-50",o&&"animate-spin")})})]}),e.jsxs(t.CommandList,{children:[e.jsxs(t.CommandEmpty,{children:["No ",s==null?void 0:s.toLowerCase()," found."]}),e.jsx(t.CommandGroup,{children:p==null?void 0:p.map(j=>e.jsx(t.CommandItem,{className:"overflow-x-auto",value:j.name,onSelect:O=>f(O,j.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Check,{className:t.cn("size-4",n===j.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:j.name,children:j.name})]})},j.id))})]})]})})]})}function ye({title:s,items:a,value:n,isLoading:r,isError:o,refetch:i,onChange:c,showNone:d=!1,className:l,disabled:h=!1,type:u="combobox"}){const m=r?"Loading...":o?"Error":n;function y(){if(s==="Connection")return e.jsx(mn,{className:"size-4"});if(s==="Database")return e.jsx(t.Database,{className:"size-4"});if(s==="Schema")return e.jsx(un,{className:"size-4"});if(s==="Table")return e.jsx(Oe,{className:"size-4"});if(s==="Model")return e.jsx(zs,{className:"size-4"})}function v(){return e.jsxs(t.Select,{disabled:h,value:m,onValueChange:c,children:[e.jsx(t.SelectTrigger,{className:t.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",l),children:e.jsx(t.SelectValue,{placeholder:r?"Loading...":o?"Error":`Select ${s}`})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[r?e.jsx(t.SelectLabel,{children:"Loading..."}):e.jsxs(t.SelectLabel,{className:"flex items-center justify-between gap-2",children:[s,e.jsx(At,{className:t.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:i})]}),e.jsxs(e.Fragment,{children:[d&&e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),a&&a.map((p,D)=>e.jsx(t.SelectItem,{value:p.id,children:p.name},D))]}),(r||o)&&e.jsx(t.SelectItem,{value:m,children:m})]})})]})}function C(){return e.jsx(Dn,{icon:y(),items:a,value:m,onChange:c||(()=>{}),isLoading:r,isError:o,refetch:i,name:s,showNone:d})}return e.jsx(t.TooltipProvider$1,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:u==="select"?v():C()})})}function Tn({column:s}){const[a,n]=L.useState(!1),r=t.useEditorStore(p=>p.selectedTableName),o=t.useEditorStore(p=>p.selectedSchemaName),i=t.useEditorStore(p=>p.selectedDatabaseName),c=t.useEditorStore(p=>p.selectedDatamodelId),d=t.useEditorStore(p=>p.sqlGen),{modelItems:l,connectionType:h}=t.useEditorAside(),u=t.useEditorStore(p=>p.actions.setSqlGen),m=t.useEditorStore(p=>p.actions.setCardSql),y=t.useEditorStore(p=>p.actions.setRunSql);function v(p,D){var I;const f=t.createSqlGenConfig(p,d,D),j=(I=l==null?void 0:l.find(k=>k.id===c))==null?void 0:I.name;u(f);const O=t.getSql(f,t.fmt(o||""),t.fmt(r),j||"",h,i||"");O&&(m(O),y(!0)),n(!1)}function C(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>v(s,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>v(s,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>v(s,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>v(s,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>v(s,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(t.HoverCard,{openDelay:0,open:a,onOpenChange:n,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx(t.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(t.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:C()})]})}function rt({column:s}){return e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger$1,{className:"shrink-0",asChild:!0,children:t.isTextDataType(s.data_type)?e.jsx(t.TextIcon,{className:"size-3 text-muted-foreground"}):t.isNumberDataType(s.data_type)?e.jsx(Ze,{className:"size-3 text-muted-foreground"}):t.isDateDataType(s.data_type)?e.jsx(t.Calendar,{className:"size-3 text-muted-foreground"}):t.isBooleanDataType(s.data_type)?e.jsx(Bt,{className:"size-3 text-muted-foreground"}):s.data_type.startsWith("json")?e.jsx(Ps,{className:"size-3 text-muted-foreground"}):e.jsx(t.QuestionMarkIcon,{className:"size-3 text-muted-foreground"})}),e.jsx(t.TooltipContent,{children:e.jsx("p",{className:"text-xs",children:s.data_type})})]})}function Fe({column:s,className:a}){return e.jsxs("div",{className:t.cn("flex min-h-8 grow items-center space-x-2 px-2 text-sm",a),children:[e.jsx(rt,{column:s}),e.jsx("span",{children:s.column_name})]})}function In({id:s,children:a,type:n="column"}){const{attributes:r,listeners:o,setNodeRef:i,transform:c}=t.useDraggable({id:s,data:{type:n}}),d=c?{translate:t.CSS.Translate.toString(c),transform:t.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:i,style:d,...o,...r,children:a})}function Mn({onClick:s,column:a}){const n=t.useDndStore(u=>u.activeId),r=t.useEditorStore(u=>{var m;return(m=u.card.queryConfig)==null?void 0:m.groupByColumns}),o=t.useEditorStore(u=>{var m;return(m=u.card.queryConfig)==null?void 0:m.metricColumns}),i=t.useEditorStore(u=>{var m;return(m=u.card.queryConfig)==null?void 0:m.filterColumns});function c(u){return d(u)||l(u)||h(u)}function d(u){return r==null?void 0:r.some(m=>m.name===u.column_name)}function l(u){return o==null?void 0:o.some(m=>m.name===u.column_name)}function h(u){return i==null?void 0:i.some(m=>m.name===u.column_name)}return e.jsxs("div",{onClick:()=>s(a),className:t.cn("relative grow overflow-x-hidden overflow-y-hidden rounded-md active:border active:border-dashed active:border-muted-foreground",{"bg-muted-foreground/10":c(a)}),children:[n===a.column_name&&e.jsx(t.DragOverlay,{children:e.jsx(Fe,{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(Fe,{column:a})}),e.jsx(In,{id:a.column_name,type:"column",children:e.jsx(Fe,{column:a})})]})}const ze={id:"__placeholder__",role:"groupby",type:"string"},Pe={id:"__placeholder__",role:"groupby",type:"string"},Re={id:"__placeholder__",role:"metric",type:"number"},Ve={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},qt={id:"__placeholder__"},xe="droppable-group-by",pe="droppable-metrics",fe="droppable-pivot-by",De="sortable-group-by",Je="sortable-metrics",Te="sortable-pivot-by",He="droppable-filters",Ye="sortable-filters",ot="sortable-order-by";function An(){const s=t.useDndStore(T=>T.insertIndex),a=t.useEditorStore(T=>{var b;return((b=T.card.queryConfig)==null?void 0:b.groupByColumns)||[]}),n=t.useEditorStore(T=>{var b;return((b=T.card.queryConfig)==null?void 0:b.metricColumns)||[]}),r=t.useEditorStore(T=>{var b;return((b=T.card.queryConfig)==null?void 0:b.filterColumns)||[]}),o=t.useEditorStore(T=>{var b;return((b=T.card.queryConfig)==null?void 0:b.orderBy)||[]}),i=t.useEditorStore(T=>{var b;return((b=T.card.queryConfig)==null?void 0:b.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:d,setPreviewGroupByColumns:l,setPreviewMetricColumns:h,setPreviewFilterColumns:u,setPreviewPivotColumns:m}=t.useDndActions(),{setGroupByColumns:y,setMetricColumns:v,setFilterColumns:C,setOrderByColumns:p,setPivotByColumns:D}=t.useEditorActions(),{columns:f}=t.useDataColumns(),{formattedTableName:j}=t.useEditorAside(),O=t.useSensors(t.useSensor(t.MouseSensor,{activationConstraint:{distance:1}})),I=T=>{var F;const{active:b,over:M}=T;if(((F=b.data.current)==null?void 0:F.type)==="column"&&M){const P=M.id,V=f.find(q=>q.column_name===b.id);if(!V)return;const z=t.isNumberDataType(V.data_type),U=t.isTextDataType(V.data_type),R=t.isDateDataType(V.data_type);if(U||R){if(a.some(H=>H.id===P)){const H=a.findIndex(G=>G.id===P);c(H);const Q=a.filter(G=>G.id!==ze.id);Q.splice(H,0,ze),l(Q)}else if(M.id===xe){c(a.length);const H=[...a,ze];l(H),h(n),u(r)}}if(U||R){if(i.some(H=>H.id===P)){const H=i.findIndex(G=>G.id===P);c(H);const Q=i.filter(G=>G.id!==Pe.id);Q.splice(H,0,Pe),m(Q)}else if(M.id===fe){c(i.length);const H=[...i,Pe];m(H),l(a),h(n),u(r)}}if(z||U){if(n.some(H=>H.id===P)){console.log("isOverMetricSortable",P);const H=n.findIndex(G=>G.id===P);c(H);const Q=n.filter(G=>G.id!==Re.id);Q.splice(H,0,Re),h(Q)}else if(M.id===pe){c(n.length);const H=[...n,Re];h(H),u(r),l(a),m(i)}}if(N(V)){if(r.some(H=>H.id===P)){const H=r.findIndex(G=>G.id===P);c(H);const Q=r.filter(G=>G.id!==Ve.id);Q.splice(H,0,Ve),u(Q)}else if(M.id===He){c(r.length);const H=[...r,Ve];u(H),h(n),l(a),m(i)}}}else l(a),h(n),u(r),m(i)};function k(T){d(T.active.id),c(null),l(a),h(n),u(r),m(i)}function N(T){return!r.some(b=>b.name===T.column_name)}function S(T,b="SUM"){const{column_name:M,data_type:F}=T,P=[...n],V=s!==null?s:n.length,z={...T,id:re(M),name:M,label:Ce(M,b),type:F,role:"metric",aggregate:b};P.splice(V,0,z),v(P)}function w(T){const b=t.isTextDataType(T.data_type);t.isDateDataType(T.data_type);const M=[...i],F=s!==null?s:i.length;let P;b?P={...T,id:re(T.column_name),name:T.column_name,type:T.data_type,role:"groupby"}:P={...T,id:re(T.column_name),name:T.column_name,type:T.data_type,role:"groupby",label:be(T.column_name,"month"),granularity:"month"},M.splice(F,0,P),D(M)}function E(T){const b=t.isTextDataType(T.data_type);t.isDateDataType(T.data_type);const M=[...a],F=s!==null?s:a.length;let P;b?P={...T,id:re(T.column_name),name:T.column_name,type:T.data_type,role:"groupby"}:P={...T,id:re(T.column_name),name:T.column_name,type:T.data_type,role:"groupby",label:be(T.column_name,"month"),granularity:"month"},M.splice(F,0,P),y(M)}function g(T){const b=[...r],M=s!==null?s:r.length,F={...T,id:re(T.column_name),name:T.column_name,type:T.data_type,sql:t.getDefaultFilterSql(T.data_type,j,t.fmt(T.column_name)),role:"filter"};b.splice(M,0,F),C(b)}function x(T){var P,V,z,U,R,q,H,Q;const{active:b,over:M}=T,F=b.data.current;if((F==null?void 0:F.type)==="column"&&M){const G=f.find(te=>te.column_name===b.id);if(!G)return;const $=t.isNumberDataType(G.data_type),J=t.isTextDataType(G.data_type),X=t.isDateDataType(G.data_type);(J||X)&&(M.id===xe||((P=M.data.current)==null?void 0:P.type)===De)&&E(G),(J||X)&&(M.id===fe||((V=M.data.current)==null?void 0:V.type)===Te)?w(G):($||J)&&(M.id===pe||((z=M.data.current)==null?void 0:z.type)===Je)?($&&S(G),J&&S(G,"COUNT")):N(G)&&(M.id===He||((U=M.data.current)==null?void 0:U.type)===Ye)&&g(G)}if(M&&((R=M.data.current)==null?void 0:R.type)===De&&a.some(G=>G.id===b.id)){const G=a.findIndex(J=>J.id===b.id),$=a.findIndex(J=>J.id===M.id);if(G!==-1&&$!==-1&&G!==$){const J=[...a],[X]=J.splice(G,1);J.splice($,0,X),y(J)}}if(M&&((q=M.data.current)==null?void 0:q.type)===Te&&i.some(G=>G.id===b.id)){const G=i.findIndex(J=>J.id===b.id),$=i.findIndex(J=>J.id===M.id);if(G!==-1&&$!==-1&&G!==$){const J=[...i],[X]=J.splice(G,1);J.splice($,0,X),D(J)}}if(M&&((H=M.data.current)==null?void 0:H.type)===Je&&n.some(G=>G.id===b.id)){const G=n.findIndex(J=>J.id===b.id),$=n.findIndex(J=>J.id===M.id);if(G!==-1&&$!==-1&&G!==$){const J=[...n],[X]=J.splice(G,1);J.splice($,0,X),v(J)}}if(M&&((Q=M.data.current)==null?void 0:Q.type)===Ye&&r.some(G=>G.id===b.id)){const G=r.findIndex(J=>J.id===b.id),$=r.findIndex(J=>J.id===M.id);if(G!==-1&&$!==-1&&G!==$){const J=[...r],[X]=J.splice(G,1);J.splice($,0,X),C(J)}}B(T),d(null),c(null),l(a),h(n),u(r),m(i)}function B(T){const{active:b,over:M}=T,F=b.data.current;if((F==null?void 0:F.type)===ot&&M){const P=o.findIndex(z=>Ne(z.columnId)===b.id),V=o.findIndex(z=>Ne(z.columnId)===M.id);if(P!==-1&&V!==-1&&P!==V){const z=[...o],[U]=z.splice(P,1);z.splice(V,0,U),p(z)}}}function A(){d(null),c(null),l(a),h(n),u(r)}return{handleDragOver:I,handleDragEnd:x,handleDragStart:k,handleDragCancel:A,sensors:O}}function re(s){return`${s}-${t.v4()}`}function Ce(s,a){const n=t.toTitleCase(s.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 Ne(s){return`${ot}-${s}`}function be(s,a){const n=t.toTitleCase(s.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 Ln({schemaName:s,tableName:a,columns:n,status:r}){const o=t.useEditorStore(b=>b.sqlGen),i=t.useEditorStore(b=>b.isDevMode),c=t.useEditorStore(b=>b.selectedConnectionId),d=t.useEditorStore(b=>{var M,F;return(F=(M=b.card)==null?void 0:M.queryConfig)==null?void 0:F.metricColumns});t.useEditorStore(b=>{var M,F;return(F=(M=b.card)==null?void 0:M.queryConfig)==null?void 0:F.groupByColumns});const l=t.useEditorStore(b=>b.selectedDatabaseName),h=t.useEditorStore(b=>b.selectedSchemaName),u=t.useEditorStore(b=>b.selectedTableName),m=t.useEditorStore(b=>b.selectedDatamodelId),y=t.useDashboardStore(b=>b.dashboard.aiScopeTables),{addToAIScope:v,removeFromAIScope:C}=t.useDashboardActions(),{addColumnToMetricColumns:p,addColumnToGroupBy:D,setCardSql:f,setRunSql:j,setSqlGen:O,setIsShowingVisual:I}=t.useEditorActions(),{connectionType:k,modelItems:N,selectedDatamodelName:S}=t.useEditorAside();function w(b){var M;if(i){const F=t.createSqlGenConfig(b,o);O(F);const P=(M=N==null?void 0:N.find(z=>z.id===m))==null?void 0:M.name,V=t.getSql(F,t.fmt(s),t.fmt(a),P||"",k,l||"");V&&(f(V),j(!0))}if(!i){if(t.isTextDataType(b.data_type))if(d&&d.length>0){const F={...b,role:"groupby",id:re(b.column_name),name:b.column_name,type:b.data_type};D(F)}else{const F={...b,role:"metric",id:re(b.column_name),name:b.column_name,label:Ce(b.column_name,"COUNT"),type:b.data_type,aggregate:"COUNT"};p(F)}if(t.isDateDataType(b.data_type)){const F={...b,role:"groupby",id:re(b.column_name),name:b.column_name,type:b.data_type,label:be(b.column_name,"month"),granularity:"month"};D(F)}if(t.isNumberDataType(b.data_type)){const F={...b,role:"metric",id:re(b.column_name),name:b.column_name,label:Ce(b.column_name,"SUM"),type:b.data_type,aggregate:"SUM"};p(F)}}}function E(b){b===!0&&(u||S)&&c?(v({connectionId:c,connectionType:k==="S3"||k==="API"?"DuckDb":k||"",databaseName:l||"",schemaName:h||"",tableName:u||"",datamodelName:t.resolveDatamodelName(S),datamodelId:m||""}),t.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(C({connectionId:c||"",connectionType:k||"",tableName:u||"",datamodelName:t.resolveDatamodelName(S),datamodelId:m||"",databaseName:l||"",schemaName:h||""}),t.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function g(){const b=t.getFormattedTableNameForQuery({schemaName:s,tableName:a,modelName:S,connectionType:k,databaseName:l||""});I(!1);const M=k==="MSSQL"?`SELECT top 10 * FROM ${b}`:`SELECT * FROM ${b} LIMIT 10`;f(M),j(!0)}function x(){const b=t.getFormattedTableNameForQuery({schemaName:s,tableName:a,modelName:S,connectionType:k,databaseName:l||""});f(`SELECT COUNT(*) as count FROM ${b}`),j(!0)}function B(){return(y==null?void 0:y.find(b=>b.connectionId===c&&(b.tableName===u||b.datamodelName===S)))!==void 0}function A(b){return i?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>w(b),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(rt,{column:b}),e.jsx("span",{children:b.column_name})]}),e.jsx("div",{onClick:M=>M.stopPropagation(),className:"flex items-center justify-end",children:t.isNumberDataType(b.data_type)&&e.jsx(Tn,{column:b})})]}):e.jsx(Mn,{onClick:w,column:b})}function T(){return e.jsxs(e.Fragment,{children:[e.jsxs(t.Toggle,{title:`${B()?"Remove from":"Add to"} Assistant Scope`,pressed:B(),onPressedChange:E,variant:"outline",className:t.cn("h-9 px-2",{}),children:[e.jsx(t.Plus,{className:t.cn("mr-1 size-4",{"text-green-400":B(),"text-muted-foreground":!B()})}),"AI"]}),e.jsxs(t.Button,{disabled:r!=="Success",onClick:g,size:"sm",variant:"secondary",className:"flex",children:[r!=="Success"?e.jsx(t.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(rn,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(t.Button,{disabled:r!=="Success",onClick:x,size:"sm",variant:"secondary",className:"w-full",children:[r!=="Success"?e.jsx(t.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(Lt,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-6",children:Array.from({length:3}).map((b,M)=>e.jsx(t.Skeleton,{className:"h-7 w-full"},M))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[i&&e.jsx("div",{className:"mx-2 flex items-center justify-center gap-2",children:T()}),e.jsxs(t.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-2 py-0",children:[e.jsx("div",{className:"flex flex-col gap-1",children:n==null?void 0:n.map(b=>e.jsx("div",{className:t.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:A(b)},b.column_name))}),e.jsx(t.ScrollBar,{orientation:"vertical"}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function _t({ColumnsComponent:s,type:a}){var me;const n=t.useEditorStore(W=>W.card),r=t.useEditorStore(W=>W.selectedConnectionId),o=t.useDashboardStore(W=>W.showFilters),i=t.useEditorStore(W=>W.selectedDatamodelId),c=t.useEditorStore(W=>W.selectedDatabaseName),d=t.useEditorStore(W=>W.selectedSchemaName),l=t.useEditorStore(W=>W.selectedTableName),h=t.useEditorStore(W=>W.isDevMode),{setSelectedTableName:u,setIsDevMode:m,setCardSql:y}=t.useEditorActions(),{connectionItems:v,modelItems:C,schemaItems:p,databaseItems:D,tableItems:f,columns:j,isConnectionsLoading:O,isModelsLoading:I,isConnectionsError:k,isModelsError:N,isDatabasesLoadingOrFetching:S,isDatabaseError:w,isSchemaLoadingOrFetching:E,isSchemaError:g,isColumnsError:x,isColumnsLoadingOrFetching:B,isTableLoadingOrFetching:A,isTableError:T,connectionType:b,isNonDbConnection:M,refetchDatabases:F,refetchModels:P,refetchSchemas:V,refetchTables:z,refetchColumns:U,refetchConnections:R,handleConnectionChange:q,handleDatabaseChange:H,handleSchemaChange:Q,handleDatamodelChange:G,handleTableChange:$,tableName:J,schemaName:X}=t.useEditorAside(),{data:te,refetch:ne}=t.useDashboardCardQuery(n);function le(){return s?s(X,J,j):e.jsx(Ln,{schemaName:X,tableName:J,columns:j,status:B?"Loading...":x?"Error":"Success"})}function oe(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function ce(W){W===!0?te&&(y(te.userSql),setTimeout(()=>{ne()},100)):y(""),m(W)}function ie(){if(!r||b==="S3"||b==="API")return null;if(!i||i==="none")return e.jsx(ye,{refetch:F,showNone:!0,onChange:H,isError:w,isLoading:S,items:D,value:c||"",title:"Database",type:"combobox"})}function _(){if(r&&!M&&(!c||c==="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(t.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(t.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(t.Separator,{})})]})}function K(){if(!r||b==="S3"||b==="API")return null;if(!c||c==="none")return e.jsx(ye,{refetch:P,showNone:!0,onChange:G,isError:N,isLoading:I,items:C,value:i||"",title:"Model",type:"combobox"})}function ae(){return!r||b==="S3"||b==="API"||!c||c==="none"?null:e.jsx(ye,{refetch:V,onChange:Q,isError:g,isLoading:E,items:p,value:d||"",title:"Schema",type:"combobox"})}function de(){function W(){let Z=!1;return b==="API"?(Z=!1,Z):((b==="S3"||r&&c&&c!=="none"&&d)&&(Z=!0),Z)}return W()?e.jsx(ye,{refetch:z,onChange:$,isError:T,items:f,isLoading:A,value:l||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:t.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!o}),children:[e.jsxs("section",{className:"space-y-3 px-6 py-4",children:[e.jsx(ye,{refetch:R,items:v,title:"Connection",value:r||"",onChange:q,isLoading:O,isError:k,type:"combobox",connectionTooltip:((me=v==null?void 0:v.find(W=>W.id===r))==null?void 0:me.type)||""}),ie(),_(),K(),ae(),de()]}),le(),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(t.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:h,onCheckedChange:ce,id:"dev-mode"}),e.jsx(t.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(t.Button,{onClick:oe,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(cn,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function Gt({error:s,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[o,i]=L.useState(!1),c=L.useRef(null),d=L.useRef(!1);function l(){s&&!d.current&&navigator.clipboard.writeText(s)}function h(y){(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),l())}function u(){const y=window.getSelection();if(y&&y.toString().trim()!==""){const v=y.toString();navigator.clipboard.writeText(v),i(!0),d.current=!0,setTimeout(()=>{i(!1),d.current=!1},1e3)}else d.current=!1}function m(){i(!1),d.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${a}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(t.CopyButton,{text:s,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${n}`,onClick:l,onKeyDown:h,onMouseUp:u,onMouseDown:m,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:s}),o&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function $t({sql:s,error:a,onDebugWithAssistant:n}){const r=t.useEditorStore(l=>l.isDevMode),{setIsDevMode:o,setCardSql:i,setRunSql:c}=t.useEditorActions();function d(){o(!r),i(s),setTimeout(()=>{c(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-2",children:[e.jsxs(t.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(Gt,{error:a}),s&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"rounded-md",children:e.jsx(t.CodeHighlighter,{code:s,language:"sql"})})})]}),!r&&s&&e.jsxs(t.Button,{onClick:d,variant:"secondary",size:"sm",children:[e.jsx(Ks,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&n&&e.jsxs(t.Button,{onClick:n,size:"sm",variant:"secondary",children:[e.jsx(en,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function Jt({sql:s,error:a,onDebugWithAssistant:n}){return e.jsxs(t.HoverCard,{openDelay:a?0:500,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(It,{className:"h-4 w-4 text-red-500"}):e.jsx(t.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(t.HoverCardContent,{align:"start",className:"flex w-[600px]",children:e.jsx($t,{sql:s,error:a,onDebugWithAssistant:n})})]})}var Ht={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},St=L.createContext&&L.createContext(Ht),On=["attr","size","title"];function Bn(s,a){if(s==null)return{};var n=Fn(s,a),r,o;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(o=0;o<i.length;o++)r=i[o],!(a.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Fn(s,a){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(a.indexOf(r)>=0)continue;n[r]=s[r]}return n}function Ie(){return Ie=Object.assign?Object.assign.bind():function(s){for(var a=1;a<arguments.length;a++){var n=arguments[a];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(s[r]=n[r])}return s},Ie.apply(this,arguments)}function wt(s,a){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);a&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(s,o).enumerable})),n.push.apply(n,r)}return n}function Me(s){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?wt(Object(n),!0).forEach(function(r){zn(s,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(n)):wt(Object(n)).forEach(function(r){Object.defineProperty(s,r,Object.getOwnPropertyDescriptor(n,r))})}return s}function zn(s,a,n){return a=Pn(a),a in s?Object.defineProperty(s,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):s[a]=n,s}function Pn(s){var a=Rn(s,"string");return typeof a=="symbol"?a:a+""}function Rn(s,a){if(typeof s!="object"||!s)return s;var n=s[Symbol.toPrimitive];if(n!==void 0){var r=n.call(s,a);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(s)}function Yt(s){return s&&s.map((a,n)=>L.createElement(a.tag,Me({key:n},a.attr),Yt(a.child)))}function ge(s){return a=>L.createElement(Vn,Ie({attr:Me({},s.attr)},a),Yt(s.child))}function Vn(s){var a=n=>{var{attr:r,size:o,title:i}=s,c=Bn(s,On),d=o||n.size||"1em",l;return n.className&&(l=n.className),s.className&&(l=(l?l+" ":"")+s.className),L.createElement("svg",Ie({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,c,{className:l,style:Me(Me({color:s.color||n.color},n.style),s.style),height:d,width:d,xmlns:"http://www.w3.org/2000/svg"}),i&&L.createElement("title",null,i),s.children)};return St!==void 0?L.createElement(St.Consumer,null,n=>a(n)):a(Ht)}function qn(s){return ge({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:[]}]})(s)}function Kt(s){const{theme:a}=t.useTheme(),n=t.useDashboardStore(p=>p.theme),r=t.useEditorStore(p=>p.frame),o=t.useEditorStore(p=>p.card),i=t.useEditorStore(p=>p.activeTabCardId),c=t.Le(),{refetch:d}=t.useDashboardCardQuery(o),{updateCardTab:l,setRunSql:h}=t.useEditorActions(),u=L.useRef(),m=L.useRef({}),y=r.cards.find(p=>p.id===i),v=L.useCallback(()=>{let p="";return s==="python"&&(p=(y==null?void 0:y.python)||t.PYTHON_DEFAULT_CODE),s==="sql"&&(p=(y==null?void 0:y.sql)||""),p},[s,y]);L.useEffect(()=>{if(i&&o.id&&o.id!==i){if(u.current&&c){const p=u.current.getModel();p&&(m.current[o.id]=p);let D=m.current[i];if(!D){const f=v();D=c.editor.createModel(f,s),m.current[i]=D}u.current.setModel(D)}l(i,o),h(!0)}},[i,o,l,c,h,s,v]),L.useEffect(()=>{if(!c)return;const p=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",D=n==="system"?p:n;c.editor.defineTheme("default",{base:D==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":D==="light"?"#ffffff":t.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[a,n,c]),L.useEffect(()=>{const p=u.current;p&&c&&o&&p.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return d(),!1})},[c,d,o]);function C(p,D){if(u.current=p,!m.current[o.id]){const f=p.getModel(),j=v();m.current[o.id]=f||(D==null?void 0:D.editor.createModel(j,s))||p.getModel()}p.setModel(m.current[o.id])}return{handleEditorDidMount:C}}function _n(){const s=t.useEditorStore(c=>c.card.sql),a=t.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=t.useEditorActions(),{handleEditorDidMount:o}=Kt("sql");function i(c){n(c),t.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!s&&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(t.Ft,{theme:"default",className:"pt-3",onChange:i,value:s||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:o})]})}function Gn(){const s=t.useEditorStore(o=>o.card.python),{setCardPython:a}=t.useEditorActions(),{handleEditorDidMount:n}=Kt("python");function r(o){a(o)}return e.jsx(t.Ft,{className:"pt-3",theme:"default",onChange:r,value:s||t.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function $n({jsonString:s}){return e.jsx(t.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:s,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function Jn(){const s=t.useQueryClient(),[a,n]=L.useState(!1),[r,o]=L.useState(!1);t.useEditorStore(z=>z.frame);const i=t.useEditorStore(z=>z.card);t.useEditorStore(z=>z.isShowingVisual),t.useEditorStore(z=>z.selectedConnectionId),t.useEditorStore(z=>z.tempQueryData),t.useEditorStore(z=>z.selectedDatabaseName),t.useEditorStore(z=>z.selectedDatamodelId),t.useEditorStore(z=>z.selectedSchemaName);const c=t.useEditorStore(z=>z.showAIDialog);t.useEditorStore(z=>z.selectedTableName);const d=t.useEditorStore(z=>{var U;return(U=z==null?void 0:z.card)==null?void 0:U.sql}),l=t.useEditorStore(z=>{var U;return(U=z==null?void 0:z.card)==null?void 0:U.python}),{sheetFilterValues:h}=t.useSheetFilterValues(),{setCardCustomCfg:u,setQueryResultColumns:m,setCardSql:y,setTempQueryData:v,setPythonStdOut:C,setCardPreferences:p,setCardType:D,setCardPython:f,runAssistant:j,setShowAIDialog:O}=t.useEditorActions();t.useEditorStore(z=>z.onSave),t.useEditorStore(z=>z.onClose),t.useEditorStore(z=>z.actions.setSqlGen);const I=t.useEditorStore(z=>z.runSql),k=t.useEditorStore(z=>z.actions.setRunSql),N=t.useEditorStore(z=>z.actions.setIsSqlRunning),{data:S,isLoading:w,isFetching:E,isSuccess:g,isError:x,error:B,queryKey:A,refetch:T,errorMessage:b}=t.useDashboardCardQuery(i);L.useEffect(()=>{if(S&&(S.rowLimitExceeded&&t.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),C((S==null?void 0:S.output)||""),S.records.length>0)){const{dimensionKeys:z}=t.getKeys(S.records);m(z)}},[S,m,C]),L.useEffect(()=>{(w||E)&&N(!0),(x||g)&&N(!1),x&&(m([]),C(""))},[w,E,S,C,x,g,N,m,B]),L.useEffect(()=>{I&&(s.getQueryData(A)||T(),k(!1))},[I,T,k,A,s]);async function M(){const z=`Can you help me debug this query in the current table scope?
357
357
 
358
358
  Error:
359
359
 
@@ -365,11 +365,11 @@
365
365
 
366
366
  ${l?`Python:
367
367
  ${l}`:""}
368
- `;y(z)}function F(){return e.jsxs(e.Fragment,{children:[r&&e.jsx("div",{className:"relative flex w-1/3 min-w-0 grow overflow-hidden text-xs",role:"editor-filter-container",children:e.jsx("div",{className:"mt-2 w-[99%]",children:e.jsx($n,{jsonString:JSON.stringify(h,null,2)})})}),h&&h.length>0&&e.jsx(t.Button,{variant:"ghost",onClick:()=>o(!r),className:"absolute bottom-0 right-6 size-7 p-1",children:r?e.jsx(t.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(t.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function P(){return e.jsxs(t.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(t.ResizablePanel,{id:"1",order:1,defaultSize:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(_n,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(t.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(t.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(Gn,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function V(){return e.jsxs("div",{role:"editor-controls",className:"item-center flex flex-wrap justify-between gap-2 px-6 py-4",children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsxs(t.Button,{title:"Shift + Enter",disabled:w||E,onClick:()=>{T()},className:"h-8 shrink-0",size:"sm",children:[w||E?e.jsx(t.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(t.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(Jt,{sql:S==null?void 0:S.sql,error:b,onDebugWithAssistant:M}),e.jsx(t.EditorClearButton,{}),e.jsx(t.Toggle,{pressed:a,onPressedChange:z=>n(z),className:"",size:"sm",children:e.jsx(qn,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{O(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:c?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.EditorCancelButton,{}),e.jsx(t.EditorAcceptButton,{})]})]})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[P(),F()]}),V()]})}function Hn({data:s}){var c;const[a,n]=L.useState([]),o=Object.keys(s[0]).map(d=>({accessorKey:d,header:({column:l})=>{const h=l.getIsSorted();return e.jsx("div",{className:"flex gap-2",children:e.jsxs("div",{className:"flex cursor-pointer items-center",onClick:()=>l.toggleSorting(l.getIsSorted()==="asc"),children:[d,h==="asc"?e.jsx(t.TriangleUpIcon,{className:"ml-2 h-5 w-5"}):h==="desc"?e.jsx(t.TriangleDownIcon,{className:"ml-2 h-5 w-5"}):null]})})}})),i=t.useReactTable({data:s,columns:o,getCoreRowModel:t.getCoreRowModel(),getPaginationRowModel:t.getPaginationRowModel(),onSortingChange:n,getSortedRowModel:t.getSortedRowModel(),manualPagination:!0,state:{sorting:a}});return e.jsxs(t.CustomScrollArea,{className:"grow overflow-auto font-mono text-xs text-foreground/95",children:[e.jsxs("table",{className:"w-full",children:[e.jsx(t.TableHeader,{className:"sticky top-0 z-50 h-0 bg-muted",children:i.getHeaderGroups().map(d=>e.jsx(t.TableRow,{className:"",children:d.headers.map(l=>e.jsx(t.TableHead,{className:"h-11 font-semibold text-foreground",children:l.isPlaceholder?null:t.flexRender(l.column.columnDef.header,l.getContext())},l.id))},d.id))}),e.jsx(t.TableBody,{children:(c=i.getRowModel().rows)!=null&&c.length?i.getRowModel().rows.map(d=>e.jsx(t.TableRow,{className:"h-11 whitespace-nowrap py-2","data-state":d.getIsSelected()&&"selected",children:d.getVisibleCells().map(l=>e.jsx(t.TableCell,{className:"py-2",children:t.flexRender(l.column.columnDef.cell,l.getContext())},l.id))},d.id)):e.jsx(t.TableRow,{children:e.jsx(t.TableCell,{colSpan:o.length,className:"h-24 text-center",children:"No results."})})})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function Yn({card:s}){var y,O,I,k,N,S,w,E,g,x,B;const[a,n]=L.useState(!1),[r,o]=L.useState([]),{authToken:i}=t.useSemaphorContext(),c=t.getTokenParams(i==null?void 0:i.accessToken),d=t.useDashboardStore(A=>A.themeStyle),l={colors:((O=(y=d==null?void 0:d.chart)==null?void 0:y.dataset)==null?void 0:O.backgroundColor)||[]};(I=s.customCardPreferences)!=null&&I.inputData;const{getCard:h}=t.useCustomVisual(((k=s.customCardPreferences)==null?void 0:k.url)||""),u=((N=s.customCardPreferences)==null?void 0:N.visualType)||"single",m=t.useEditorStore(A=>A.frame),{setCustomCardPreferences:j}=t.useEditorActions(),{data:v}=t.useDashboardCardQuery(s),C=L.useCallback((A,T)=>{o(b=>({...b,[A]:T}))},[]);if(!((S=s.customCardPreferences)!=null&&S.componentName))return null;const p=h((w=s.customCardPreferences)==null?void 0:w.componentName);function D(A){n(A)}const f=Object.keys(((E=s.customCardPreferences)==null?void 0:E.dataInputCardIds)||{}).map(A=>{var M,F,P;const T=(F=(M=s.customCardPreferences)==null?void 0:M.dataInputCardIds)==null?void 0:F[A].cardId,b=(P=m==null?void 0:m.cards)==null?void 0:P.find(V=>V.id===T);return b||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(L.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[p&&u==="single"&&e.jsx(p,{params:c,theme:l,settings:(g=s.customCardPreferences)==null?void 0:g.settings,onDataChange:C,data:(v==null?void 0:v.records)||[]}),p&&u==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((x=s.customCardPreferences)==null?void 0:x.dataInputCardIds)||{}).map(A=>{var M,F,P;const T=(F=(M=s.customCardPreferences)==null?void 0:M.dataInputCardIds)==null?void 0:F[A].cardId,b=(P=m==null?void 0:m.cards)==null?void 0:P.find(V=>V.id===T);if(b)return e.jsx(t.MultiInputEmptyRenderer,{onLoadingStatus:D,onDataChange:C,dataInputIndex:A,card:b},b.id+A)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(p,{theme:l,onDataChange:C,settings:f.map(A=>{var T;return(T=A==null?void 0:A.customCardPreferences)==null?void 0:T.settings}),data:f.map(A=>A!=null&&A.id?r==null?void 0:r[A.id]:[])})})]})]},(B=s.customCardPreferences)==null?void 0:B.componentName)})}function Ut({className:s,...a}){var f;const n=t.useEditorStore(y=>y.card),r=((f=n.customCardPreferences)==null?void 0:f.showCardHeader)??!0,o=t.useEditorStore(y=>y.frame),i=t.useDashboardStore(y=>y.dashboard.filters);t.useEditorStore(y=>y.actions.setRunSql);const{updateFilter:c}=t.useDashboardActions(),d=i==null?void 0:i.find(y=>y.id===o.filterId),{data:l,isLoading:h,isFetching:u,errorMessage:m}=t.useDashboardCardQuery(n),{setCard:j}=t.useEditorActions(),{data:v}=t.useTopoJson(n),C=L.useMemo(()=>!n.id||!(l!=null&&l.records)?null:t.createChartConfig({card:n,data:l==null?void 0:l.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:v}),[n.id,l==null?void 0:l.records,n.type,n.queryConfig,n.customCfg,n.preferences,v]);function p(y){return e.jsx(Yn,{card:y})}function D(){if(l!=null&&l.records&&(l==null?void 0:l.records.length)===0&&!h&&!u)return m?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(t.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:n.mode!=="explorer"?"Error fetching data. Please check your SQL or Python code.":"Error fetching data. Please check your chart configuration"})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(t.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if(!n.id)return null;if(n.type==="custom")return p(n);if(!["table","custom"].includes(n.type)&&C)return e.jsx(e.Fragment,{children:h||u?e.jsx(e.Fragment,{}):e.jsx(t.ChartJsVisual,{cfg:C})});if(n.type==="table"&&(l!=null&&l.records)&&(l==null?void 0:l.records.length)>0)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(t.TableVisual,{card:n,data:l==null?void 0:l.records})})}return e.jsxs(t.Card,{role:"editor-visual-card",className:t.cn("relative flex h-full flex-col rounded-none",s),...a,children:[r&&e.jsxs(t.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{children:[e.jsx(t.Editable,{enabled:!0,text:n.title,onSave:y=>j({...n,title:y}),children:e.jsx("div",{className:"flex items-center gap-5",children:e.jsx(t.CardTitle,{className:"text-base",children:n.title||"Add title"})})},n.title),e.jsx(t.Editable,{enabled:!0,text:n.description||"",onSave:y=>j({...n,description:y}),children:e.jsx(t.CardDescription,{children:n.description||"Add description"})},n.description)]}),d&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Editable,{enabled:!0,className:"my-1",text:d.title||d.column,onSave:y=>c({...d,title:y}),children:e.jsx(t.Label,{children:d.title})}),e.jsx(t.FilterComponent,{filter:d})]})]}),e.jsx(t.CardContent,{className:"flex grow flex-col",children:D()})]})}const qe=({language:s,value:a,onChange:n,readonly:r})=>e.jsx(t.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:s,value:a,onChange:n}),Kn=()=>e.jsxs(t.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(t.DialogTitle,{children:"Customize Card"})}),e.jsxs(t.DialogDescription,{children:["See the configuration options and documentation",e.jsx("a",{target:"_blank",className:"ml-1 text-blue-500 underline",href:"https://www.chartjs.org/docs/latest/samples/bar/vertical.html",children:"here."})]})]}),Un=({customCode:s,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:o})=>e.jsxs(t.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(t.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(t.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(t.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(t.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(t.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(qe,{language:"json",value:n,onChange:r})}),e.jsx(t.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(qe,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(t.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(qe,{language:"javascript",value:s,onChange:o})})]}),Qn=({error:s,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:o})=>e.jsxs(t.DialogFooter,{className:"flex items-center",children:[e.jsx(t.Label,{className:"mr-2 text-red-500",children:s}),e.jsx(t.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(t.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(t.Button,{onClick:o,variant:"outline",children:"Close"})]});function Wn(){const[s,a]=L.useState(!1),[n,r]=L.useState(""),[o,i]=L.useState(""),[c,d]=L.useState(""),[l,h]=L.useState(""),u=t.useEditorStore(k=>k.card),m=t.useEditorStore(k=>k.card.customCfg),j=m?JSON.stringify(m,null,2):"",{data:v}=t.useDashboardCardQuery(u),{data:C}=t.useTopoJson(u),{setCardCustomCfg:p,setCustomVisualCode:D}=t.useEditorActions(),f=k=>{var N,S;return JSON.stringify({...k,data:{...k.data,datasets:(S=(N=k.data)==null?void 0:N.datasets)==null?void 0:S.map(w=>({...w,data:[]}))}},null,2)},y=()=>{var N,S;if(!((N=v==null?void 0:v.records)!=null&&N.length))return;const k=t.createChartConfig({card:u,data:v.records,cardType:u.type,queryConfig:u.queryConfig,preferences:u.preferences,topoJson:C});if(k){r(f(k)),d(((S=u.preferences)==null?void 0:S.customVisualCode)||"");const w=t.merge(k,m);i(f(w))}},O=()=>{try{if(c&&D(c),o){const k=JSON.parse(o),N=t.getObjectDiff(JSON.parse(n),k);p(N),h("")}}catch{h("Invalid JSON configuration")}},I=Object.keys(m||{}).length===0;return e.jsxs(t.Dialog,{open:s,onOpenChange:a,children:[e.jsx(t.DialogTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Customize Visual",onClick:y,className:I?"":"text-green-600 hover:text-green-700",children:e.jsx(t.Settings,{className:"h-4 w-4"})})}),e.jsxs(t.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(Kn,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackEditorCard,children:e.jsx(Ut,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Un,{customCode:c,cardCustomCfgString:j,mergedConfig:o,onConfigChange:k=>i(k??""),onCodeChange:k=>d(k??"")})]}),e.jsx(Qn,{error:l,hasCardCustomConfig:!!m,onReset:()=>{i(n),p(null)},onApply:O,onClose:()=>a(!1)})]})]})}function Qt(s){const[a,n]=L.useState(null);return a}function Wt(){const{authToken:s}=t.useSemaphorContext(),{data:a,isLoading:n,isFetching:r,isError:o}=t.useQuery({queryKey:["plugins",s==null?void 0:s.accessToken],queryFn:()=>t.getPlugins(s==null?void 0:s.accessToken)});return{data:a,isLoading:n,isFetching:r,isError:o}}function Xn({onChartTypeChange:s}){const[a,n]=L.useState([]),{setCardCustomCfg:r,setCardPreferences:o,setCardType:i,setCustomCardPreferences:c}=t.useEditorActions(),{data:d}=Wt();function l(h,u){r(null),o({}),i(h),u&&c({type:"component",visualType:"single",url:u.url,componentName:u.name,icon:u.icon}),s==null||s()}return L.useEffect(()=>{(async()=>{var u;if(d){const j=(await Promise.all((u=d==null?void 0:d.plugins)==null?void 0:u.map(async v=>(await t.loadManifest(v.value)).visuals.map(D=>({name:D.name,icon:D.icon,url:v.value}))))).flat();n(j)}})()},[d]),a.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(t.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:a.map((h,u)=>e.jsx(Zn,{text:h.name,onClick:()=>l("custom",h),icon:h.icon},h.url+h.name+u))})]})}const Zn=({text:s,icon:a,onClick:n})=>{const r=Qt(),o=s.charAt(0).toUpperCase();return e.jsx(t.IconButton,{onClick:n,tooltip:s,children:r?e.jsx(r,{className:"h-4 w-4"}):o})};function it(s){return ge({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm87.63,96H191.48A64.1,64.1,0,0,0,136,64.52V40.37A88.13,88.13,0,0,1,215.63,120ZM120,120H80.68A48.09,48.09,0,0,1,120,80.68Zm0,16v39.32A48.09,48.09,0,0,1,80.68,136Zm16,0h39.32A48.09,48.09,0,0,1,136,175.32Zm0-16V80.68A48.09,48.09,0,0,1,175.32,120ZM120,40.37V64.52A64.1,64.1,0,0,0,64.52,120H40.37A88.13,88.13,0,0,1,120,40.37ZM40.37,136H64.52A64.1,64.1,0,0,0,120,191.48v24.15A88.13,88.13,0,0,1,40.37,136ZM136,215.63V191.48A64.1,64.1,0,0,0,191.48,136h24.15A88.13,88.13,0,0,1,136,215.63Z"},child:[]}]})(s)}function ea(s){return ge({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M48,180c0,11,7.18,20,16,20a14.24,14.24,0,0,0,10.22-4.66A8,8,0,0,1,85.78,206.4,30.06,30.06,0,0,1,64,216c-17.65,0-32-16.15-32-36s14.35-36,32-36a30.06,30.06,0,0,1,21.78,9.6,8,8,0,0,1-11.56,11.06A14.24,14.24,0,0,0,64,160C55.18,160,48,169,48,180Zm79.6-8.69c-4-1.16-8.14-2.35-10.45-3.84-1.25-.81-1.23-1-1.12-1.9a4.57,4.57,0,0,1,2-3.67c4.6-3.12,15.34-1.73,19.82-.56A8,8,0,0,0,142,145.86c-2.12-.55-21-5.22-32.84,2.76a20.58,20.58,0,0,0-9,14.95c-2,15.88,13.65,20.41,23,23.11,12.06,3.49,13.12,4.92,12.78,7.59-.31,2.41-1.26,3.34-2.14,3.93-4.6,3.06-15.17,1.56-19.55.36A8,8,0,0,0,109.94,214a61.34,61.34,0,0,0,15.19,2c5.82,0,12.3-1,17.49-4.46a20.82,20.82,0,0,0,9.19-15.23C154,179,137.49,174.17,127.6,171.31Zm83.09-26.84a8,8,0,0,0-10.23,4.84L188,184.21l-12.47-34.9a8,8,0,0,0-15.07,5.38l20,56a8,8,0,0,0,15.07,0l20-56A8,8,0,0,0,210.69,144.47ZM216,88v24a8,8,0,0,1-16,0V96H152a8,8,0,0,1-8-8V40H56v72a8,8,0,0,1-16,0V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88Zm-27.31-8L160,51.31V80Z"},child:[]}]})(s)}function lt(s){return ge({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M6 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"},child:[]},{tag:"path",attr:{d:"M16 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"},child:[]},{tag:"path",attr:{d:"M14.5 7.5m-4.5 0a4.5 4.5 0 1 0 9 0a4.5 4.5 0 1 0 -9 0"},child:[]}]})(s)}function ct(s){return ge({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4.387 3h15.226a1 1 0 0 1 .948 1.316l-5.105 15.316a2 2 0 0 1 -1.898 1.368h-3.116a2 2 0 0 1 -1.898 -1.368l-5.104 -15.316a1 1 0 0 1 .947 -1.316"},child:[]},{tag:"path",attr:{d:"M5 9h14"},child:[]},{tag:"path",attr:{d:"M7 15h10"},child:[]}]})(s)}function dt(s){return ge({attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"m2 19.99 7.5-7.51 4 4 7.09-7.97L22 9.92l-8.5 9.56-4-4-6 6.01-1.5-1.5zm1.5-4.5 6-6.01 4 4L22 3.92l-1.41-1.41-7.09 7.97-4-4L2 13.99l1.5 1.5z"},child:[]}]})(s)}function ut(s){return ge({attr:{version:"1.2",baseProfile:"tiny",viewBox:"0 0 24 24"},child:[{tag:"path",attr:{d:"M4 18c-.552 0-1-.448-1-1v-6.382l-.553.276c-.495.248-1.095.046-1.342-.447-.247-.494-.046-1.094.448-1.342l2-1c.31-.155.678-.139.973.044.294.183.474.504.474.851v8c0 .552-.448 1-1 1zM13 18h-5c-.404 0-.769-.244-.924-.617-.155-.374-.069-.804.217-1.09l4-4c.254-.254.394-.591.394-.95 0-.358-.14-.695-.394-.949-.508-.508-1.39-.508-1.9.001-.253.252-.393.589-.393.948 0 .552-.448 1-1 1s-1-.448-1-1c0-.894.348-1.733.98-2.364 1.265-1.263 3.464-1.263 4.727.001.632.631.979 1.471.979 2.363 0 .893-.348 1.733-.979 2.364l-2.293 2.293h2.586c.552 0 1 .448 1 1s-.448 1-1 1zM20.955 12.377c.338-.457.545-1.016.545-1.627 0-1.517-1.234-2.75-2.75-2.75-1.031 0-1.966.569-2.44 1.484-.254.49-.063 1.094.428 1.348.49.254 1.094.062 1.348-.428.128-.249.383-.404.664-.404.414 0 .75.336.75.75s-.336.75-.75.75c-.552 0-1 .448-1 1s.448 1 1 1c.689 0 1.25.561 1.25 1.25s-.561 1.25-1.25 1.25-1.25-.561-1.25-1.25c0-.552-.448-1-1-1s-1 .448-1 1c0 1.792 1.458 3.25 3.25 3.25s3.25-1.458 3.25-3.25c0-.939-.406-1.779-1.045-2.373z"},child:[]}]})(s)}function Xt({onChartTypeChange:s,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:o}=t.useEditorStore(u=>u.actions),{setCardCustomCfg:i,setCustomCardPreferences:c,setQueryConfig:d}=t.useEditorActions();function l(u,m){i(null),r({}),n(u),["custom","text","map"].includes(u)&&(o(!0),d(void 0)),s==null||s()}const h=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(t.IconButton,{openDelay:h,tooltip:"Table",onClick:()=>l("table"),className:"h-10 p-4",children:e.jsx(Oe,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Bar Chart",onClick:()=>l("bar"),className:"h-10 p-4",children:e.jsx(Ae,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Line Chart",onClick:()=>l("line"),className:"h-10 p-4",children:e.jsx(Le,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Stacked Bar Chart",onClick:()=>l("stackedBar"),className:"h-10 p-4",children:e.jsx(Ke,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Stacked Line Chart",onClick:()=>l("stackedLine"),className:"h-10 p-4",children:e.jsx(dt,{className:t.cn("size-5",a),strokeWidth:0})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Scatter Chart",onClick:()=>l("scatter"),className:"h-10 p-4",children:e.jsx(We,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Bubble Chart",onClick:()=>l("bubble"),className:"h-10 p-4",children:e.jsx(lt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Pie Chart",onClick:()=>l("pie"),className:"h-10 p-4",children:e.jsx(Qe,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Doughnut Chart",onClick:()=>l("doughnut"),className:"h-10 p-4",children:e.jsx(Xe,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Funnel Chart",onClick:()=>l("funnel"),className:"h-10 p-4",children:e.jsx(ct,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Radar Chart",onClick:()=>l("radar"),className:"h-10 p-4",children:e.jsx(tt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Polar Area Chart",onClick:()=>l("polarArea"),className:"h-10 p-4",children:e.jsx(it,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Tornado Chart",onClick:()=>l("tornado"),className:"h-10 p-4",children:e.jsx(nt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{tooltip:"Range Chart",onClick:()=>l("range"),className:"h-10 p-4",children:e.jsx(Ue,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"KPI",onClick:()=>l("kpi"),className:"h-10 p-4",children:e.jsx(ut,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Text",onClick:()=>l("text"),className:"h-10 p-4",children:e.jsx(Tt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{tooltip:"Map",onClick:()=>l("map"),className:"h-10 p-4",children:e.jsx(et,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Custom",onClick:()=>l("custom"),className:"h-10 p-4",children:e.jsx(st,{className:t.cn("size-5",a)})})]})}function ta({chartType:s,className:a,customIcon:n,componentName:r}){const o=Qt();switch(s){case"bar":return e.jsx(Ae,{className:a});case"line":return e.jsx(Le,{className:a});case"pie":return e.jsx(Qe,{className:a});case"radar":return e.jsx(tt,{className:a});case"scatter":return e.jsx(We,{className:a});case"bubble":return e.jsx(lt,{className:a});case"doughnut":return e.jsx(Xe,{className:a});case"stackedBar":return e.jsx(Ke,{className:a});case"stackedLine":return e.jsx(dt,{className:a});case"polarArea":return e.jsx(it,{className:a});case"funnel":return e.jsx(ct,{className:a});case"tornado":case"pyramid":return e.jsx(nt,{className:a});case"range":return e.jsx(Ue,{className:a});case"kpi":return e.jsx(ut,{className:a});case"text":return e.jsx(Ft,{className:a});case"map":return e.jsx(et,{className:a});case"custom":return n&&o?e.jsx(o,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(st,{className:a});default:return e.jsx(Oe,{className:a})}}function Zt({variant:s="ghost"}){var i,c;const[a,n]=L.useState(!1),r=t.useEditorStore(d=>d.card),o=r.type;return t.useDashboardStore(d=>d.isVisualEditing),e.jsxs(t.Popover,{open:a,onOpenChange:n,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{size:"sm",variant:s||"ghost",children:e.jsx(ta,{className:"size-4",chartType:o,customIcon:(i=r.customCardPreferences)==null?void 0:i.icon,componentName:(c=r.customCardPreferences)==null?void 0:c.componentName})})}),e.jsxs(t.PopoverContentCustom,{onOpenAutoFocus:d=>d.preventDefault(),className:"w-72 p-1",children:[e.jsx(Xt,{onChartTypeChange:()=>n(!1)}),e.jsx(Xn,{onChartTypeChange:()=>n(!1)})]})]})}const Se="focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0";function kt(s,a){var r,o,i;const n=t.getNumberAxis(s,{});return["pie","doughnut","polarArea","funnel"].includes(a)?"category":((i=(o=(r=s==null?void 0:s.chartOptions)==null?void 0:r.scales)==null?void 0:o[n])==null?void 0:i.type)||"linear"}function sa(){var M,F,P,V,z,U;const[s,a]=L.useState(!1),n=t.useEditorStore(R=>{var q;return(q=R.card)==null?void 0:q.preferences}),r=t.useEditorStore(R=>{var q;return(q=R.card)==null?void 0:q.type}),o=t.getNumberAxis(n,{}),[i,c]=L.useState(kt(n,r)),[d,l]=L.useState(((P=(F=(M=n==null?void 0:n.chartOptions)==null?void 0:M.scales)==null?void 0:F[o])==null?void 0:P.min)||""),[h,u]=L.useState(((U=(z=(V=n==null?void 0:n.chartOptions)==null?void 0:V.scales)==null?void 0:z[o])==null?void 0:U.max)||""),[m,j]=L.useState(d||h?"custom":"auto"),[v,C]=L.useState(""),[p,D]=L.useState(0),[f,y]=L.useState(""),[O,I]=L.useState(""),[k,N]=L.useState(""),S=t.useEditorStore(R=>R.actions.setCardPreferences),{updateCardInFrame:w}=t.useEditorActions(),E=t.useEditorStore(R=>R.card),g=["pie","doughnut","polarArea","funnel"].includes(r);L.useEffect(()=>{var R,q,H,Q,G,$,J,X,te,ne,le,oe,ce,ie;c(kt(n,r)),l(((H=(q=(R=n==null?void 0:n.chartOptions)==null?void 0:R.scales)==null?void 0:q[o])==null?void 0:H.min)===0?0:""),u((($=(G=(Q=n==null?void 0:n.chartOptions)==null?void 0:Q.scales)==null?void 0:G[o])==null?void 0:$.max)||""),C(((ne=(te=(X=(J=n==null?void 0:n.chartOptions)==null?void 0:J.scales)==null?void 0:X[o])==null?void 0:te.ticks)==null?void 0:ne.stepSize)||""),D(((le=n==null?void 0:n.numberAxisFormat)==null?void 0:le.decimalPlaces)||0),y(((oe=n==null?void 0:n.numberAxisFormat)==null?void 0:oe.suffix)||""),I(((ce=n==null?void 0:n.numberAxisFormat)==null?void 0:ce.currency)||""),N(((ie=n==null?void 0:n.numberAxisFormat)==null?void 0:ie.locale)||"")},[s,n,o,r]);function x(R,q){return q===""||/^[0-9\b]+$/.test(q)?Number(q):Number(R)}function B(){const R=[...new Set(t.LOCALE_CURRENCY_PAIRS.map(q=>q.currency))];return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-6 items-center gap-2",children:[e.jsx(t.Label,{className:"col-span-2 hover:cursor-pointer hover:underline",htmlFor:"currency",children:e.jsx("a",{target:"_blank",href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat",children:"Currency"})}),e.jsxs(t.Select,{value:O||"none",onValueChange:q=>I(q==="none"?"":q),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Currency"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),R.map(q=>e.jsx(t.SelectItem,{value:q,children:q},q))]})})]}),e.jsxs(t.Select,{value:k,onValueChange:q=>N(q),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Locale"}),t.LOCALE_CURRENCY_PAIRS.map(q=>e.jsx(t.SelectItem,{value:q.locale,children:q.locale},q.locale))]})})]})]}),e.jsxs("div",{className:"grid grid-cols-9 items-center gap-2",children:[e.jsx(t.Label,{className:"col-span-3",htmlFor:"format",children:"Decimals"}),e.jsx(t.Input,{value:p,onChange:q=>D(Number(q.target.value)),id:"format",className:`col-span-6 h-8 w-full tracking-wide ${Se}`})]})]})}function A(){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-4 space-y-2",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the scale for number axis"})}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"scale",children:"Type"}),e.jsxs(t.Select,{disabled:g,value:i,onValueChange:R=>c(R),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{id:"type",children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Option"}),e.jsx(t.SelectItem,{value:"linear",children:"Linear"}),e.jsx(t.SelectItem,{value:"logarithmic",children:"Logarithmic"}),e.jsx(t.SelectItem,{value:"category",children:"Category"})]})})]})]}),i=="linear"&&e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2 py-1",children:[e.jsx(t.Label,{htmlFor:"scale-option",children:"Setup"}),e.jsxs(t.RadioGroup,{disabled:g,id:"scale-option",value:m,onValueChange:R=>j(R),className:"col-span-2 flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"auto",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Auto"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"custom",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Custom"})]})]})]}),m==="custom"&&i=="linear"&&T()]})}function T(){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"range",children:"Range"}),e.jsx(t.Input,{id:"min",value:d,onChange:R=>l(q=>x(q,R.target.value)),className:`col-span-1 h-8 w-full ${Se}`}),e.jsx(t.Input,{value:h,onChange:R=>u(q=>x(q,R.target.value)),id:"max",className:`col-span-1 h-8 w-full ${Se}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"step-size",children:"Step Size"}),e.jsx(t.Input,{value:v,onChange:R=>C(q=>x(q,R.target.value)),id:"step-size",className:`col-span-1 h-8 w-full ${Se}`})]})]})}function b(){var Q;let R={};m==="custom"&&(R={min:d,max:h,ticks:{stepSize:v}});const q={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,scales:{...(Q=n==null?void 0:n.chartOptions)==null?void 0:Q.scales,[o]:{type:i,...i==="linear"?R:{}}}},numberAxisFormat:{decimalPlaces:p,suffix:f,currency:O,locale:k}};console.log(q),S(q);const H={...E,preferences:q};w(H)}return e.jsxs(t.Popover,{onOpenChange:R=>a(R),children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Format Number",children:e.jsx(Hs,{className:"size-4"})})}),e.jsx(t.PopoverContentCustom,{align:"end",className:"max-w-65",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Format Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the format for number axis"})]}),e.jsxs("div",{className:"grid gap-2",children:[B(),A(),e.jsx(t.SelectSeparator,{}),e.jsx("div",{className:"grid grid-cols-3",children:e.jsx(t.Button,{onClick:b,variant:"secondary",className:"col-span-1 col-start-3 h-8 w-full",children:"Apply"})})]})]})})]})}function na(){const s=t.useEditorStore(d=>{var l,h,u,m;return(m=(u=(h=(l=d.card.preferences)==null?void 0:l.chartOptions)==null?void 0:h.plugins)==null?void 0:u.legend)==null?void 0:m.position}),a=t.useEditorStore(d=>{var l,h,u,m;return(m=(u=(h=(l=d.card.preferences)==null?void 0:l.chartOptions)==null?void 0:h.plugins)==null?void 0:u.legend)==null?void 0:m.align}),n=t.useEditorStore(d=>{var l,h,u,m;return(m=(u=(h=(l=d.card.preferences)==null?void 0:l.chartOptions)==null?void 0:h.plugins)==null?void 0:u.legend)==null?void 0:m.display}),{setLegendOptions:r}=t.useEditorActions(),o=d=>{r({display:d,position:s,align:a})},i=d=>{r({display:n,position:d,align:a})},c=d=>{r({display:n,position:s,align:d})};return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Legend Settings",children:e.jsx(tn,{className:"size-4"})})}),e.jsx(t.PopoverContentCustom,{align:"end",className:"w-72",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Legend Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the legend options for the chart."})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"displayLegend",children:"Display"}),e.jsx("div",{className:"col-span-2 flex h-8 items-center",children:e.jsx(t.SmallSwitch,{checked:n,onCheckedChange:o,id:"displayLegend"})})]}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"position",children:"Position"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(t.IconButton,{tooltip:"Top",onClick:()=>i("top"),children:e.jsx(t.ArrowUp,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Left",onClick:()=>i("left"),children:e.jsx(Ms,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Bottom",onClick:()=>i("bottom"),children:e.jsx(t.ArrowDown,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Right",onClick:()=>i("right"),children:e.jsx(As,{className:"size-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"align",children:"Align"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(t.IconButton,{tooltip:"Start",onClick:()=>c("start"),children:e.jsx(ks,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Center",onClick:()=>c("center"),children:e.jsx(ws,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"End",onClick:()=>c("end"),children:e.jsx(Es,{className:"size-4"})})]})]})]})]})]})})]})}function aa(){const s=t.useEditorStore(i=>{var c,d;return(d=(c=i.card.preferences)==null?void 0:c.chartOptions)==null?void 0:d.indexAxis}),a=t.useEditorStore(i=>i.card.type),{setChartOrientation:n}=t.useEditorStore(i=>i.actions);function r(){return e.jsx(t.IconButton,{onClick:()=>{n(s==="x"||s===void 0?"y":"x")},tooltip:"Chart Orientation",children:s==="x"||s===void 0?e.jsx(vt,{className:"size-4"}):e.jsx(bt,{className:"size-4"})})}function o(){return e.jsx(t.IconButton,{onClick:()=>{n(s==="y"||s===void 0?"x":"y")},tooltip:"Chart Orientation",children:s==="y"||s===void 0?e.jsx(vt,{className:"size-4"}):e.jsx(bt,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?o():r()})}function es(){const s=t.useEditorStore(c=>c.card),a=t.useEditorStore(c=>c.isShowingVisual),n=t.useEditorStore(c=>{var d,l;return(l=(d=c.card)==null?void 0:d.preferences)==null?void 0:l.chartOptions}),r=t.getChartGridStyle(n),{setChartGrid:o}=t.useEditorActions();function i(){const c=["xy","none","x","y"],l=(c.indexOf(r)+1)%c.length;o(c[l])}return a?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(s.type)&&e.jsx(e.Fragment,{children:e.jsx(aa,{})}),!["kpi","text","custom","table"].includes(s.type)&&e.jsxs(e.Fragment,{children:[e.jsx(sa,{}),e.jsx(na,{})]}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(s.type)&&e.jsxs(t.IconButton,{tooltip:"Grid Style",onClick:i,children:[(r==="xy"||!r)&&e.jsx(Zs,{className:"size-4"}),r==="x"&&e.jsx(Gs,{className:"size-4"}),r==="y"&&e.jsx(xn,{className:"size-4"}),r==="none"&&e.jsx(jn,{className:"size-4"})]})]}):null}function ra(){const s=t.useEditorStore(C=>C.frame),a=t.useEditorStore(C=>C.card),{setFrame:n,setActiveTabCardId:r,setCard:o,updateCardInFrame:i}=t.useEditorActions(),c=(C,p)=>{C.dataTransfer.setData("tabIndex",p.toString())},d=C=>{C.preventDefault()},l=(C,p)=>{const D=C.dataTransfer.getData("tabIndex");if(D===p.toString())return;const f=Array.from(s.cards),[y]=f.splice(parseInt(D),1);f.splice(p,0,y),n({...s,cards:f})};function h(C){const p=s.cards.filter(y=>y.id!==C),D=p[0],f={...s,cards:p,activeCardId:D.id};n(f),r(D.id),o(D)}function u(C,p){const D={...s,cards:[...s.cards,p],activeCardId:C.id};n(D),r(p.id)}function m(){const C={...a,id:t.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};u(a,C)}function j(C){const p={connectionId:C.connectionId,lastSelectedDatabase:C.lastSelectedDatabase,lastSelectedSchema:C.lastSelectedSchema,lastSelectedTable:C.lastSelectedTable,lastSelectedDatamodelId:C.lastSelectedDatamodelId,id:t.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]};u(C,p)}function v(C,p){return C.cards.length===1&&(p.displayTab===!0||p.displayTab===void 0)||C.activeCardId!==p.id&&(p.displayTab===!0||p.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const D=p.displayTab===void 0?!1:!p.displayTab;o({...p,displayTab:D}),i({...p,displayTab:D})},children:p.displayTab===!0||p.displayTab===void 0?e.jsx(t.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(Ys,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(t.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[s.cards.map((C,p)=>e.jsxs(t.TabsTrigger,{draggable:!0,onDragStart:D=>c(D,p),onDragOver:d,onDrop:D=>l(D,p),className:"",value:C.id,children:[v(s,C),e.jsx(t.Editable,{enabled:s.activeCardId===C.id,text:C.tabTitle||C.title,onSave:D=>{o({...a,tabTitle:D}),i({...a,tabTitle:D})},children:C.tabTitle||C.title},C.id),s.activeCardId===C.id&&s.cards.length>1&&e.jsx(t.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>h(C.id)})]},C.id)),e.jsx(t.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>j(a),children:e.jsx(t.Plus,{className:"h-4 w-4"})}),e.jsx(t.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:m,children:e.jsx(Js,{className:"h-4 w-4"})})]})})}function ts(){const s=t.useEditorStore(p=>p.frame),a=t.useEditorStore(p=>p.card),n=t.useEditorStore(p=>p.isSqlRunning),r=t.useEditorStore(p=>p.isDevMode),{setFrame:o,setActiveTabCardId:i,setCard:c,setIsDevMode:d,setRunSql:l}=t.useEditorActions(),{data:h,isLoading:u,isFetching:m}=t.useDashboardCardQuery(a);function j(p){const D=s.cards.find(f=>f.id===p);if(D!=null&&D.sql){r||d(!0),i(p);return}if(D!=null&&D.queryConfig){r&&d(!1),v(p),i(p);return}r||v(p),i(p)}function v(p){const D={...s,cards:s.cards.map(y=>y.id===a.id?a:y),activeCardId:p};o(D);const f=D.cards.find(y=>y.id===p);f.sql&&l(!0),c(f)}function C(){return a.type==="kpi"?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(t.KPICard,{card:a,data:h==null?void 0:h.records,isPending:u})})}):a.type==="text"?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(t.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(t.TextCard,{isLoading:n,card:a,data:h==null?void 0:h.records})})})}):e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackEditorCard,children:e.jsx(Ut,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:j,value:s.activeCardId,className:"flex grow flex-col",children:[s.cards.map(p=>e.jsx(t.TabsContent,{className:"mt-0 grow",value:p.id,children:C()},p.id)),e.jsx(ra,{})]})}function we({children:s}){t.useEditorStore(y=>y.frame);const a=t.useEditorStore(y=>y.card),n=t.useEditorStore(y=>y.isDevMode),r=t.useEditorStore(y=>y.isShowingVisual),o=t.useDashboardStore(y=>y.isVisualEditing),i=t.useEditorStore(y=>y.pythonStdOut);t.useEditorStore(y=>y.actions.setRunSql);const{setFrame:c,setCard:d,setActiveTabCardId:l,runAssistant:h,setIsDevMode:u}=t.useEditorActions(),{data:m,isLoading:j,isFetching:v,errorMessage:C}=t.useDashboardCardQuery(a);function p(){const y=JSON.stringify(m==null?void 0:m.records,null,2),O=new Blob([y],{type:"application/json"}),I=URL.createObjectURL(O),k=document.createElement("a");k.href=I,k.download=`${a.title}.json`,k.click()}function D(){const O=[Object.keys(m==null?void 0:m.records.reduce((S,w)=>({...S,...w}),{})).join(","),...((m==null?void 0:m.records)||[]).map(S=>Object.values(S).join(","))].join(`
369
- `),I=new Blob([O],{type:"text/csv"}),k=URL.createObjectURL(I),N=document.createElement("a");N.href=k,N.download=`${a.title}.csv`,N.click()}function f(){const y=`Can you get the documentation for ${a.type} chart?`;h(y)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[(j||v)&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 top-0 z-50 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(t.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(Zt,{}),o&&e.jsx(t.IconButton,{tooltip:"Visual Docs",onClick:f,children:e.jsx(Fs,{className:"size-4"})}),!["table","custom"].includes(a.type)&&o&&e.jsx(Wn,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(t.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:D,children:e.jsx(ea,{className:"size-4"})}),e.jsx(t.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:p,children:e.jsx(Us,{strokeWidth:1.5,className:"size-4"})}),e.jsx(t.CopyButton,{text:JSON.stringify(m==null?void 0:m.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[s,e.jsx(es,{})]}),n&&e.jsx(ia,{})]}),r?e.jsx(ts,{}):e.jsxs(t.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[i&&e.jsxs(e.Fragment,{children:[e.jsx(t.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:i&&e.jsx(oa,{})}),e.jsx(t.ResizableHandle,{})]}),e.jsxs(t.ResizablePanel,{id:"2",order:2,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:[(m==null?void 0:m.records)&&(m==null?void 0:m.records.length)>0&&e.jsx(Hn,{data:(m==null?void 0:m.records)||[]}),C&&e.jsx(Gt,{error:C})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function oa(){const s=t.useEditorStore(n=>n.pythonStdOut);if(!s)return null;const a=s.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col border-r",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center border-b bg-muted px-3 font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(t.ScrollArea,{className:"overflow-y-auto px-2 pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function ia(){const s=t.useEditorStore(n=>n.isShowingVisual),a=t.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(t.SmallSwitch,{checked:s,onCheckedChange:()=>a(!s),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function la(){var p,D;const s=t.useEditorStore(f=>f.card.customCardPreferences),{data:a}=Wt(),n=(a==null?void 0:a.plugins)||[],r=t.useEditorStore(f=>f.card),o=t.useEditorStore(f=>f.frame),i=(s==null?void 0:s.visualType)||"single",{setCustomCardPreferences:c}=t.useEditorActions(),{components:d,manifest:l}=t.useCustomVisual((s==null?void 0:s.url)||""),h=(p=l==null?void 0:l.visuals)==null?void 0:p.find(f=>f.name===(s==null?void 0:s.componentName));function u(f,y){if(!s)return;const I={...(s==null?void 0:s.dataInputCardIds)||{},[f]:{cardId:y,hookRef:null}};c({...s,dataInputCardIds:I})}function m(f){var O,I;const y=(O=o==null?void 0:o.cards)==null?void 0:O.filter(k=>{var N;return((N=k==null?void 0:k.customCardPreferences)==null?void 0:N.visualType)!=="multiple"}).map(k=>({value:k.id,label:k.tabTitle||k.title}));return e.jsx("div",{className:"space-y-2",children:(I=f==null?void 0:f.dataInputs)==null?void 0:I.map((k,N)=>{var S,w;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:k}),e.jsx(se,{className:"col-span-6 h-8 w-full justify-between",label:"",options:y||[],value:((w=(S=s==null?void 0:s.dataInputCardIds)==null?void 0:S[N])==null?void 0:w.cardId)||"",onValueChange:E=>u(N,E)})]},N+Math.random())})})}function j(f,y,O=[],I=""){var k,N;return s?f==="input"?e.jsx(t.Input,{className:`h-8 w-full ${t.removeRing}`,value:((k=s==null?void 0:s.settings)==null?void 0:k[y])||I,onChange:S=>{c({...s,settings:{...s==null?void 0:s.settings,[y]:S.target.value}})}},y):f==="select"?e.jsx(se,{className:"h-8 w-full",label:"",options:O,value:((N=s==null?void 0:s.settings)==null?void 0:N[y])||I,onValueChange:S=>{c({...s,settings:{...s==null?void 0:s.settings,[y]:S}})}}):null:null}function v(f){const y=Object.entries((f==null?void 0:f.settings)||{});return e.jsx("div",{className:"space-y-3",children:y.map(([O,I])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:I.title}),j(I.ui,O,I.options,I.defaultValue)]},O))})}function C(f){s&&c({...s,visualType:f,componentName:""})}return e.jsxs(t.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(t.AccordionItem,{value:"plugin-settings",children:[e.jsx(t.AccordionTrigger,{children:"Plugin"}),e.jsx(t.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(se,{icon:e.jsx(Bs,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(s==null?void 0:s.url)||"",onValueChange:f=>c({...s||{url:"",componentName:""},url:f})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&e.jsx(t.Tabs,{value:i,onValueChange:C,children:e.jsxs(t.TabsList,{className:"h-9 w-full",children:[e.jsx(t.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(t.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&s&&e.jsx(e.Fragment,{children:d&&e.jsx(se,{icon:e.jsx($s,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(d==null?void 0:d.filter(f=>f.type===i).map(f=>({value:f.name,label:f.name})))||[],value:s.componentName,onValueChange:f=>{console.log("changing value",f),c({...s,componentName:f})}})})]})})]}),((D=r==null?void 0:r.customCardPreferences)==null?void 0:D.componentName)&&e.jsxs(t.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{children:[h&&h.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:m(h)})]}),h&&h.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:v(h)})})]})]})]})}function je(){const[s,a]=L.useState([]),n=t.useEditorStore(h=>h.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:o}=t.useEditorStore(h=>h.actions),i=t.useEditorStore(h=>h.queryResultColumns);t.useEditorStore(h=>{var u;return(u=h.card.preferences)==null?void 0:u.filterOnClickColumnIndex}),L.useEffect(()=>{i&&a(new Array(i.length).fill(!1))},[i]);function c(h,u){var m,j;u?n!=null&&n.onClickFilter&&((m=n==null?void 0:n.onClickFilter)==null?void 0:m.length)>0?o({...n,onClickFilter:[...n.onClickFilter,{columnIndex:h,expression:""}]}):o({...n,onClickFilter:[{columnIndex:h,expression:""}]}):(o({...n,onClickFilter:(j=n==null?void 0:n.onClickFilter)==null?void 0:j.filter(v=>v.columnIndex!==h)}),a(v=>{const C=[...v];return C[h]=!1,C}))}function d(h,u){var j;const m=(j=n==null?void 0:n.onClickFilter)==null?void 0:j.map(v=>v.columnIndex===h?{...v,expression:u.target.value}:v);o({...n,onClickFilter:m})}function l(h){var u,m,j,v;if(s!=null&&s[h]||(m=(u=n==null?void 0:n.onClickFilter)==null?void 0:u.find(C=>C.columnIndex===h))!=null&&m.expression)return e.jsx(t.Input,{value:(v=(j=n==null?void 0:n.onClickFilter)==null?void 0:j.find(C=>C.columnIndex===h))==null?void 0:v.expression,onChange:C=>d(h,C),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsxs("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:[e.jsx(t.Label,{children:"On Click"}),i==null?void 0:i.map((h,u)=>{var m,j;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(t.Checkbox,{checked:!!((m=n==null?void 0:n.onClickFilter)!=null&&m.find(v=>v.columnIndex===u)),onCheckedChange:v=>c(u,v)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:h}),e.jsx("div",{className:"flex items-center gap-2",children:((j=n==null?void 0:n.onClickFilter)==null?void 0:j.find(v=>v.columnIndex===u))&&e.jsx(t.Pencil,{onClick:()=>{a(v=>{const C=[...v];return C[u]=!v[u],C})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),l(u)]})},h)})]})}function ca({idx:s}){var d;const a=t.useEditorStore(l=>{var h;return(h=l.card)==null?void 0:h.preferences}),n=t.useEditorStore(l=>{var h;return(h=l.card.preferences)==null?void 0:h.datasetOptions}),r=t.useEditorStore(l=>l.actions.setCardPreferences),o=(d=a==null?void 0:a.chartOptions)==null?void 0:d.indexAxis,i=n==null?void 0:n.find(l=>l.idx===s);function c(l,h){(l==="end"||l==="start")&&t.getContrastColor(t.getCanvasBackgroundColor());const u={display:l!=="none",align:l,anchor:l,clamp:!0};if(!i)r({...a,datasetOptions:[...n||[],{idx:h,datalabels:u}]});else{const m={...i};m.datalabels=u;const j=n==null?void 0:n.map(v=>v.idx===h?m:v);r({...a,datasetOptions:j})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(Ot,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(t.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>c("none",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(t.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>c("start",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(sn,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(an,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(nn,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})})]})})]})}function da(){const s=t.useEditorStore(i=>i.card),{data:a}=t.useDashboardCardQuery(s),{keys:n}=t.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(i=>!t.METADATA_KEYS.includes(i));let o=r;if(["stackedBar","stackedLine"].includes(s.type)){const i=t.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:c}=t.getKeys(i);o=c.slice(1)}return{transformedMetricKeys:o,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function mt({children:s,className:a,delayDuration:n}){return e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{delayDuration:n,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:t.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}function ss(){const s=t.useEditorStore(l=>l.card),a=t.useEditorStore(l=>{var h,u,m;return(m=(u=(h=l==null?void 0:l.card)==null?void 0:h.preferences)==null?void 0:u.chartOptions)==null?void 0:m.indexAxis}),{data:n}=t.useDashboardCardQuery(s),r=a==="y"?"Metric":"Dimension",o=a==="y"?"Dimension":"Metric",{dimensionKeys:i,transformedMetricKeys:c,keys:d}=da();return d.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:i.map(l=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:l,children:ns(l)},l))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:o}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((l,h)=>e.jsx(as,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:l,idx:h},l))})]})]})}function ns(s,a=30){return s.length>a?s.slice(0,a)+"...":s}function as({col:s,idx:a,className:n,iconClassName:r,children:o}){const i=t.useEditorStore(u=>{var m;return(m=u.card)==null?void 0:m.preferences}),c=t.useEditorStore(u=>{var m,j;return(j=(m=u.card)==null?void 0:m.preferences)==null?void 0:j.datasetOptions}),d=c==null?void 0:c.find(u=>u.idx===a),{setCardPreferences:l}=t.useEditorStore(u=>u.actions);function h(u){if(!d)l({...i,datasetOptions:[...c||[],{idx:a,type:u==="area"?"line":u,fill:u==="area"?"origin":""}]});else{const m={...d};m.type=u==="area"?"line":u,m.fill=u==="area"?"origin":"";const j=c==null?void 0:c.map(v=>v.idx===a?m:v);l({...i,datasetOptions:j})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[o||e.jsx(mt,{className:"max-w-[100px]",title:s,children:ns(s)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ae,{onClick:()=>h("bar"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Le,{onClick:()=>h("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Vs,{onClick:()=>h("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(ca,{idx:a})]})]})}function rs(){const s=t.useEditorStore(v=>v.selectedConnectionId),a=t.useEditorStore(v=>v.selectedDatamodelId),n=t.useEditorStore(v=>v.selectedDatabaseName),r=t.useEditorStore(v=>v.selectedSchemaName),o=t.useEditorStore(v=>v.selectedTableName),i=t.useDashboardStore(v=>v.dashboard.filters)||[],c=t.useDashboardStore(v=>v.actions.addFilter),d=t.useDashboardStore(v=>v.actions.removeFilter),{removeFilterValues:l}=t.useDashboardActions(),{modelItems:h,tableName:u,connectionType:m}=t.useEditorAside();function j(v,C="dashboard"){var S;const p=t.fmt(v.column_name),D=t.fmt(n||""),f=t.fmt(r||""),y=t.fmt(u);let O=t.getQualifiedTableName({schemaName:f,tableName:y,connectionType:m,databaseName:D}),I=`${O}.${p}`;const k=(S=h==null?void 0:h.find(w=>w.id===a))==null?void 0:S.name;a&&a!=="none"&&(I=`${t.DATAMODEL_NAMESPCACE}.${k}.${p}`,O=`${t.DATAMODEL_NAMESPCACE}.${k}`);const N=i==null?void 0:i.find(w=>w.column===I&&w.table===y&&(w.database===D||w.database===n));if(N)l(N.id),d(N.id);else{const w=t.v4();return u==="api"&&s?(c({location:C,id:w,column:I,title:v.column_name,dataType:v.data_type,table:"api",database:"",connectionId:s,operation:"in",sql:t.getDefaultFilterSql(v.data_type,O,p)}),w):(c({id:w,location:C,column:I,title:v.column_name,dataType:v.data_type,table:o||"",database:n||"",connectionId:s||"",operation:"in",sql:t.getDefaultFilterSql(v.data_type,O,p)}),w)}}return{assignFilter:j}}function ve(){const s=t.useDashboardStore(d=>d.dashboard.filters),a=t.useEditorStore(d=>d.frame),{setFrame:n}=t.useEditorActions(),{columns:r}=t.useEditorAside(),{assignFilter:o}=rs();function i(d){const l=o(d,"frame");n({...a,filterId:l})}const c=s==null?void 0:s.find(d=>d.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Card Filter"}),e.jsx(ua,{onSelect:i,columns:r}),c&&e.jsx(t.FilterHeader,{filter:c})]})}function ua({columns:s,onSelect:a}){var c;const[n,r]=he.useState(!1),[o,i]=he.useState("");return e.jsxs(t.Popover,{open:n,onOpenChange:r,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[o?(c=s.find(d=>d.column_name===o))==null?void 0:c.column_name:"Select Column...",e.jsx(t.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No framework found."}),e.jsx(t.CommandGroup,{children:s==null?void 0:s.map(d=>e.jsxs(t.CommandItem,{value:d.column_name,onSelect:l=>{const h=l===o?"":l;i(h),r(!1),h&&a(d)},children:[d.column_name,e.jsx(t.CheckIcon,{className:t.cn("ml-auto h-4 w-4",o===d.column_name?"opacity-100":"opacity-0")})]},d.column_name))})]})]})})]})}function ma({cardType:s}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} Chart`}),e.jsxs(t.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:a=>a.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsx(t.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(ss,{})})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(je,{}),e.jsx(ve,{})]})]})]})})}function Be(){const s=t.useEditorStore(d=>d.card.type),a=t.useEditorStore(d=>d.isDevMode),n=t.useEditorStore(d=>d.card.preferences),{setCardPreferences:r}=t.useEditorStore(d=>d.actions);function o(d){var u;const l={datalabels:{display:d!=="none",align:d,anchor:d,clamp:!0}},h={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(u=n==null?void 0:n.chartOptions)==null?void 0:u.plugins,...l}}};r(h)}function i(){var d,l,h;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(t.Select,{value:((h=(l=(d=n==null?void 0:n.chartOptions)==null?void 0:d.plugins)==null?void 0:l.datalabels)==null?void 0:h.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Data Labels"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"start",children:"Start"}),e.jsx(t.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"end",children:"End"})]})})]})]})}function c(){var d,l,h;return e.jsx("div",{children:e.jsxs(t.Select,{value:((h=(l=(d=n==null?void 0:n.chartOptions)==null?void 0:d.plugins)==null?void 0:l.datalabels)==null?void 0:h.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(t.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?i():c()})}function ha({cardType:s}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:i=>i.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} Chart`}),e.jsx(t.AccordionContent,{className:"space-y-4 font-mono text-xs",children:a(s)})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsx(t.AccordionContent,{className:"px-2",children:e.jsx(Be,{})})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(je,{}),e.jsx(ve,{})]})]})]})})}const xa={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},pa={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function fa(){const s=t.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(t.Accordion,{className:" ",type:"single",collapsible:!0,children:ga(s)}),!["kpi"].includes(s)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Be,{}),e.jsx(je,{}),e.jsx(ve,{})]})]})}function ga(s){if(["line","bar"].includes(s))return e.jsxs(e.Fragment,{children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT x-axis, y-axis-1, y-axis-2, y-axis-3,... FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"X-axis - Category (ex. city)"}),e.jsx("li",{children:"Y-axis - Number (ex. population)"})]})]})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(t.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and change the `type` property in the dataset."]}),e.jsx("pre",{children:JSON.stringify(xa,null,2)})]})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(t.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and add `fill` property to the dataset. See",e.jsx("a",{className:"mx-1 text-blue-500 hover:underline",href:"https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html",target:"_blank",children:"docs"}),"for more options."]}),e.jsx("pre",{children:JSON.stringify(pa,null,2)})]})]})]});if(s==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:s})," chart query?"]})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis, radius FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Bubble Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"}),e.jsx("li",{children:"Radius - Number (ex. population)"})]})]})]})});if(s==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:s})," chart query?"]})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"})]})]})]})});if(["pie","doughnut","polarArea","funnel"].includes(s))return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:s==="polarArea"?"Polar":s.charAt(0).toUpperCase()+s.slice(1)})," ","chart query"]})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Measure - Number (ex. population)"})]})]})]})})}function ja(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(t.Accordion,{type:"single",collapsible:!0,children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(t.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(t.FormatNumberSetting,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function _e({children:s,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,className:t.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(t.Label,{children:a}),e.jsx(t.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:s})]})}const ya=[{label:"Mercator",value:"mercator"},{label:"Azimuthal Equidistant",value:"azimuthalEquidistant"},{label:"Gnomonic",value:"gnomonic"},{label:"Orthographic",value:"orthographic"},{label:"Stereographic",value:"stereographic"},{label:"Equal Earth",value:"equalEarth"},{label:"Albers",value:"albers"},{label:"Albers USA",value:"albersUsa"},{label:"Conic Conformal",value:"conicConformal"},{label:"Conic Equal Area",value:"conicEqualArea"},{label:"Conic Equidistant",value:"conicEquidistant"},{label:"Equirectangular",value:"equirectangular"},{label:"Transverse Mercator",value:"transverseMercator"},{label:"Natural Earth 1",value:"naturalEarth1"}],ba=["blues","brBG","buGn","buPu","cividis","cool","cubehelixDefault","gnBu","greens","greys","inferno","magma","orRd","oranges","pRGn","piYG","plasma","puBu","puBuGn","puOr","puRd","purples","rainbow","rdBu","rdGy","rdPu","rdYlBu","rdYlGn","reds","sinebow","spectral","turbo","viridis","warm","ylGn","ylGnBu","ylOrBr","ylOrRd"],va=ba.map(s=>({label:s,value:s}));function Na(){var l,h,u,m,j,v,C,p,D,f,y,O,I,k,N,S,w,E;const s=t.useEditorStore(g=>g.card),a=(h=(l=s==null?void 0:s.preferences)==null?void 0:l.mapVisualOptions)==null?void 0:h.topoJsonUrl,[n,r]=L.useState(((m=(u=s==null?void 0:s.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:m.customTopoJsonUrl)||""),{setCardPreferences:o}=t.useEditorActions(),{data:i}=t.useTopoJson(s),c=Object.keys((i==null?void 0:i.objects)||{}).map(g=>({label:g,value:g}))||[],d=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(_e,{summary:"Map Chart",children:e.jsx("p",{className:"rounded-md bg-muted p-2 font-mono text-xs",children:"SELECT country, value FROM table"})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(_e,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(se,{className:"h-9",options:d,onValueChange:g=>{console.log("value",g),o({...s.preferences,mapVisualOptions:{topoJsonUrl:g}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(t.Input,{onChange:g=>{r(g.target.value)},onBlur:()=>{var g;console.log("onBlur",n),o({...s.preferences,mapVisualOptions:{...(g=s.preferences)==null?void 0:g.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${t.removeRing}`,placeholder:"Custom URL"}),i&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Map Object"}),e.jsx(se,{className:"h-9",options:c,value:((v=(j=s.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:v.objectKey)||"",label:"Map Object",onValueChange:g=>{var x;o({...s.preferences,mapVisualOptions:{...(x=s.preferences)==null?void 0:x.mapVisualOptions,objectKey:g}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(se,{className:"h-9",options:ya,value:((p=(C=s.preferences)==null?void 0:C.mapVisualOptions)==null?void 0:p.projection)||"",label:"Projection",onValueChange:g=>{var x;o({...s.preferences,mapVisualOptions:{...(x=s.preferences)==null?void 0:x.mapVisualOptions,projection:g}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(se,{className:"h-9",options:va,value:((f=(D=s.preferences)==null?void 0:D.mapVisualOptions)==null?void 0:f.colorScale)||"",label:"Select Color Scale",onValueChange:g=>{var x;o({...s.preferences,mapVisualOptions:{...(x=s.preferences)==null?void 0:x.mapVisualOptions,colorScale:g}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(_e,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:.1,value:((O=(y=s.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:O.projectionScale)||1,onChange:g=>{var x;o({...s.preferences,mapVisualOptions:{...(x=s.preferences)==null?void 0:x.mapVisualOptions,projectionScale:Number(g.target.value)}})}}),e.jsx(t.Label,{children:"X"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((N=(k=(I=s.preferences)==null?void 0:I.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:N[0])||0,onChange:g=>{var x,B,A,T;o({...s.preferences,mapVisualOptions:{...(x=s.preferences)==null?void 0:x.mapVisualOptions,projectionOffset:[Number(g.target.value),((T=(A=(B=s.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:T[1])||0]}})}}),e.jsx(t.Label,{children:"Y"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((E=(w=(S=s.preferences)==null?void 0:S.mapVisualOptions)==null?void 0:w.projectionOffset)==null?void 0:E[1])||0,onChange:g=>{var x,B,A,T;o({...s.preferences,mapVisualOptions:{...(x=s.preferences)==null?void 0:x.mapVisualOptions,projectionOffset:[((T=(A=(B=s.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:T[0])||0,Number(g.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(je,{})]})}function Ca(){var r;const s=t.useEditorStore(o=>o.card.preferences),{setCardPreferences:a}=t.useEditorStore(o=>o.actions);function n(o){a({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:o==="dynamic"}})}return e.jsxs(t.RadioGroup,{value:(r=s==null?void 0:s.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function ke({cardType:s,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return s==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} ${n}`}),e.jsx(t.AccordionContent,{children:a||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[s!=="text"&&e.jsx(Be,{}),s==="text"&&e.jsx(Ca,{})]})]}),!["range","text"].includes(s)&&e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(je,{}),e.jsx(ve,{})]})]})]})})}function Sa(){const s=t.useEditorStore(r=>{var o,i;return(i=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:i.sortChart}),{setSortChart:a}=t.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Sort"}),e.jsx(se,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:s||"none",onValueChange:r=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(t.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(ss,{})]})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(je,{}),e.jsx(ve,{})]})]})]})})}function wa({cardType:s="table"}){console.log("cardType",s);const a=t.useEditorStore(o=>{var i;return(i=o.card)==null?void 0:i.preferences}),n=t.useEditorStore(o=>o.actions.setCardPreferences),r=o=>{n({...a,allowDownload:o})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(t.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(je,{}),e.jsx(ve,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}const ka=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT dimension, cohort, metric FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),Ea=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),Da=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function Ta(){const s=t.useEditorStore(n=>n.card.type);function a(n){switch(n){case"stackedBar":case"stackedLine":return e.jsx(Sa,{});case"tornado":case"pyramid":return e.jsx(ke,{docContent:ka,cardType:n});case"kpi":return e.jsx(ja,{});case"line":case"bar":return e.jsx(ma,{cardType:n});case"range":return e.jsx(ke,{docContent:Ea,cardType:n});case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return e.jsx(ke,{cardType:n});case"bubble":case"scatter":return e.jsx(ha,{cardType:n});case"table":return e.jsx(wa,{cardType:n});case"text":return e.jsx(ke,{docContent:Da,cardType:n,suffix:"Visual"});case"map":return e.jsx(Na,{});case"custom":return e.jsx(la,{});default:return e.jsx(fa,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[a(s),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function os({label:s,column:a,functions:n,onFunctionChange:r}){let o=n[0];"aggregate"in a?o=n.find(c=>c.value===a.aggregate)||n[0]:"granularity"in a&&(o=n.find(c=>c.value===a.granularity)||n[0]);function i(c){r(c)}return e.jsx(se,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:o.logo,options:n,value:o.value,onValueChange:c=>i(c),label:s,showPlaceholderLabel:!1})}const Ia=[{label:"Sum",value:"SUM",logo:e.jsx(Lt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(Ze,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(Ws,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(Is,{className:"size-3.5"})},{label:"Min",value:"MIN",logo:e.jsx(t.ArrowDown,{className:"size-3.5"})},{label:"Max",value:"MAX",logo:e.jsx(t.ArrowUp,{className:"size-3.5"})}];function Ma({column:s}){const{updateMetricColumnOld:a}=t.useEditorActions();let n=Ia;t.isTextDataType(s.type)&&(n=n.filter(o=>["COUNT","DISTINCT"].includes(o.value))),t.isNumberDataType(s.type)&&(n=n.filter(o=>!["DISTINCT"].includes(o.value)));function r(o){const i={...s,aggregate:o,label:Ce(s.name,o)};a(s.id,i)}return e.jsx(os,{column:s,functions:n,onFunctionChange:o=>r(o),label:"Aggregation"})}const Aa=[{label:"Day (D)",value:"day",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"D"})},{label:"Week (W)",value:"week",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"W"})},{label:"Month (M)",value:"month",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"M"})},{label:"Year (Y)",value:"year",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"Y"})}];function La({column:s}){const{updateGroupByColumnOld:a}=t.useEditorActions();function n(r){const o={...s,granularity:r,label:be(s.name,r)};a(s.id,o)}return e.jsx(os,{column:s,functions:Aa,onFunctionChange:r=>n(r),label:"Granularity"})}function Oa({col:s,onChange:a,droppableId:n}){const{columns:r}=t.useDataColumns(),o=L.useMemo(()=>{let d=[];(n===xe||n===pe||n===fe)&&(d=r);const l=d==null?void 0:d.filter(h=>h.column_name!==s.name);return l==null?void 0:l.map(h=>({id:h.column_name,value:h.column_name}))},[r,n,s.name]),i=[{id:s.name,value:s.name}];function c(d){const l=r==null?void 0:r.find(h=>{var u;return h.column_name===((u=d[0])==null?void 0:u.id)});l&&a(l)}return o!=null&&o.length?e.jsx(t.ComboBox2,{multiple:!1,options:o,selectedOptions:i,onChange:c,selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"border-none bg-muted pl-0 pr-8"}):e.jsx("input",{disabled:!0,type:"text",className:"overflow-hidden truncate text-ellipsis whitespace-nowrap bg-muted text-sm",value:s.name})}function is({column:s}){const a=t.useEditorStore(l=>l.card.type),n=t.useEditorStore(l=>{var h,u;return(u=(h=l.card)==null?void 0:h.config)==null?void 0:u.metricColumns}),r=(n==null?void 0:n.map(l=>l.label))||[],o=r==null?void 0:r.find(l=>l===s.label||l===s.name),i=o?r.indexOf(o):-1;function c(){return e.jsx("div",{className:"pr-1",children:o&&e.jsx(as,{idx:i,col:o,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function d(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Be,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&c(),["pie","doughnut"].includes(a)&&d()]})}function Ba({column:s,type:a,onRemoveColumn:n,droppableId:r}){const[o,i]=L.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:d,updatePivotByColumnOld:l}=t.useEditorActions(),{attributes:h,listeners:u,setNodeRef:m,transform:j,transition:v,isDragging:C}=t.useSortable({id:s.id,data:{type:a}}),p=j?{opacity:C?.5:void 0,transform:t.CSS.Translate.toString(j),transition:v}:void 0,D=t.isTextDataType(s.type);function f(N){const S=t.isNumberDataType(N.data_type),w=t.isTextDataType(N.data_type),E=t.isDateDataType(N.data_type),g=S?"number":w?"string":E?"date":"string";if(r===xe){if(w){const x={id:s.id,name:N.column_name,type:g,role:"groupby"};c(s.id,x)}if(E){const x={id:s.id,name:N.column_name,type:g,role:"groupby",label:be(N.column_name,"month"),granularity:"month"};c(s.id,x)}}if(r===fe){if(w){const x={id:s.id,name:N.column_name,type:g,role:"groupby"};l(s.id,x)}if(E){const x={id:s.id,name:N.column_name,type:g,label:be(N.column_name,"month"),granularity:"month",role:"groupby"};l(s.id,x)}}if(r===pe){const x={id:s.id,name:N.column_name,type:g,role:"metric",label:Ce(N.column_name,"SUM"),aggregate:S?"SUM":"COUNT"};d(s.id,x)}}function y(){if(r===pe)return e.jsx("div",{"data-setting-container":"",className:"mt-1.5 max-h-32 overflow-y-auto rounded-md border border-border p-3 text-sm",children:e.jsx(is,{column:s})})}function O(){const N=t.isDateDataType(s.type);if(r===pe)return e.jsx(Ma,{column:s});if((r===xe||r===fe)&&N)return e.jsx(La,{column:s})}function I(){return e.jsx("div",{className:t.cn("grow",{"pl-3":(r===xe||r===fe)&&D}),children:e.jsx(Oa,{col:s,onChange:f,droppableId:r})})}function k(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>i(!o),children:o?e.jsx(fn,{className:t.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(Mt,{className:t.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...u,...h,ref:m,style:p,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[k(),O(),I()]}),o&&y()]}),e.jsx("div",{className:t.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:o}),children:e.jsx("button",{onClick:()=>n(s.id),children:e.jsx(t.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function Ge({id:s,label:a,columns:n,previewColumns:r,sortableType:o,onRemoveColumn:i}){var p,D;const{setNodeRef:c,isOver:d,over:l}=t.useDroppable({id:s}),h=t.useDndStore(f=>f.activeId),u=t.useEditorStore(f=>{var y;return(y=f.card)==null?void 0:y.type}),m=d||((D=(p=l==null?void 0:l.data)==null?void 0:p.current)==null?void 0:D.type)===o,j=h?r:n,v=o===De?"Rows":o===Te?"Pivot Columns":"Columns";function C(){if(!j||j.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(t.SortableContext,{items:n==null?void 0:n.map(f=>f.id),children:e.jsxs("div",{className:t.cn("group space-y-2 rounded-md p-4",m&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(t.Label,{className:"text-sm",children:a}),u!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:v})]}),C(),e.jsx("div",{className:"space-y-2",children:j==null?void 0:j.map(f=>f.id===qt.id?e.jsx(Fa,{},f.id):e.jsx(Ba,{droppableId:s,type:o,column:f,onRemoveColumn:i},f.id))})]})})}function Fa(){return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm",children:e.jsx("span",{className:"text-muted-foreground/70",children:"Drop here"})})}function ls({children:s,id:a,type:n}){const{attributes:r,listeners:o,setNodeRef:i,transform:c,transition:d,isDragging:l}=t.useSortable({id:a,data:{type:n}}),h=c?{opacity:l?.5:void 0,transform:t.CSS.Translate.toString(c),transition:d}:void 0;return e.jsx("div",{...o,...r,ref:i,style:h,children:s})}function za(){const s=t.useEditorStore(f=>{var y;return(y=f.card.queryConfig)==null?void 0:y.orderBy})||[],a=t.useEditorStore(f=>{var y;return(y=f.card.queryConfig)==null?void 0:y.groupByColumns})||[],n=t.useEditorStore(f=>{var y;return(y=f.card.queryConfig)==null?void 0:y.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:o,updateOrderByColumn:i}=t.useEditorActions(),c=[...a,...n];if(c.length===0)return e.jsx(e.Fragment,{});const d=e.jsx(Os,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),l=e.jsx(Ts,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=e.jsx(Ls,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(Ds,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=c==null?void 0:c.filter(f=>!s.some(y=>y.columnId===f.id)).map(f=>({id:f.id,value:f.label||f.name}));function j(f,y){const O=v(f);return O?O.role==="metric"?y==="asc"?h:u:y==="asc"?d:l:null}function v(f){return c.find(y=>y.id===f)}function C(f){const y=s.find(O=>O.columnId===f);if(y){const O={...y,direction:y.direction==="asc"?"desc":"asc"};i(O)}}const p=f=>{r({columnId:f.id,direction:"asc"})};function D(f){const y=s.find(O=>O.columnId===f);y&&o(y)}return e.jsx(t.SortableContext,{items:s.map(f=>Ne(f.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(t.Label,{className:"text-sm",children:"Sort By"}),m.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(t.ComboBox2,{multiple:!1,options:m,selectedOptions:[],onChange:f=>p(f[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),s.map(f=>{var y,O;return e.jsx(ls,{id:Ne(f.columnId),type:ot,children:e.jsx("div",{className:"group flex h-8 items-center gap-2 rounded-sm p-0",children:e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2 rounded-sm bg-muted px-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Mt,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(mt,{className:"w-[175px] text-sm",children:((y=v(f.columnId))==null?void 0:y.label)||((O=v(f.columnId))==null?void 0:O.name)})]}),e.jsx("button",{title:f.direction==="asc"?"Ascending":"Descending",onClick:()=>C(f.columnId),className:"rounded-sm p-0",children:j(f.columnId,f.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>D(f.columnId),className:"rounded-sm p-0",children:e.jsx(t.X,{className:"size-3 text-muted-foreground opacity-0 transition-opacity duration-200 hover:text-foreground group-hover:opacity-100"})})})]})},f.columnId)},Ne(f.columnId))})]})})}function Pa(){const s=t.useEditorStore(D=>{var f;return((f=D.card.queryConfig)==null?void 0:f.groupByColumns)||[]}),a=t.useEditorStore(D=>D.card.type),n=t.useDndStore(D=>D.previewGroupByColumns),r=t.useEditorStore(D=>{var f;return((f=D.card.queryConfig)==null?void 0:f.metricColumns)||[]}),o=t.useDndStore(D=>D.previewMetricColumns),i=t.useEditorStore(D=>{var f;return((f=D.card.queryConfig)==null?void 0:f.pivotColumns)||[]}),c=t.useDndStore(D=>D.previewPivotColumns),{removeColumnFromGroupBy:d,removeColumnFromMetricColumns:l,removeColumnFromPivotBy:h}=t.useEditorActions();function u(D){d(D)}function m(D){l(D)}function j(D){h(D)}let v="Group By",C="Metrics",p="Stack By";return a==="table"&&(v="Rows",C="Metrics",p="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(Xt,{iconClassName:"size-[19px]"}),e.jsxs(t.CustomScrollArea,{className:"flex min-h-0 grow basis-0 flex-col gap-4 overflow-y-auto",children:[e.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e.jsx(Ge,{onRemoveColumn:u,sortableType:De,id:xe,label:v,columns:s,previewColumns:n}),e.jsx(Ge,{onRemoveColumn:j,sortableType:Te,id:fe,label:p,columns:i,previewColumns:c}),e.jsx(Ge,{onRemoveColumn:m,sortableType:Je,id:pe,label:C,columns:r,previewColumns:o}),e.jsx(za,{})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function ht({children:s,column:a,id:n,sortableType:r,className:o}){const[i,c]=L.useState(!1),{removeEditorFilter:d,clearEditorFilter:l}=t.useEditorActions(),h=t.useEditorStore(m=>{var j,v;return(v=(j=m.card.queryConfig)==null?void 0:j.filters)==null?void 0:v.some(C=>C.filterColumnName===a.name)});function u(m){d(m)}return e.jsx(ls,{id:n,type:r,children:e.jsxs("div",{className:t.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":i}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-sm",children:a.name}),h&&e.jsx("button",{onClick:()=>l(a),children:e.jsx(t.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>u(a),children:e.jsx(t.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:t.cn("group flex items-center rounded-t-md text-sm",!i&&"rounded-b-md",i&&"border border-border"),children:[e.jsx("div",{children:e.jsx(t.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:t.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",o),children:s})]})]})})}function Ra({column:s,sortableType:a}){const n=t.useDashboardStore(O=>O.themeStyle),r=t.useEditorStore(O=>{var I,k;return(k=(I=O.card)==null?void 0:I.queryConfig)==null?void 0:k.filters}),o=t.useEditorStore(O=>{var I,k;return(k=(I=O.card.queryConfig)==null?void 0:I.filterColumns)==null?void 0:k.find(N=>N.name===s.name)}),{selectedConnectionId:i,selectedDatabaseName:c,selectedTableName:d}=t.useEditorAside(),l=L.useMemo(()=>{var O;return(O=r==null?void 0:r.find(I=>I.filterColumnName===s.name))==null?void 0:O.filterValue},[r,s.name]),h=L.useMemo(()=>Array.isArray(l)?l.map(O=>({id:O,value:O})):[],[l]),{updateEditorFilterValue:u}=t.useEditorActions(),m={column:s.name,sql:s.sql,id:s.name,connectionId:i,dataType:s.type},{data:j,isLoading:v,isFetching:C,isError:p}=t.useFilterQuery(m),D=L.useMemo(()=>{var I;return m.column?(I=j==null?void 0:j.records)==null?void 0:I.map(k=>{let N=m.column.split(".").slice(-1)[0].replace(/"/g,"");return k[N]===void 0&&(N=N.toLowerCase()),{id:k[N],value:k[N]}}):[]},[j,m.column]);function f(O){const I=O.map(k=>k.id);u(s.name,I)}function y(){return v||C?e.jsx(t.Skeleton,{style:{borderRadius:n==null?void 0:n.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):p?e.jsx("div",{className:"flex h-8 min-w-60 items-center bg-muted px-2 text-sm",children:"Error"}):e.jsx(t.ComboBox2,{renderFilterModeButton:()=>e.jsx(Va,{columnName:s.name}),showNegativeIndicator:(o==null?void 0:o.mode)==="exclude",options:D,onChange:f,selectedOptions:h,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(ht,{className:"w-60",id:s.id,sortableType:a,column:s,children:y()})}function Va({columnName:s}){const{setEditorFilterMode:a}=t.useEditorActions(),n=t.useEditorStore(o=>{var i,c;return(c=(i=o.card.queryConfig)==null?void 0:i.filterColumns)==null?void 0:c.find(d=>d.name===s)});function r(){(n==null?void 0:n.mode)==="exclude"?a(s,"include"):a(s,"exclude")}return e.jsx(t.Button,{onClick:r,variant:"secondary",size:"sm",className:t.cn("h-5 text-xs hover:underline",{}),children:t.titleCase((n==null?void 0:n.mode)==="exclude"?"exclude":"include")})}function qa({column:s,sortableType:a}){const[n,r]=L.useState(!1),{selectedConnectionId:o,selectedDatabaseName:i,selectedTableName:c}=t.useEditorAside(),d={column:s.name,sql:s.sql,id:s.name,connectionId:o,title:"",dataType:s.type},{isLoading:l,isFetching:h,isError:u,data:m}=t.useFilterQuery(d),j=m==null?void 0:m.records,{dateRange:v,setDateRange:C,initialDateRange:p}=t.useDateRangeFromRecords(j),{updateEditorFilterValue:D}=t.useEditorActions();function f(I){var N,S;const k={gte:(N=I==null?void 0:I.from)==null?void 0:N.toISOString(),lte:(S=I==null?void 0:I.to)==null?void 0:S.toISOString()};D(s.name,k)}function y(){D(s.name,null,!0),C(p)}function O(){return l||h?e.jsx("div",{children:e.jsx(t.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):u?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):j?e.jsx(t.DateRangePopover,{title:d.title,open:n,inputClassName:"h-8",setOpen:r,dateRange:v,setDateRange:C,onApply:f,onClear:y}):e.jsx(t.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(ht,{className:"w-72",id:s.id,sortableType:a,column:s,children:O()})}function _a({id:s,label:a,columns:n,previewColumns:r,sortableType:o}){var C,p;const{setNodeRef:i,isOver:c,over:d}=t.useDroppable({id:s}),l=t.useDndStore(D=>D.activeId),h={},u=c||((p=(C=d==null?void 0:d.data)==null?void 0:C.current)==null?void 0:p.type)===o;function m(){if(!v||v.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function j(D){const f=t.isDateDataType(D.type);return D.id===qt.id?e.jsx(ht,{id:D.id,sortableType:o,column:D,children:e.jsx(Ga,{})},D.id):f?e.jsx(qa,{droppableId:s,sortableType:o,column:D},D.id):e.jsx(Ra,{droppableId:s,sortableType:o,column:D},D.id)}const v=l?r:n;return e.jsx(t.SortableContext,{items:n==null?void 0:n.map(D=>D.id),children:e.jsxs("div",{className:t.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",u&&"border border-muted-foreground/20"),ref:i,style:h,children:[e.jsx(t.Label,{className:"text-sm",children:a}),m(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:v==null?void 0:v.map(D=>j(D))})]})})}function Ga(){return e.jsx("div",{className:"flex h-8 w-60 items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm text-muted-foreground",children:"Drop here"})}function $a(){const s=t.useEditorStore(o=>{var i;return((i=o.card.queryConfig)==null?void 0:i.filterColumns)||[]}),a=t.useDndStore(o=>o.previewFilterColumns),{removeColumnFromFilterColumns:n}=t.useEditorActions();function r(o){n(o)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(_a,{onRemoveColumn:r,sortableType:Ye,id:He,label:"Filters",columns:s,previewColumns:a})})}function Ja(){const s=t.useEditorStore(i=>i.card),a=t.useEditorStore(i=>i.showAIDialog),{setShowAIDialog:n}=t.useEditorActions(),{data:r,errorMessage:o}=t.useDashboardCardQuery(s);return e.jsxs("section",{className:"flex justify-between gap-2 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.EditorClearButton,{}),!a&&e.jsxs(t.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(Jt,{sql:r==null?void 0:r.sql,error:o})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-green-300 px-3 py-1 text-xs font-medium text-black",children:"Preview"}),e.jsx(t.EditorCancelButton,{}),e.jsx(t.EditorAcceptButton,{variant:"default"})]})]})}function Ha(){const s=L.useRef(null),a=L.useRef(null),n=t.useEditorStore(d=>d.isShowingVisual),r=t.useEditorStore(d=>d.showAIDialog),o=t.useEditorStore(d=>d.isDevMode);L.useEffect(()=>{var d,l,h,u;r?((d=s.current)==null||d.resize(0),(l=a.current)==null||l.resize(0)):((h=s.current)==null||h.resize(25),(u=a.current)==null||u.resize(25))},[r]);function i(){return e.jsxs(e.Fragment,{children:[e.jsx(t.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Jn,{})}),e.jsx(t.ResizableHandle,{withHandle:!0}),e.jsx(t.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!r?e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(t.ResizablePanel,{ref:s,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Ta,{})})}),!r&&e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(we,{})})]}):e.jsx(we,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:n?e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(t.ResizablePanel,{ref:a,defaultSize:25,maxSize:30,children:e.jsx(Pa,{})})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{defaultSize:75,maxSize:100,children:e.jsxs(t.ResizablePanelGroup,{direction:"vertical",children:[e.jsxs(t.ResizablePanel,{className:"flex min-h-fit flex-col",minSize:10,defaultSize:20,children:[e.jsx(Ja,{}),e.jsx($a,{})]}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(we,{})})]})})]}):e.jsx(we,{})})})}return e.jsx(t.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:o?i():c()})}function Ya(s){const a=t.useAIInteractionStore(_=>_.currentAIContext),[n,r]=L.useState(""),[o,i]=L.useState(null),{authToken:c}=t.useSemaphorContext(),d=t.useEditorStore(_=>{var K;return(K=_==null?void 0:_.card)==null?void 0:K.sql}),l=t.useEditorStore(_=>_.isDevMode),h=t.useEditorStore(_=>{var K;return(K=_==null?void 0:_.card)==null?void 0:K.python}),{setCardPython:u,setCardSql:m,setRunSql:j,switchCardType:v,setQueryConfig:C}=t.useEditorActions(),p=t.useEditorStore(_=>_.currentAssitantScope)||[],D=t.useEditorStore(_=>_.userInputForAI),f=t.useEditorStore(_=>_.triggerAIRun),y=t.useEditorStore(_=>_.card),O=t.useEditorStore(_=>_.selectedDatabaseName),I=t.useEditorStore(_=>_.selectedTableName),k=t.useEditorStore(_=>_.selectedConnectionId),N=t.useEditorStore(_=>_.selectedSchemaName),S=t.useDashboardStore(_=>_.dashboard.aiScopeTables),{errorMessage:w,refetch:E,data:g}=t.useDashboardCardQuery(y),{setTriggerAIRun:x,setCurrentAssitantScope:B,setCardConfig:A}=t.useEditorActions(),{selectedDatamodelName:T,connectionType:b,selectedDatamodelId:M}=t.useEditorAside(),{messages:F,setMessages:P,reload:V,error:z,append:U,input:R,setInput:q,status:H,handleInputChange:Q,handleSubmit:G,stop:$}=t.useChat({api:"https://semaphor.cloud/api/v1/assistant",headers:{Authorization:`Bearer ${c==null?void 0:c.accessToken}`},body:{random:Math.random(),assistantId:"editor-assistant",isDevMode:l,aiContext:a},maxSteps:10,onError:_=>{console.log("on error",_)},onToolCall:J,onFinish(_,K){X(K.usage),r(""),K.finishReason==="stop"&&r("")}});L.useEffect(()=>{f&&D&&(U({role:"user",content:D}),x(!1))},[f,D,U,x]);async function J({toolCall:_}){var K,ae,de,me;if(["createChartFromSql","createForecast"].includes(_.toolName)){const W=_.args.sql,Z=_.args.python,ee=_.args.chartType;return v(ee),m(W),u(Z),j(!0),{status:"success",message:"Let the user know that chart is created"}}else if(_.toolName==="getTableColumns")r("Getting table columns...");else{if(_.toolName==="getUserSql")return d?{status:"success",sql:d,python:h||""}:{status:"error",message:"No SQL found"};if(_.toolName==="getCurrentTableScope")return r("Getting table scope..."),oe(),{status:"success",tables:p};if(_.toolName==="generateQueryConfig"){r("Generating query config...");const W=_.args.chartType,Z=_.args.queryConfig;_.args.cardConfig,v(W),A(Z),m(void 0),u(void 0);const ee=await E();return(K=ee==null?void 0:ee.data)!=null&&K.error?{status:"error",queryConfig:Z,message:(ae=ee==null?void 0:ee.data)==null?void 0:ae.error.message}:(de=ee==null?void 0:ee.data)!=null&&de.records?{status:"success",queryConfig:Z,message:"The data has been visualized"}:{status:"success",queryConfig:Z,message:"The data has been visualized",records:(me=ee==null?void 0:ee.data)==null?void 0:me.records}}else r("Analyzing...")}}function X(_){i(K=>K?{promptTokens:K.promptTokens+_.promptTokens,completionTokens:K.completionTokens+_.completionTokens,totalTokens:K.totalTokens+_.totalTokens}:_)}function te(_){const K=t.removeFromScopeArray(p,_);ne(K)}function ne(_){const K=t.sanitizeAIScope(_);B(K),P(ae=>[...ae,{id:crypto.randomUUID(),role:"system",content:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(K)}`}])}function le(){const _={databaseName:O||"",schemaName:N||"",tableName:I||"",datamodelId:M||"",datamodelName:t.resolveDatamodelName(T),connectionId:k||"",connectionType:b||""},K=t.dedup([...p,_]);ne(K)}function oe(){const _={databaseName:O||"",schemaName:N||"",tableName:I||"",datamodelName:t.resolveDatamodelName(T),connectionId:k||"",connectionType:b||"",datamodelId:M||""};if(!t.isInAiScopeArray([...S||[],...p],_)||p.length===0){const ae=t.dedup([...S||[],...p,_]).filter(de=>de.connectionId===_.connectionId);ne(ae)}}const ce=!["ready","error"].includes(H),ie=t.getErrorMessage(z);return{messages:F,setMessages:P,reload:V,append:U,input:R,setInput:q,isLoading:ce,handleSetAIScope:oe,handleAddCurrentTableToScope:le,removeFromCurrentSelections:te,currentAssitantScope:p,setCurrentAssitantScope:B,handleInputChange:Q,handleSubmit:G,stop:$,chatStatus:H,toolStatus:n,llmUsage:o,onFinish:s,errorMessage:ie}}const Ka=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Et(){const s=L.useRef(null),a=L.useRef(null),[n,r]=L.useState(!1),[o,i]=L.useState(t.isDevEnv),[c,d]=L.useState(!1),[l,h]=L.useState(!1),u=t.useCurrentAIContext(),{setCurrentAIContext:m}=t.useAIActions(),j=t.useDashboardStore($=>$.dashboard.aiContext),v=t.useEditorStore($=>$.card.dataSource),C=t.useEditorStore($=>$.actions.setCardSql),p=t.useEditorStore($=>$.actions.setRunSql),D=t.useEditorStore($=>$.showAIDialog),f=t.useDashboardStore($=>$.handleOpenAssistantProfile),{setShowAIDialog:y,setCardPython:O}=t.useEditorActions(),{setDataSource:I}=t.useEditorActions(),{assistantProfile:k}=t.useAssistantProfile(),{messages:N,setMessages:S,reload:w,append:E,input:g,setInput:x,isLoading:B,handleInputChange:A,handleSubmit:T,stop:b,chatStatus:M,llmUsage:F,errorMessage:P}=Ya();t.useAssistantScroll({scrollContainerRef:s,inputRef:a,messages:N}),L.useEffect(()=>{var $;D&&(($=a.current)==null||$.focus(),m({selectedEntities:(v==null?void 0:v.selectedEntities)||[]}))},[D,v,m]);function V($,J){J==="sql"?(C($),p(!0)):J==="python"&&(O($),p(!0))}function z(){var $;($=j==null?void 0:j.selectedEntities)==null||$[0],h(!0)}function U(){u.selectedEntities.length===0&&m({selectedEntities:(j==null?void 0:j.selectedEntities)||[]})}function R($){U();const J={role:"user",content:$.title+" "+$.subtitle};E(J)}function q($){U(),E({role:"user",content:$})}function H(){return e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.Button,{className:"h-7 p-2",size:"sm",variant:"ghost",children:e.jsx(t.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",children:[e.jsx(t.DropdownMenuLabel,{children:"Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsx(t.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:r,children:"Token Usage"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:i,children:"Tool Invocations"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:d,children:"System Message"})]})]})}function Q(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const G=(g==null?void 0:g.length)===0&&(N==null?void 0:N.filter($=>$.role==="user").length)===0;return e.jsxs("div",{"data-role":"editor-assistant",className:"flex h-full w-full flex-col justify-between px-6 py-4",children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Q(),f&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:f,children:(k==null?void 0:k.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center gap-2",children:[H(),e.jsx(t.IconButton,{tooltip:"Add Context",className:"h-7 p-2",onClick:z,children:e.jsx(t.Settings,{className:"size-4"})}),e.jsx(t.IconButton,{className:"h-7 p-2",tooltip:"New Chat",onClick:()=>{S([]),w()},children:e.jsx(t.SquarePen,{className:"size-4"})}),e.jsx(t.Button,{variant:"ghost",className:"h-8",size:"sm",onClick:()=>{y(!1)},children:e.jsx(t.PanelRight,{className:"size-4"})})]})]}),e.jsx(t.CustomScrollArea,{ref:s,className:"mt-2 flex w-full grow basis-0",children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[e.jsx(t.PrintMessages,{messages:N,showTools:o,handleRun:V,showSystemMessage:c}),e.jsx(t.ChatStatus,{messages:N,chatStatus:M,errorMessage:P})]})}),e.jsxs("div",{className:"mb-3",children:[G&&!k&&e.jsx(t.Placeholders,{onClick:R,placeholders:Ka}),e.jsx("div",{children:G&&k&&e.jsx(t.SeedQuestions,{seedQuestions:k.seedQuestions||[],handleSeedQuestionClick:q})})]}),e.jsx(t.ChatInputWithContext,{ref:a,setInput:x,stop:b,input:g,handleInputChange:A,handleSubmit:$=>{U(),T($)},isLoading:B,onFocus:()=>{}}),F&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",F.promptTokens," prompt tokens,"," ",F.completionTokens," completion tokens,"," ",F.totalTokens," total tokens"]})}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:(v==null?void 0:v.selectedEntities)||[],open:l,onOpenChange:h,dataSource:v||t.EMPTY_DATA_SOURCE,fallbackDataSource:t.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function Ua({field:s}){const{attributes:a,listeners:n,setNodeRef:r,transform:o,transition:i,isDragging:c}=t.useSortable({id:s.id}),[d,l]=L.useState(!1),h={transform:t.CSS.Transform.toString(o),transition:i},u=t.getDataType(s.dataType),j=(v=>{const C=(v||"").toLowerCase();switch(t.getDataType(C)){case"number":return Ze;case"date":return t.Calendar;case"boolean":return Bt;case"json":return _s;case"geo":return ln;default:return Ft}})(s.dataType);return e.jsxs("div",{ref:r,style:h,...a,...n,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:border-blue-200 hover:bg-blue-50 dark:hover:border-blue-800 dark:hover:bg-blue-950"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1 p-2",onClick:()=>l(!d),children:[e.jsx("div",{className:"flex-shrink-0 hover:cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"invisible size-3.5 text-gray-400 group-hover/container:visible"})}),e.jsx(j,{className:t.cn("size-3.5 flex-shrink-0 text-gray-500",u==="string"?"text-blue-500":"",u==="number"?"text-green-500":"",u==="date"?"text-purple-500":"",u==="boolean"?"text-orange-500":"")}),e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm text-foreground/90 hover:text-foreground dark:text-muted-foreground ${d?"whitespace-normal break-words":"truncate"}`,children:s.name})})}),e.jsx(t.TooltipContent,{side:"bottom",align:"start",className:"max-w-fit",children:e.jsxs("div",{className:"overflow-x-auto",children:[e.jsx("p",{className:t.cn("font-medium",{"text-blue-500":u==="string","text-green-500":u==="number","text-purple-500":u==="date","text-orange-500":u==="boolean"}),children:s.label||s.name}),s.description&&e.jsx("div",{className:"mt-1 text-sm text-muted-foreground",children:s.description}),e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(hn,{className:"size-3.5"}),e.jsx("p",{className:"",children:s.qualifiedEntityName?`${s.qualifiedEntityName}.${s.name}`:s.name})]}),e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(j,{className:t.cn("size-3 flex-shrink-0 text-gray-500",u==="string"?"text-blue-500":"",u==="number"?"text-green-500":"",u==="date"?"text-purple-500":"",u==="boolean"?"text-orange-500":"")}),e.jsx("p",{className:t.cn("text-xs font-normal text-gray-500"),children:s.dataType})]})]})})]})}),e.jsx("button",{onClick:v=>{v.stopPropagation(),l(!d)},className:"invisible flex-shrink-0 text-gray-400 hover:text-gray-600 group-hover/container:visible",children:d?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronRight,{className:"h-4 w-4"})})]}),d&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(t.Card,{className:"",children:e.jsxs(t.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ot,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:s.label||s.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:s.name})]}),e.jsx(t.Badge,{variant:"outline",className:"mt-2 text-xs",children:s.dataType})]})})})]})}function Qa({entityGroup:s,fields:a,isOpen:n,onToggle:r}){return e.jsxs(t.Collapsible,{open:n,onOpenChange:r,children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 rounded-md px-3 py-2 hover:bg-muted",children:[e.jsx("span",{className:"flex-1 text-left text-sm font-medium",children:s.label||s.entityName}),e.jsxs("span",{className:"text-xs text-gray-500",children:["(",a.length,")"]}),n?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronRight,{className:"h-4 w-4"})]}),e.jsx(t.CollapsibleContent,{className:"mt-1 space-y-1",children:e.jsx(t.SortableContext,{items:a.map(o=>o.id),strategy:t.verticalListSortingStrategy,children:a.map(o=>e.jsx(Ua,{field:o},o.id))})})]})}function Wa(){const[s,a]=L.useState(""),[n,r]=L.useState(new Set),[o,i]=L.useState("all"),c=t.useEditorStore(I=>I.card.dataSource),{columns:d=[],columnGroups:l=[],isLoading:h,error:u}=t.useColumns(),m=d.filter(I=>I.name.toLowerCase().includes(s.toLowerCase())||I.dataType.toLowerCase().includes(s.toLowerCase())||I.qualifiedEntityName&&I.qualifiedEntityName.toLowerCase().includes(s.toLowerCase())),j=I=>I.dataType==="number"||I.dataType==="integer"||I.dataType==="float"||I.dataType==="decimal"||I.dataType==="currency"?"metrics":"dimensions",C=(o==="all"?m:m.filter(I=>j(I)===o)).reduce((I,k)=>{const N=k.qualifiedEntityName||"Other Fields";return I[N]||(I[N]={label:t.toLabel(k.entityName),fields:[]}),I[N].fields.push(k),I},{});L.useEffect(()=>{const I=Object.keys(C);r(new Set(I))},[Object.keys(C).join(",")]);const p=I=>{const k=new Set(n);k.has(I)?k.delete(I):k.add(I),r(k)},D=m.filter(I=>j(I)==="dimensions").length,f=m.filter(I=>j(I)==="metrics").length,y=m.filter(I=>j(I)==="calculated").length,O=m.length>0;return h?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(t.LoaderCircle,{className:"h-8 w-8 animate-spin text-gray-400"}),e.jsx("span",{className:"mt-2 text-sm text-gray-500",children:"Loading fields..."})]}):u?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(t.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:u.message||"Failed to load column data"})]}):!c||!c.selectedEntities||c.selectedEntities.length===0?e.jsx(t.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(t.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[d.length>0&&e.jsx("div",{className:"mb-4",children:e.jsx(t.Input$1,{type:"text",placeholder:"Search fields...",value:s,onChange:I=>a(I.target.value)})}),O&&e.jsx(t.Tabs,{defaultValue:"all",value:o,onValueChange:I=>i(I),className:"mb-4",children:e.jsxs(t.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(t.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:m.length})]}),e.jsxs(t.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(t.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:D})]}),e.jsxs(t.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(t.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:f})]}),e.jsxs(t.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(Rs,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:y})]})]})})]}),e.jsxs(t.CustomScrollArea,{className:"py-2",children:[e.jsxs("div",{className:"space-y-2",children:[Object.entries(C).map(([I,k])=>{const N=l.find(S=>S.entityName===I)||{entityName:I,label:k.label};return e.jsx(Qa,{entityGroup:N,fields:k.fields,isOpen:n.has(I),onToggle:()=>p(I)},I)}),Object.keys(C).length===0&&d.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]}),Object.keys(C).length===0&&d.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"}),e.jsx(t.ScrollBar,{orientation:"vertical"})]})]})}function Xa(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(Wa,{})," "]})}function Za({initialJoinPlan:s,availableDataSources:a}){const[n,r]=L.useState(s),[o,i]=L.useState(new Set),c=()=>{const N=n.joins.length>0?Math.max(...n.joins.map(w=>w.sequence))+1:1,S={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:N,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,S]}),i(new Set([...o,S.id]))},d=N=>{r({...n,joins:n.joins.filter(S=>S.id!==N)}),i(new Set([...o].filter(S=>S!==N)))},l=(N,S)=>{var x,B;const w=n.joins.find(A=>A.id===N);if(!w)return;const E={...w,...S},g=n.joins.map(A=>A.id===N?E:A);if((x=E.source)!=null&&x.name&&((B=E.target)!=null&&B.name)&&E.joinKeyGroups[0].keys.length===0){const A=a.find(F=>{var P;return F.name===((P=E.source)==null?void 0:P.name)}),T=a.find(F=>{var P;return F.name===((P=E.target)==null?void 0:P.name)}),b={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(A==null?void 0:A.name)||"",entityName:(A==null?void 0:A.name)||"",entityType:(A==null?void 0:A.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(T==null?void 0:T.name)||"",entityName:(T==null?void 0:T.name)||"",entityType:(T==null?void 0:T.type)||"table"},operator:"="},M=[...E.joinKeyGroups];M[0]={...M[0],keys:[b]},E.joinKeyGroups=M,g[g.findIndex(F=>F.id===N)]=E}r({...n,joins:g})};return{joinPlan:n,expandedJoins:o,setJoinPlan:r,addJoin:c,removeJoin:d,updateJoin:l,moveJoinUp:N=>{const S=n.joins.findIndex(w=>w.id===N);if(S>0){const w=[...n.joins],E={...w[S]},g={...w[S-1]};w[S]=g,w[S-1]=E,w.forEach((B,A)=>{B.sequence=A+1});const x={...n,joins:w};r(x)}},moveJoinDown:N=>{const S=n.joins.findIndex(w=>w.id===N);if(S<n.joins.length-1){const w=[...n.joins],E={...w[S]},g={...w[S+1]};w[S]=g,w[S+1]=E,w.forEach((B,A)=>{B.sequence=A+1});const x={...n,joins:w};r(x)}},toggleJoinExpansion:N=>{const S=new Set(o);S.has(N)?S.delete(N):S.add(N),i(S)},getAvailableSourceEntities:N=>{if(n.joins.length===0)return a;const S=n.joins.findIndex(E=>E.id===N);if(S===0)return a;const w=new Set;return n.baseEntity.name&&w.add(n.baseEntity.name),n.joins.slice(0,S).forEach(E=>{w.add(E.source.name),w.add(E.target.name)}),a.filter(E=>w.has(E.name))},getAvailableTargetEntities:N=>a.filter(S=>S.name!==N),addJoinKeyGroup:N=>{const S=n.joins.find(E=>E.id===N);if(!S)return;const w=[...S.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];l(N,{joinKeyGroups:w})},updateGroupOperator:(N,S,w)=>{const E=n.joins.find(x=>x.id===N);if(!E)return;const g=[...E.joinKeyGroups];g[S]={...g[S],operator:w},l(N,{joinKeyGroups:g})},removeJoinKeyGroup:(N,S)=>{const w=n.joins.find(g=>g.id===N);if(!w)return;const E=[...w.joinKeyGroups];E.splice(S,1),l(N,{joinKeyGroups:E})},addJoinKey:(N,S)=>{const w=n.joins.find(A=>A.id===N);if(!w)return;const E=a.find(A=>A.name===w.source.name),g=a.find(A=>A.name===w.target.name),x=[...w.joinKeyGroups],B={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(E==null?void 0:E.name)||"",entityName:(E==null?void 0:E.name)||"",entityType:(E==null?void 0:E.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(g==null?void 0:g.name)||"",entityName:(g==null?void 0:g.name)||"",entityType:(g==null?void 0:g.type)||"table"},operator:"="};x[S]={...x[S],keys:[...x[S].keys,B]},l(N,{joinKeyGroups:x})},updateJoinKey:(N,S,w,E,g)=>{const x=n.joins.find(M=>M.id===N);if(!x)return;const B=a.find(M=>M.name===x.source.name),A=a.find(M=>M.name===x.target.name),T=[...x.joinKeyGroups],b=T[S].keys[w];E==="sourceColumnName"&&B?T[S].keys[w]={...b,source:{...b.source,name:g}}:E==="targetColumnName"&&A?T[S].keys[w]={...b,target:{...b.target,name:g}}:E==="operator"&&(T[S].keys[w]={...b,operator:g}),l(N,{joinKeyGroups:T})},removeJoinKey:(N,S,w)=>{const E=n.joins.find(x=>x.id===N);if(!E)return;const g=[...E.joinKeyGroups];g[S].keys.splice(w,1),l(N,{joinKeyGroups:g})},generateSQLPreview:()=>{const N=[...n.joins].sort((E,g)=>E.sequence-g.sequence),S=n.baseEntity;if(!S.name)return"SELECT * FROM table -- Please select a base entity";let w=`SELECT *
368
+ `;j(z)}function F(){return e.jsxs(e.Fragment,{children:[r&&e.jsx("div",{className:"relative flex w-1/3 min-w-0 grow overflow-hidden text-xs",role:"editor-filter-container",children:e.jsx("div",{className:"mt-2 w-[99%]",children:e.jsx($n,{jsonString:JSON.stringify(h,null,2)})})}),h&&h.length>0&&e.jsx(t.Button,{variant:"ghost",onClick:()=>o(!r),className:"absolute bottom-0 right-6 size-7 p-1",children:r?e.jsx(t.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(t.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function P(){return e.jsxs(t.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(t.ResizablePanel,{id:"1",order:1,defaultSize:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(_n,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(t.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(t.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(Gn,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function V(){return e.jsxs("div",{role:"editor-controls",className:"item-center flex flex-wrap justify-between gap-2 px-6 py-4",children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsxs(t.Button,{title:"Shift + Enter",disabled:w||E,onClick:()=>{T()},className:"h-8 shrink-0",size:"sm",children:[w||E?e.jsx(t.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(t.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(Jt,{sql:S==null?void 0:S.sql,error:b,onDebugWithAssistant:M}),e.jsx(t.EditorClearButton,{}),e.jsx(t.Toggle,{pressed:a,onPressedChange:z=>n(z),className:"",size:"sm",children:e.jsx(qn,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{O(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:c?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.EditorCancelButton,{}),e.jsx(t.EditorAcceptButton,{})]})]})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[P(),F()]}),V()]})}function Hn({data:s}){var c;const[a,n]=L.useState([]),o=Object.keys(s[0]).map(d=>({accessorKey:d,header:({column:l})=>{const h=l.getIsSorted();return e.jsx("div",{className:"flex gap-2",children:e.jsxs("div",{className:"flex cursor-pointer items-center",onClick:()=>l.toggleSorting(l.getIsSorted()==="asc"),children:[d,h==="asc"?e.jsx(t.TriangleUpIcon,{className:"ml-2 h-5 w-5"}):h==="desc"?e.jsx(t.TriangleDownIcon,{className:"ml-2 h-5 w-5"}):null]})})}})),i=t.useReactTable({data:s,columns:o,getCoreRowModel:t.getCoreRowModel(),getPaginationRowModel:t.getPaginationRowModel(),onSortingChange:n,getSortedRowModel:t.getSortedRowModel(),manualPagination:!0,state:{sorting:a}});return e.jsxs(t.CustomScrollArea,{className:"grow overflow-auto font-mono text-xs text-foreground/95",children:[e.jsxs("table",{className:"w-full",children:[e.jsx(t.TableHeader,{className:"sticky top-0 z-50 h-0 bg-muted",children:i.getHeaderGroups().map(d=>e.jsx(t.TableRow,{className:"",children:d.headers.map(l=>e.jsx(t.TableHead,{className:"h-11 font-semibold text-foreground",children:l.isPlaceholder?null:t.flexRender(l.column.columnDef.header,l.getContext())},l.id))},d.id))}),e.jsx(t.TableBody,{children:(c=i.getRowModel().rows)!=null&&c.length?i.getRowModel().rows.map(d=>e.jsx(t.TableRow,{className:"h-11 whitespace-nowrap py-2","data-state":d.getIsSelected()&&"selected",children:d.getVisibleCells().map(l=>e.jsx(t.TableCell,{className:"py-2",children:t.flexRender(l.column.columnDef.cell,l.getContext())},l.id))},d.id)):e.jsx(t.TableRow,{children:e.jsx(t.TableCell,{colSpan:o.length,className:"h-24 text-center",children:"No results."})})})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function Yn({card:s}){var j,O,I,k,N,S,w,E,g,x,B;const[a,n]=L.useState(!1),[r,o]=L.useState([]),{authToken:i}=t.useSemaphorContext(),c=t.getTokenParams(i==null?void 0:i.accessToken),d=t.useDashboardStore(A=>A.themeStyle),l={colors:((O=(j=d==null?void 0:d.chart)==null?void 0:j.dataset)==null?void 0:O.backgroundColor)||[]};(I=s.customCardPreferences)!=null&&I.inputData;const{getCard:h}=t.useCustomVisual(((k=s.customCardPreferences)==null?void 0:k.url)||""),u=((N=s.customCardPreferences)==null?void 0:N.visualType)||"single",m=t.useEditorStore(A=>A.frame),{setCustomCardPreferences:y}=t.useEditorActions(),{data:v}=t.useDashboardCardQuery(s),C=L.useCallback((A,T)=>{o(b=>({...b,[A]:T}))},[]);if(!((S=s.customCardPreferences)!=null&&S.componentName))return null;const p=h((w=s.customCardPreferences)==null?void 0:w.componentName);function D(A){n(A)}const f=Object.keys(((E=s.customCardPreferences)==null?void 0:E.dataInputCardIds)||{}).map(A=>{var M,F,P;const T=(F=(M=s.customCardPreferences)==null?void 0:M.dataInputCardIds)==null?void 0:F[A].cardId,b=(P=m==null?void 0:m.cards)==null?void 0:P.find(V=>V.id===T);return b||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(L.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[p&&u==="single"&&e.jsx(p,{params:c,theme:l,settings:(g=s.customCardPreferences)==null?void 0:g.settings,onDataChange:C,data:(v==null?void 0:v.records)||[]}),p&&u==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((x=s.customCardPreferences)==null?void 0:x.dataInputCardIds)||{}).map(A=>{var M,F,P;const T=(F=(M=s.customCardPreferences)==null?void 0:M.dataInputCardIds)==null?void 0:F[A].cardId,b=(P=m==null?void 0:m.cards)==null?void 0:P.find(V=>V.id===T);if(b)return e.jsx(t.MultiInputEmptyRenderer,{onLoadingStatus:D,onDataChange:C,dataInputIndex:A,card:b},b.id+A)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(p,{theme:l,onDataChange:C,settings:f.map(A=>{var T;return(T=A==null?void 0:A.customCardPreferences)==null?void 0:T.settings}),data:f.map(A=>A!=null&&A.id?r==null?void 0:r[A.id]:[])})})]})]},(B=s.customCardPreferences)==null?void 0:B.componentName)})}function Ut({className:s,...a}){var f;const n=t.useEditorStore(j=>j.card),r=((f=n.customCardPreferences)==null?void 0:f.showCardHeader)??!0,o=t.useEditorStore(j=>j.frame),i=t.useDashboardStore(j=>j.dashboard.filters);t.useEditorStore(j=>j.actions.setRunSql);const{updateFilter:c}=t.useDashboardActions(),d=i==null?void 0:i.find(j=>j.id===o.filterId),{data:l,isLoading:h,isFetching:u,errorMessage:m}=t.useDashboardCardQuery(n),{setCard:y}=t.useEditorActions(),{data:v}=t.useTopoJson(n),C=L.useMemo(()=>!n.id||!(l!=null&&l.records)?null:t.createChartConfig({card:n,data:l==null?void 0:l.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:v}),[n.id,l==null?void 0:l.records,n.type,n.queryConfig,n.customCfg,n.preferences,v]);function p(j){return e.jsx(Yn,{card:j})}function D(){if(l!=null&&l.records&&(l==null?void 0:l.records.length)===0&&!h&&!u)return m?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(t.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:n.mode!=="explorer"?"Error fetching data. Please check your SQL or Python code.":"Error fetching data. Please check your chart configuration"})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(t.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if(!n.id)return null;if(n.type==="custom")return p(n);if(!["table","custom"].includes(n.type)&&C)return e.jsx(e.Fragment,{children:h||u?e.jsx(e.Fragment,{}):e.jsx(t.ChartJsVisual,{cfg:C})});if(n.type==="table"&&(l!=null&&l.records)&&(l==null?void 0:l.records.length)>0)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(t.TableVisual,{card:n,data:l==null?void 0:l.records})})}return e.jsxs(t.Card,{role:"editor-visual-card",className:t.cn("relative flex h-full flex-col rounded-none",s),...a,children:[r&&e.jsxs(t.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{children:[e.jsx(t.Editable,{enabled:!0,text:n.title,onSave:j=>y({...n,title:j}),children:e.jsx("div",{className:"flex items-center gap-5",children:e.jsx(t.CardTitle,{className:"text-base",children:n.title||"Add title"})})},n.title),e.jsx(t.Editable,{enabled:!0,text:n.description||"",onSave:j=>y({...n,description:j}),children:e.jsx(t.CardDescription,{children:n.description||"Add description"})},n.description)]}),d&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Editable,{enabled:!0,className:"my-1",text:d.title||d.column,onSave:j=>c({...d,title:j}),children:e.jsx(t.Label,{children:d.title})}),e.jsx(t.FilterComponent,{filter:d})]})]}),e.jsx(t.CardContent,{className:"flex grow flex-col",children:D()})]})}const qe=({language:s,value:a,onChange:n,readonly:r})=>e.jsx(t.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:s,value:a,onChange:n}),Kn=()=>e.jsxs(t.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(t.DialogTitle,{children:"Customize Card"})}),e.jsxs(t.DialogDescription,{children:["See the configuration options and documentation",e.jsx("a",{target:"_blank",className:"ml-1 text-blue-500 underline",href:"https://www.chartjs.org/docs/latest/samples/bar/vertical.html",children:"here."})]})]}),Un=({customCode:s,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:o})=>e.jsxs(t.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(t.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(t.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(t.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(t.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(t.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(qe,{language:"json",value:n,onChange:r})}),e.jsx(t.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(qe,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(t.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(qe,{language:"javascript",value:s,onChange:o})})]}),Qn=({error:s,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:o})=>e.jsxs(t.DialogFooter,{className:"flex items-center",children:[e.jsx(t.Label,{className:"mr-2 text-red-500",children:s}),e.jsx(t.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(t.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(t.Button,{onClick:o,variant:"outline",children:"Close"})]});function Wn(){const[s,a]=L.useState(!1),[n,r]=L.useState(""),[o,i]=L.useState(""),[c,d]=L.useState(""),[l,h]=L.useState(""),u=t.useEditorStore(k=>k.card),m=t.useEditorStore(k=>k.card.customCfg),y=m?JSON.stringify(m,null,2):"",{data:v}=t.useDashboardCardQuery(u),{data:C}=t.useTopoJson(u),{setCardCustomCfg:p,setCustomVisualCode:D}=t.useEditorActions(),f=k=>{var N,S;return JSON.stringify({...k,data:{...k.data,datasets:(S=(N=k.data)==null?void 0:N.datasets)==null?void 0:S.map(w=>({...w,data:[]}))}},null,2)},j=()=>{var N,S;if(!((N=v==null?void 0:v.records)!=null&&N.length))return;const k=t.createChartConfig({card:u,data:v.records,cardType:u.type,queryConfig:u.queryConfig,preferences:u.preferences,topoJson:C});if(k){r(f(k)),d(((S=u.preferences)==null?void 0:S.customVisualCode)||"");const w=t.merge(k,m);i(f(w))}},O=()=>{try{if(c&&D(c),o){const k=JSON.parse(o),N=t.getObjectDiff(JSON.parse(n),k);p(N),h("")}}catch{h("Invalid JSON configuration")}},I=Object.keys(m||{}).length===0;return e.jsxs(t.Dialog,{open:s,onOpenChange:a,children:[e.jsx(t.DialogTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Customize Visual",onClick:j,className:I?"":"text-green-600 hover:text-green-700",children:e.jsx(t.Settings,{className:"h-4 w-4"})})}),e.jsxs(t.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(Kn,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackEditorCard,children:e.jsx(Ut,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Un,{customCode:c,cardCustomCfgString:y,mergedConfig:o,onConfigChange:k=>i(k??""),onCodeChange:k=>d(k??"")})]}),e.jsx(Qn,{error:l,hasCardCustomConfig:!!m,onReset:()=>{i(n),p(null)},onApply:O,onClose:()=>a(!1)})]})]})}function Qt(s){const[a,n]=L.useState(null);return a}function Wt(){const{authToken:s}=t.useSemaphorContext(),{data:a,isLoading:n,isFetching:r,isError:o}=t.useQuery({queryKey:["plugins",s==null?void 0:s.accessToken],queryFn:()=>t.getPlugins(s==null?void 0:s.accessToken)});return{data:a,isLoading:n,isFetching:r,isError:o}}function Xn({onChartTypeChange:s}){const[a,n]=L.useState([]),{setCardCustomCfg:r,setCardPreferences:o,setCardType:i,setCustomCardPreferences:c}=t.useEditorActions(),{data:d}=Wt();function l(h,u){r(null),o({}),i(h),u&&c({type:"component",visualType:"single",url:u.url,componentName:u.name,icon:u.icon}),s==null||s()}return L.useEffect(()=>{(async()=>{var u;if(d){const y=(await Promise.all((u=d==null?void 0:d.plugins)==null?void 0:u.map(async v=>(await t.loadManifest(v.value)).visuals.map(D=>({name:D.name,icon:D.icon,url:v.value}))))).flat();n(y)}})()},[d]),a.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(t.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:a.map((h,u)=>e.jsx(Zn,{text:h.name,onClick:()=>l("custom",h),icon:h.icon},h.url+h.name+u))})]})}const Zn=({text:s,icon:a,onClick:n})=>{const r=Qt(),o=s.charAt(0).toUpperCase();return e.jsx(t.IconButton,{onClick:n,tooltip:s,children:r?e.jsx(r,{className:"h-4 w-4"}):o})};function it(s){return ge({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm87.63,96H191.48A64.1,64.1,0,0,0,136,64.52V40.37A88.13,88.13,0,0,1,215.63,120ZM120,120H80.68A48.09,48.09,0,0,1,120,80.68Zm0,16v39.32A48.09,48.09,0,0,1,80.68,136Zm16,0h39.32A48.09,48.09,0,0,1,136,175.32Zm0-16V80.68A48.09,48.09,0,0,1,175.32,120ZM120,40.37V64.52A64.1,64.1,0,0,0,64.52,120H40.37A88.13,88.13,0,0,1,120,40.37ZM40.37,136H64.52A64.1,64.1,0,0,0,120,191.48v24.15A88.13,88.13,0,0,1,40.37,136ZM136,215.63V191.48A64.1,64.1,0,0,0,191.48,136h24.15A88.13,88.13,0,0,1,136,215.63Z"},child:[]}]})(s)}function ea(s){return ge({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M48,180c0,11,7.18,20,16,20a14.24,14.24,0,0,0,10.22-4.66A8,8,0,0,1,85.78,206.4,30.06,30.06,0,0,1,64,216c-17.65,0-32-16.15-32-36s14.35-36,32-36a30.06,30.06,0,0,1,21.78,9.6,8,8,0,0,1-11.56,11.06A14.24,14.24,0,0,0,64,160C55.18,160,48,169,48,180Zm79.6-8.69c-4-1.16-8.14-2.35-10.45-3.84-1.25-.81-1.23-1-1.12-1.9a4.57,4.57,0,0,1,2-3.67c4.6-3.12,15.34-1.73,19.82-.56A8,8,0,0,0,142,145.86c-2.12-.55-21-5.22-32.84,2.76a20.58,20.58,0,0,0-9,14.95c-2,15.88,13.65,20.41,23,23.11,12.06,3.49,13.12,4.92,12.78,7.59-.31,2.41-1.26,3.34-2.14,3.93-4.6,3.06-15.17,1.56-19.55.36A8,8,0,0,0,109.94,214a61.34,61.34,0,0,0,15.19,2c5.82,0,12.3-1,17.49-4.46a20.82,20.82,0,0,0,9.19-15.23C154,179,137.49,174.17,127.6,171.31Zm83.09-26.84a8,8,0,0,0-10.23,4.84L188,184.21l-12.47-34.9a8,8,0,0,0-15.07,5.38l20,56a8,8,0,0,0,15.07,0l20-56A8,8,0,0,0,210.69,144.47ZM216,88v24a8,8,0,0,1-16,0V96H152a8,8,0,0,1-8-8V40H56v72a8,8,0,0,1-16,0V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88Zm-27.31-8L160,51.31V80Z"},child:[]}]})(s)}function lt(s){return ge({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M6 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"},child:[]},{tag:"path",attr:{d:"M16 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"},child:[]},{tag:"path",attr:{d:"M14.5 7.5m-4.5 0a4.5 4.5 0 1 0 9 0a4.5 4.5 0 1 0 -9 0"},child:[]}]})(s)}function ct(s){return ge({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4.387 3h15.226a1 1 0 0 1 .948 1.316l-5.105 15.316a2 2 0 0 1 -1.898 1.368h-3.116a2 2 0 0 1 -1.898 -1.368l-5.104 -15.316a1 1 0 0 1 .947 -1.316"},child:[]},{tag:"path",attr:{d:"M5 9h14"},child:[]},{tag:"path",attr:{d:"M7 15h10"},child:[]}]})(s)}function dt(s){return ge({attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"m2 19.99 7.5-7.51 4 4 7.09-7.97L22 9.92l-8.5 9.56-4-4-6 6.01-1.5-1.5zm1.5-4.5 6-6.01 4 4L22 3.92l-1.41-1.41-7.09 7.97-4-4L2 13.99l1.5 1.5z"},child:[]}]})(s)}function ut(s){return ge({attr:{version:"1.2",baseProfile:"tiny",viewBox:"0 0 24 24"},child:[{tag:"path",attr:{d:"M4 18c-.552 0-1-.448-1-1v-6.382l-.553.276c-.495.248-1.095.046-1.342-.447-.247-.494-.046-1.094.448-1.342l2-1c.31-.155.678-.139.973.044.294.183.474.504.474.851v8c0 .552-.448 1-1 1zM13 18h-5c-.404 0-.769-.244-.924-.617-.155-.374-.069-.804.217-1.09l4-4c.254-.254.394-.591.394-.95 0-.358-.14-.695-.394-.949-.508-.508-1.39-.508-1.9.001-.253.252-.393.589-.393.948 0 .552-.448 1-1 1s-1-.448-1-1c0-.894.348-1.733.98-2.364 1.265-1.263 3.464-1.263 4.727.001.632.631.979 1.471.979 2.363 0 .893-.348 1.733-.979 2.364l-2.293 2.293h2.586c.552 0 1 .448 1 1s-.448 1-1 1zM20.955 12.377c.338-.457.545-1.016.545-1.627 0-1.517-1.234-2.75-2.75-2.75-1.031 0-1.966.569-2.44 1.484-.254.49-.063 1.094.428 1.348.49.254 1.094.062 1.348-.428.128-.249.383-.404.664-.404.414 0 .75.336.75.75s-.336.75-.75.75c-.552 0-1 .448-1 1s.448 1 1 1c.689 0 1.25.561 1.25 1.25s-.561 1.25-1.25 1.25-1.25-.561-1.25-1.25c0-.552-.448-1-1-1s-1 .448-1 1c0 1.792 1.458 3.25 3.25 3.25s3.25-1.458 3.25-3.25c0-.939-.406-1.779-1.045-2.373z"},child:[]}]})(s)}function Xt({onChartTypeChange:s,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:o}=t.useEditorStore(u=>u.actions),{setCardCustomCfg:i,setCustomCardPreferences:c,setQueryConfig:d}=t.useEditorActions();function l(u,m){i(null),r({}),n(u),["custom","text","map"].includes(u)&&(o(!0),d(void 0)),s==null||s()}const h=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(t.IconButton,{openDelay:h,tooltip:"Table",onClick:()=>l("table"),className:"h-10 p-4",children:e.jsx(Oe,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Bar Chart",onClick:()=>l("bar"),className:"h-10 p-4",children:e.jsx(Ae,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Line Chart",onClick:()=>l("line"),className:"h-10 p-4",children:e.jsx(Le,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Stacked Bar Chart",onClick:()=>l("stackedBar"),className:"h-10 p-4",children:e.jsx(Ke,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Stacked Line Chart",onClick:()=>l("stackedLine"),className:"h-10 p-4",children:e.jsx(dt,{className:t.cn("size-5",a),strokeWidth:0})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Scatter Chart",onClick:()=>l("scatter"),className:"h-10 p-4",children:e.jsx(We,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Bubble Chart",onClick:()=>l("bubble"),className:"h-10 p-4",children:e.jsx(lt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Pie Chart",onClick:()=>l("pie"),className:"h-10 p-4",children:e.jsx(Qe,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Doughnut Chart",onClick:()=>l("doughnut"),className:"h-10 p-4",children:e.jsx(Xe,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Funnel Chart",onClick:()=>l("funnel"),className:"h-10 p-4",children:e.jsx(ct,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Radar Chart",onClick:()=>l("radar"),className:"h-10 p-4",children:e.jsx(tt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Polar Area Chart",onClick:()=>l("polarArea"),className:"h-10 p-4",children:e.jsx(it,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Tornado Chart",onClick:()=>l("tornado"),className:"h-10 p-4",children:e.jsx(nt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{tooltip:"Range Chart",onClick:()=>l("range"),className:"h-10 p-4",children:e.jsx(Ue,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"KPI",onClick:()=>l("kpi"),className:"h-10 p-4",children:e.jsx(ut,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Text",onClick:()=>l("text"),className:"h-10 p-4",children:e.jsx(Tt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{tooltip:"Map",onClick:()=>l("map"),className:"h-10 p-4",children:e.jsx(et,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:h,tooltip:"Custom",onClick:()=>l("custom"),className:"h-10 p-4",children:e.jsx(st,{className:t.cn("size-5",a)})})]})}function ta({chartType:s,className:a,customIcon:n,componentName:r}){const o=Qt();switch(s){case"bar":return e.jsx(Ae,{className:a});case"line":return e.jsx(Le,{className:a});case"pie":return e.jsx(Qe,{className:a});case"radar":return e.jsx(tt,{className:a});case"scatter":return e.jsx(We,{className:a});case"bubble":return e.jsx(lt,{className:a});case"doughnut":return e.jsx(Xe,{className:a});case"stackedBar":return e.jsx(Ke,{className:a});case"stackedLine":return e.jsx(dt,{className:a});case"polarArea":return e.jsx(it,{className:a});case"funnel":return e.jsx(ct,{className:a});case"tornado":case"pyramid":return e.jsx(nt,{className:a});case"range":return e.jsx(Ue,{className:a});case"kpi":return e.jsx(ut,{className:a});case"text":return e.jsx(Ft,{className:a});case"map":return e.jsx(et,{className:a});case"custom":return n&&o?e.jsx(o,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(st,{className:a});default:return e.jsx(Oe,{className:a})}}function Zt({variant:s="ghost"}){var i,c;const[a,n]=L.useState(!1),r=t.useEditorStore(d=>d.card),o=r.type;return t.useDashboardStore(d=>d.isVisualEditing),e.jsxs(t.Popover,{open:a,onOpenChange:n,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{size:"sm",variant:s||"ghost",children:e.jsx(ta,{className:"size-4",chartType:o,customIcon:(i=r.customCardPreferences)==null?void 0:i.icon,componentName:(c=r.customCardPreferences)==null?void 0:c.componentName})})}),e.jsxs(t.PopoverContentCustom,{onOpenAutoFocus:d=>d.preventDefault(),className:"w-72 p-1",children:[e.jsx(Xt,{onChartTypeChange:()=>n(!1)}),e.jsx(Xn,{onChartTypeChange:()=>n(!1)})]})]})}const Se="focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0";function kt(s,a){var r,o,i;const n=t.getNumberAxis(s,{});return["pie","doughnut","polarArea","funnel"].includes(a)?"category":((i=(o=(r=s==null?void 0:s.chartOptions)==null?void 0:r.scales)==null?void 0:o[n])==null?void 0:i.type)||"linear"}function sa(){var M,F,P,V,z,U;const[s,a]=L.useState(!1),n=t.useEditorStore(R=>{var q;return(q=R.card)==null?void 0:q.preferences}),r=t.useEditorStore(R=>{var q;return(q=R.card)==null?void 0:q.type}),o=t.getNumberAxis(n,{}),[i,c]=L.useState(kt(n,r)),[d,l]=L.useState(((P=(F=(M=n==null?void 0:n.chartOptions)==null?void 0:M.scales)==null?void 0:F[o])==null?void 0:P.min)||""),[h,u]=L.useState(((U=(z=(V=n==null?void 0:n.chartOptions)==null?void 0:V.scales)==null?void 0:z[o])==null?void 0:U.max)||""),[m,y]=L.useState(d||h?"custom":"auto"),[v,C]=L.useState(""),[p,D]=L.useState(0),[f,j]=L.useState(""),[O,I]=L.useState(""),[k,N]=L.useState(""),S=t.useEditorStore(R=>R.actions.setCardPreferences),{updateCardInFrame:w}=t.useEditorActions(),E=t.useEditorStore(R=>R.card),g=["pie","doughnut","polarArea","funnel"].includes(r);L.useEffect(()=>{var R,q,H,Q,G,$,J,X,te,ne,le,oe,ce,ie;c(kt(n,r)),l(((H=(q=(R=n==null?void 0:n.chartOptions)==null?void 0:R.scales)==null?void 0:q[o])==null?void 0:H.min)===0?0:""),u((($=(G=(Q=n==null?void 0:n.chartOptions)==null?void 0:Q.scales)==null?void 0:G[o])==null?void 0:$.max)||""),C(((ne=(te=(X=(J=n==null?void 0:n.chartOptions)==null?void 0:J.scales)==null?void 0:X[o])==null?void 0:te.ticks)==null?void 0:ne.stepSize)||""),D(((le=n==null?void 0:n.numberAxisFormat)==null?void 0:le.decimalPlaces)||0),j(((oe=n==null?void 0:n.numberAxisFormat)==null?void 0:oe.suffix)||""),I(((ce=n==null?void 0:n.numberAxisFormat)==null?void 0:ce.currency)||""),N(((ie=n==null?void 0:n.numberAxisFormat)==null?void 0:ie.locale)||"")},[s,n,o,r]);function x(R,q){return q===""||/^[0-9\b]+$/.test(q)?Number(q):Number(R)}function B(){const R=[...new Set(t.LOCALE_CURRENCY_PAIRS.map(q=>q.currency))];return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-6 items-center gap-2",children:[e.jsx(t.Label,{className:"col-span-2 hover:cursor-pointer hover:underline",htmlFor:"currency",children:e.jsx("a",{target:"_blank",href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat",children:"Currency"})}),e.jsxs(t.Select,{value:O||"none",onValueChange:q=>I(q==="none"?"":q),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Currency"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),R.map(q=>e.jsx(t.SelectItem,{value:q,children:q},q))]})})]}),e.jsxs(t.Select,{value:k,onValueChange:q=>N(q),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Locale"}),t.LOCALE_CURRENCY_PAIRS.map(q=>e.jsx(t.SelectItem,{value:q.locale,children:q.locale},q.locale))]})})]})]}),e.jsxs("div",{className:"grid grid-cols-9 items-center gap-2",children:[e.jsx(t.Label,{className:"col-span-3",htmlFor:"format",children:"Decimals"}),e.jsx(t.Input,{value:p,onChange:q=>D(Number(q.target.value)),id:"format",className:`col-span-6 h-8 w-full tracking-wide ${Se}`})]})]})}function A(){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-4 space-y-2",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the scale for number axis"})}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"scale",children:"Type"}),e.jsxs(t.Select,{disabled:g,value:i,onValueChange:R=>c(R),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{id:"type",children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Option"}),e.jsx(t.SelectItem,{value:"linear",children:"Linear"}),e.jsx(t.SelectItem,{value:"logarithmic",children:"Logarithmic"}),e.jsx(t.SelectItem,{value:"category",children:"Category"})]})})]})]}),i=="linear"&&e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2 py-1",children:[e.jsx(t.Label,{htmlFor:"scale-option",children:"Setup"}),e.jsxs(t.RadioGroup,{disabled:g,id:"scale-option",value:m,onValueChange:R=>y(R),className:"col-span-2 flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"auto",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Auto"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"custom",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Custom"})]})]})]}),m==="custom"&&i=="linear"&&T()]})}function T(){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"range",children:"Range"}),e.jsx(t.Input,{id:"min",value:d,onChange:R=>l(q=>x(q,R.target.value)),className:`col-span-1 h-8 w-full ${Se}`}),e.jsx(t.Input,{value:h,onChange:R=>u(q=>x(q,R.target.value)),id:"max",className:`col-span-1 h-8 w-full ${Se}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"step-size",children:"Step Size"}),e.jsx(t.Input,{value:v,onChange:R=>C(q=>x(q,R.target.value)),id:"step-size",className:`col-span-1 h-8 w-full ${Se}`})]})]})}function b(){var Q;let R={};m==="custom"&&(R={min:d,max:h,ticks:{stepSize:v}});const q={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,scales:{...(Q=n==null?void 0:n.chartOptions)==null?void 0:Q.scales,[o]:{type:i,...i==="linear"?R:{}}}},numberAxisFormat:{decimalPlaces:p,suffix:f,currency:O,locale:k}};console.log(q),S(q);const H={...E,preferences:q};w(H)}return e.jsxs(t.Popover,{onOpenChange:R=>a(R),children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Format Number",children:e.jsx(Hs,{className:"size-4"})})}),e.jsx(t.PopoverContentCustom,{align:"end",className:"max-w-65",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Format Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the format for number axis"})]}),e.jsxs("div",{className:"grid gap-2",children:[B(),A(),e.jsx(t.SelectSeparator,{}),e.jsx("div",{className:"grid grid-cols-3",children:e.jsx(t.Button,{onClick:b,variant:"secondary",className:"col-span-1 col-start-3 h-8 w-full",children:"Apply"})})]})]})})]})}function na(){const s=t.useEditorStore(d=>{var l,h,u,m;return(m=(u=(h=(l=d.card.preferences)==null?void 0:l.chartOptions)==null?void 0:h.plugins)==null?void 0:u.legend)==null?void 0:m.position}),a=t.useEditorStore(d=>{var l,h,u,m;return(m=(u=(h=(l=d.card.preferences)==null?void 0:l.chartOptions)==null?void 0:h.plugins)==null?void 0:u.legend)==null?void 0:m.align}),n=t.useEditorStore(d=>{var l,h,u,m;return(m=(u=(h=(l=d.card.preferences)==null?void 0:l.chartOptions)==null?void 0:h.plugins)==null?void 0:u.legend)==null?void 0:m.display}),{setLegendOptions:r}=t.useEditorActions(),o=d=>{r({display:d,position:s,align:a})},i=d=>{r({display:n,position:d,align:a})},c=d=>{r({display:n,position:s,align:d})};return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Legend Settings",children:e.jsx(tn,{className:"size-4"})})}),e.jsx(t.PopoverContentCustom,{align:"end",className:"w-72",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Legend Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the legend options for the chart."})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"displayLegend",children:"Display"}),e.jsx("div",{className:"col-span-2 flex h-8 items-center",children:e.jsx(t.SmallSwitch,{checked:n,onCheckedChange:o,id:"displayLegend"})})]}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"position",children:"Position"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(t.IconButton,{tooltip:"Top",onClick:()=>i("top"),children:e.jsx(t.ArrowUp,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Left",onClick:()=>i("left"),children:e.jsx(Ms,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Bottom",onClick:()=>i("bottom"),children:e.jsx(t.ArrowDown,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Right",onClick:()=>i("right"),children:e.jsx(As,{className:"size-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"align",children:"Align"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(t.IconButton,{tooltip:"Start",onClick:()=>c("start"),children:e.jsx(ks,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Center",onClick:()=>c("center"),children:e.jsx(ws,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"End",onClick:()=>c("end"),children:e.jsx(Es,{className:"size-4"})})]})]})]})]})]})})]})}function aa(){const s=t.useEditorStore(i=>{var c,d;return(d=(c=i.card.preferences)==null?void 0:c.chartOptions)==null?void 0:d.indexAxis}),a=t.useEditorStore(i=>i.card.type),{setChartOrientation:n}=t.useEditorStore(i=>i.actions);function r(){return e.jsx(t.IconButton,{onClick:()=>{n(s==="x"||s===void 0?"y":"x")},tooltip:"Chart Orientation",children:s==="x"||s===void 0?e.jsx(vt,{className:"size-4"}):e.jsx(bt,{className:"size-4"})})}function o(){return e.jsx(t.IconButton,{onClick:()=>{n(s==="y"||s===void 0?"x":"y")},tooltip:"Chart Orientation",children:s==="y"||s===void 0?e.jsx(vt,{className:"size-4"}):e.jsx(bt,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?o():r()})}function es(){const s=t.useEditorStore(c=>c.card),a=t.useEditorStore(c=>c.isShowingVisual),n=t.useEditorStore(c=>{var d,l;return(l=(d=c.card)==null?void 0:d.preferences)==null?void 0:l.chartOptions}),r=t.getChartGridStyle(n),{setChartGrid:o}=t.useEditorActions();function i(){const c=["xy","none","x","y"],l=(c.indexOf(r)+1)%c.length;o(c[l])}return a?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(s.type)&&e.jsx(e.Fragment,{children:e.jsx(aa,{})}),!["kpi","text","custom","table"].includes(s.type)&&e.jsxs(e.Fragment,{children:[e.jsx(sa,{}),e.jsx(na,{})]}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(s.type)&&e.jsxs(t.IconButton,{tooltip:"Grid Style",onClick:i,children:[(r==="xy"||!r)&&e.jsx(Zs,{className:"size-4"}),r==="x"&&e.jsx(Gs,{className:"size-4"}),r==="y"&&e.jsx(xn,{className:"size-4"}),r==="none"&&e.jsx(jn,{className:"size-4"})]})]}):null}function ra(){const s=t.useEditorStore(C=>C.frame),a=t.useEditorStore(C=>C.card),{setFrame:n,setActiveTabCardId:r,setCard:o,updateCardInFrame:i}=t.useEditorActions(),c=(C,p)=>{C.dataTransfer.setData("tabIndex",p.toString())},d=C=>{C.preventDefault()},l=(C,p)=>{const D=C.dataTransfer.getData("tabIndex");if(D===p.toString())return;const f=Array.from(s.cards),[j]=f.splice(parseInt(D),1);f.splice(p,0,j),n({...s,cards:f})};function h(C){const p=s.cards.filter(j=>j.id!==C),D=p[0],f={...s,cards:p,activeCardId:D.id};n(f),r(D.id),o(D)}function u(C,p){const D={...s,cards:[...s.cards,p],activeCardId:C.id};n(D),r(p.id)}function m(){const C={...a,id:t.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};u(a,C)}function y(C){const p={connectionId:C.connectionId,lastSelectedDatabase:C.lastSelectedDatabase,lastSelectedSchema:C.lastSelectedSchema,lastSelectedTable:C.lastSelectedTable,lastSelectedDatamodelId:C.lastSelectedDatamodelId,id:t.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]};u(C,p)}function v(C,p){return C.cards.length===1&&(p.displayTab===!0||p.displayTab===void 0)||C.activeCardId!==p.id&&(p.displayTab===!0||p.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const D=p.displayTab===void 0?!1:!p.displayTab;o({...p,displayTab:D}),i({...p,displayTab:D})},children:p.displayTab===!0||p.displayTab===void 0?e.jsx(t.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(Ys,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(t.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[s.cards.map((C,p)=>e.jsxs(t.TabsTrigger,{draggable:!0,onDragStart:D=>c(D,p),onDragOver:d,onDrop:D=>l(D,p),className:"",value:C.id,children:[v(s,C),e.jsx(t.Editable,{enabled:s.activeCardId===C.id,text:C.tabTitle||C.title,onSave:D=>{o({...a,tabTitle:D}),i({...a,tabTitle:D})},children:C.tabTitle||C.title},C.id),s.activeCardId===C.id&&s.cards.length>1&&e.jsx(t.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>h(C.id)})]},C.id)),e.jsx(t.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>y(a),children:e.jsx(t.Plus,{className:"h-4 w-4"})}),e.jsx(t.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:m,children:e.jsx(Js,{className:"h-4 w-4"})})]})})}function ts(){const s=t.useEditorStore(p=>p.frame),a=t.useEditorStore(p=>p.card),n=t.useEditorStore(p=>p.isSqlRunning),r=t.useEditorStore(p=>p.isDevMode),{setFrame:o,setActiveTabCardId:i,setCard:c,setIsDevMode:d,setRunSql:l}=t.useEditorActions(),{data:h,isLoading:u,isFetching:m}=t.useDashboardCardQuery(a);function y(p){const D=s.cards.find(f=>f.id===p);if(D!=null&&D.sql){r||d(!0),i(p);return}if(D!=null&&D.queryConfig){r&&d(!1),v(p),i(p);return}r||v(p),i(p)}function v(p){const D={...s,cards:s.cards.map(j=>j.id===a.id?a:j),activeCardId:p};o(D);const f=D.cards.find(j=>j.id===p);f.sql&&l(!0),c(f)}function C(){return a.type==="kpi"?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(t.KPICard,{card:a,data:h==null?void 0:h.records,isPending:u})})}):a.type==="text"?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(t.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(t.TextCard,{isLoading:n,card:a,data:h==null?void 0:h.records})})})}):e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackEditorCard,children:e.jsx(Ut,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:y,value:s.activeCardId,className:"flex grow flex-col",children:[s.cards.map(p=>e.jsx(t.TabsContent,{className:"mt-0 grow",value:p.id,children:C()},p.id)),e.jsx(ra,{})]})}function we({children:s}){t.useEditorStore(j=>j.frame);const a=t.useEditorStore(j=>j.card),n=t.useEditorStore(j=>j.isDevMode),r=t.useEditorStore(j=>j.isShowingVisual),o=t.useDashboardStore(j=>j.isVisualEditing),i=t.useEditorStore(j=>j.pythonStdOut);t.useEditorStore(j=>j.actions.setRunSql);const{setFrame:c,setCard:d,setActiveTabCardId:l,runAssistant:h,setIsDevMode:u}=t.useEditorActions(),{data:m,isLoading:y,isFetching:v,errorMessage:C}=t.useDashboardCardQuery(a);function p(){const j=JSON.stringify(m==null?void 0:m.records,null,2),O=new Blob([j],{type:"application/json"}),I=URL.createObjectURL(O),k=document.createElement("a");k.href=I,k.download=`${a.title}.json`,k.click()}function D(){const O=[Object.keys(m==null?void 0:m.records.reduce((S,w)=>({...S,...w}),{})).join(","),...((m==null?void 0:m.records)||[]).map(S=>Object.values(S).join(","))].join(`
369
+ `),I=new Blob([O],{type:"text/csv"}),k=URL.createObjectURL(I),N=document.createElement("a");N.href=k,N.download=`${a.title}.csv`,N.click()}function f(){const j=`Can you get the documentation for ${a.type} chart?`;h(j)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[(y||v)&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 top-0 z-50 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(t.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(Zt,{}),o&&e.jsx(t.IconButton,{tooltip:"Visual Docs",onClick:f,children:e.jsx(Fs,{className:"size-4"})}),!["table","custom"].includes(a.type)&&o&&e.jsx(Wn,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(t.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:D,children:e.jsx(ea,{className:"size-4"})}),e.jsx(t.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:p,children:e.jsx(Us,{strokeWidth:1.5,className:"size-4"})}),e.jsx(t.CopyButton,{text:JSON.stringify(m==null?void 0:m.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[s,e.jsx(es,{})]}),n&&e.jsx(ia,{})]}),r?e.jsx(ts,{}):e.jsxs(t.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[i&&e.jsxs(e.Fragment,{children:[e.jsx(t.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:i&&e.jsx(oa,{})}),e.jsx(t.ResizableHandle,{})]}),e.jsxs(t.ResizablePanel,{id:"2",order:2,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:[(m==null?void 0:m.records)&&(m==null?void 0:m.records.length)>0&&e.jsx(Hn,{data:(m==null?void 0:m.records)||[]}),C&&e.jsx(Gt,{error:C})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function oa(){const s=t.useEditorStore(n=>n.pythonStdOut);if(!s)return null;const a=s.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col border-r",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center border-b bg-muted px-3 font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(t.ScrollArea,{className:"overflow-y-auto px-2 pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function ia(){const s=t.useEditorStore(n=>n.isShowingVisual),a=t.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(t.SmallSwitch,{checked:s,onCheckedChange:()=>a(!s),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function la(){var p,D;const s=t.useEditorStore(f=>f.card.customCardPreferences),{data:a}=Wt(),n=(a==null?void 0:a.plugins)||[],r=t.useEditorStore(f=>f.card),o=t.useEditorStore(f=>f.frame),i=(s==null?void 0:s.visualType)||"single",{setCustomCardPreferences:c}=t.useEditorActions(),{components:d,manifest:l}=t.useCustomVisual((s==null?void 0:s.url)||""),h=(p=l==null?void 0:l.visuals)==null?void 0:p.find(f=>f.name===(s==null?void 0:s.componentName));function u(f,j){if(!s)return;const I={...(s==null?void 0:s.dataInputCardIds)||{},[f]:{cardId:j,hookRef:null}};c({...s,dataInputCardIds:I})}function m(f){var O,I;const j=(O=o==null?void 0:o.cards)==null?void 0:O.filter(k=>{var N;return((N=k==null?void 0:k.customCardPreferences)==null?void 0:N.visualType)!=="multiple"}).map(k=>({value:k.id,label:k.tabTitle||k.title}));return e.jsx("div",{className:"space-y-2",children:(I=f==null?void 0:f.dataInputs)==null?void 0:I.map((k,N)=>{var S,w;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:k}),e.jsx(se,{className:"col-span-6 h-8 w-full justify-between",label:"",options:j||[],value:((w=(S=s==null?void 0:s.dataInputCardIds)==null?void 0:S[N])==null?void 0:w.cardId)||"",onValueChange:E=>u(N,E)})]},N+Math.random())})})}function y(f,j,O=[],I=""){var k,N;return s?f==="input"?e.jsx(t.Input,{className:`h-8 w-full ${t.removeRing}`,value:((k=s==null?void 0:s.settings)==null?void 0:k[j])||I,onChange:S=>{c({...s,settings:{...s==null?void 0:s.settings,[j]:S.target.value}})}},j):f==="select"?e.jsx(se,{className:"h-8 w-full",label:"",options:O,value:((N=s==null?void 0:s.settings)==null?void 0:N[j])||I,onValueChange:S=>{c({...s,settings:{...s==null?void 0:s.settings,[j]:S}})}}):null:null}function v(f){const j=Object.entries((f==null?void 0:f.settings)||{});return e.jsx("div",{className:"space-y-3",children:j.map(([O,I])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:I.title}),y(I.ui,O,I.options,I.defaultValue)]},O))})}function C(f){s&&c({...s,visualType:f,componentName:""})}return e.jsxs(t.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(t.AccordionItem,{value:"plugin-settings",children:[e.jsx(t.AccordionTrigger,{children:"Plugin"}),e.jsx(t.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(se,{icon:e.jsx(Bs,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(s==null?void 0:s.url)||"",onValueChange:f=>c({...s||{url:"",componentName:""},url:f})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&e.jsx(t.Tabs,{value:i,onValueChange:C,children:e.jsxs(t.TabsList,{className:"h-9 w-full",children:[e.jsx(t.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(t.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&s&&e.jsx(e.Fragment,{children:d&&e.jsx(se,{icon:e.jsx($s,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(d==null?void 0:d.filter(f=>f.type===i).map(f=>({value:f.name,label:f.name})))||[],value:s.componentName,onValueChange:f=>{console.log("changing value",f),c({...s,componentName:f})}})})]})})]}),((D=r==null?void 0:r.customCardPreferences)==null?void 0:D.componentName)&&e.jsxs(t.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{children:[h&&h.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:m(h)})]}),h&&h.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:v(h)})})]})]})]})}function je(){const[s,a]=L.useState([]),n=t.useEditorStore(h=>h.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:o}=t.useEditorStore(h=>h.actions),i=t.useEditorStore(h=>h.queryResultColumns);t.useEditorStore(h=>{var u;return(u=h.card.preferences)==null?void 0:u.filterOnClickColumnIndex}),L.useEffect(()=>{i&&a(new Array(i.length).fill(!1))},[i]);function c(h,u){var m,y;u?n!=null&&n.onClickFilter&&((m=n==null?void 0:n.onClickFilter)==null?void 0:m.length)>0?o({...n,onClickFilter:[...n.onClickFilter,{columnIndex:h,expression:""}]}):o({...n,onClickFilter:[{columnIndex:h,expression:""}]}):(o({...n,onClickFilter:(y=n==null?void 0:n.onClickFilter)==null?void 0:y.filter(v=>v.columnIndex!==h)}),a(v=>{const C=[...v];return C[h]=!1,C}))}function d(h,u){var y;const m=(y=n==null?void 0:n.onClickFilter)==null?void 0:y.map(v=>v.columnIndex===h?{...v,expression:u.target.value}:v);o({...n,onClickFilter:m})}function l(h){var u,m,y,v;if(s!=null&&s[h]||(m=(u=n==null?void 0:n.onClickFilter)==null?void 0:u.find(C=>C.columnIndex===h))!=null&&m.expression)return e.jsx(t.Input,{value:(v=(y=n==null?void 0:n.onClickFilter)==null?void 0:y.find(C=>C.columnIndex===h))==null?void 0:v.expression,onChange:C=>d(h,C),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsxs("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:[e.jsx(t.Label,{children:"On Click"}),i==null?void 0:i.map((h,u)=>{var m,y;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(t.Checkbox,{checked:!!((m=n==null?void 0:n.onClickFilter)!=null&&m.find(v=>v.columnIndex===u)),onCheckedChange:v=>c(u,v)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:h}),e.jsx("div",{className:"flex items-center gap-2",children:((y=n==null?void 0:n.onClickFilter)==null?void 0:y.find(v=>v.columnIndex===u))&&e.jsx(t.Pencil,{onClick:()=>{a(v=>{const C=[...v];return C[u]=!v[u],C})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),l(u)]})},h)})]})}function ca({idx:s}){var d;const a=t.useEditorStore(l=>{var h;return(h=l.card)==null?void 0:h.preferences}),n=t.useEditorStore(l=>{var h;return(h=l.card.preferences)==null?void 0:h.datasetOptions}),r=t.useEditorStore(l=>l.actions.setCardPreferences),o=(d=a==null?void 0:a.chartOptions)==null?void 0:d.indexAxis,i=n==null?void 0:n.find(l=>l.idx===s);function c(l,h){(l==="end"||l==="start")&&t.getContrastColor(t.getCanvasBackgroundColor());const u={display:l!=="none",align:l,anchor:l,clamp:!0};if(!i)r({...a,datasetOptions:[...n||[],{idx:h,datalabels:u}]});else{const m={...i};m.datalabels=u;const y=n==null?void 0:n.map(v=>v.idx===h?m:v);r({...a,datasetOptions:y})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(Ot,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(t.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>c("none",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(t.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>c("start",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(sn,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(an,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(nn,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})})]})})]})}function da(){const s=t.useEditorStore(i=>i.card),{data:a}=t.useDashboardCardQuery(s),{keys:n}=t.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(i=>!t.METADATA_KEYS.includes(i));let o=r;if(["stackedBar","stackedLine"].includes(s.type)){const i=t.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:c}=t.getKeys(i);o=c.slice(1)}return{transformedMetricKeys:o,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function mt({children:s,className:a,delayDuration:n}){return e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{delayDuration:n,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:t.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}function ss(){const s=t.useEditorStore(l=>l.card),a=t.useEditorStore(l=>{var h,u,m;return(m=(u=(h=l==null?void 0:l.card)==null?void 0:h.preferences)==null?void 0:u.chartOptions)==null?void 0:m.indexAxis}),{data:n}=t.useDashboardCardQuery(s),r=a==="y"?"Metric":"Dimension",o=a==="y"?"Dimension":"Metric",{dimensionKeys:i,transformedMetricKeys:c,keys:d}=da();return d.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:i.map(l=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:l,children:ns(l)},l))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:o}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((l,h)=>e.jsx(as,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:l,idx:h},l))})]})]})}function ns(s,a=30){return s.length>a?s.slice(0,a)+"...":s}function as({col:s,idx:a,className:n,iconClassName:r,children:o}){const i=t.useEditorStore(u=>{var m;return(m=u.card)==null?void 0:m.preferences}),c=t.useEditorStore(u=>{var m,y;return(y=(m=u.card)==null?void 0:m.preferences)==null?void 0:y.datasetOptions}),d=c==null?void 0:c.find(u=>u.idx===a),{setCardPreferences:l}=t.useEditorStore(u=>u.actions);function h(u){if(!d)l({...i,datasetOptions:[...c||[],{idx:a,type:u==="area"?"line":u,fill:u==="area"?"origin":""}]});else{const m={...d};m.type=u==="area"?"line":u,m.fill=u==="area"?"origin":"";const y=c==null?void 0:c.map(v=>v.idx===a?m:v);l({...i,datasetOptions:y})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[o||e.jsx(mt,{className:"max-w-[100px]",title:s,children:ns(s)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ae,{onClick:()=>h("bar"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Le,{onClick:()=>h("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Vs,{onClick:()=>h("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(ca,{idx:a})]})]})}function rs(){const s=t.useEditorStore(v=>v.selectedConnectionId),a=t.useEditorStore(v=>v.selectedDatamodelId),n=t.useEditorStore(v=>v.selectedDatabaseName),r=t.useEditorStore(v=>v.selectedSchemaName),o=t.useEditorStore(v=>v.selectedTableName),i=t.useDashboardStore(v=>v.dashboard.filters)||[],c=t.useDashboardStore(v=>v.actions.addFilter),d=t.useDashboardStore(v=>v.actions.removeFilter),{removeFilterValues:l}=t.useDashboardActions(),{modelItems:h,tableName:u,connectionType:m}=t.useEditorAside();function y(v,C="dashboard"){var S;const p=t.fmt(v.column_name),D=t.fmt(n||""),f=t.fmt(r||""),j=t.fmt(u);let O=t.getQualifiedTableName({schemaName:f,tableName:j,connectionType:m,databaseName:D}),I=`${O}.${p}`;const k=(S=h==null?void 0:h.find(w=>w.id===a))==null?void 0:S.name;a&&a!=="none"&&(I=`${t.DATAMODEL_NAMESPCACE}.${k}.${p}`,O=`${t.DATAMODEL_NAMESPCACE}.${k}`);const N=i==null?void 0:i.find(w=>w.column===I&&w.table===j&&(w.database===D||w.database===n));if(N)l(N.id),d(N.id);else{const w=t.v4();return u==="api"&&s?(c({location:C,id:w,column:I,title:v.column_name,dataType:v.data_type,table:"api",database:"",connectionId:s,operation:"in",sql:t.getDefaultFilterSql(v.data_type,O,p)}),w):(c({id:w,location:C,column:I,title:v.column_name,dataType:v.data_type,table:o||"",database:n||"",connectionId:s||"",operation:"in",sql:t.getDefaultFilterSql(v.data_type,O,p)}),w)}}return{assignFilter:y}}function ve(){const s=t.useDashboardStore(d=>d.dashboard.filters),a=t.useEditorStore(d=>d.frame),{setFrame:n}=t.useEditorActions(),{columns:r}=t.useEditorAside(),{assignFilter:o}=rs();function i(d){const l=o(d,"frame");n({...a,filterId:l})}const c=s==null?void 0:s.find(d=>d.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Card Filter"}),e.jsx(ua,{onSelect:i,columns:r}),c&&e.jsx(t.FilterHeader,{filter:c})]})}function ua({columns:s,onSelect:a}){var c;const[n,r]=he.useState(!1),[o,i]=he.useState("");return e.jsxs(t.Popover,{open:n,onOpenChange:r,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[o?(c=s.find(d=>d.column_name===o))==null?void 0:c.column_name:"Select Column...",e.jsx(t.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No framework found."}),e.jsx(t.CommandGroup,{children:s==null?void 0:s.map(d=>e.jsxs(t.CommandItem,{value:d.column_name,onSelect:l=>{const h=l===o?"":l;i(h),r(!1),h&&a(d)},children:[d.column_name,e.jsx(t.CheckIcon,{className:t.cn("ml-auto h-4 w-4",o===d.column_name?"opacity-100":"opacity-0")})]},d.column_name))})]})]})})]})}function ma({cardType:s}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} Chart`}),e.jsxs(t.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:a=>a.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsx(t.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(ss,{})})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(je,{}),e.jsx(ve,{})]})]})]})})}function Be(){const s=t.useEditorStore(d=>d.card.type),a=t.useEditorStore(d=>d.isDevMode),n=t.useEditorStore(d=>d.card.preferences),{setCardPreferences:r}=t.useEditorStore(d=>d.actions);function o(d){var u;const l={datalabels:{display:d!=="none",align:d,anchor:d,clamp:!0}},h={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(u=n==null?void 0:n.chartOptions)==null?void 0:u.plugins,...l}}};r(h)}function i(){var d,l,h;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(t.Select,{value:((h=(l=(d=n==null?void 0:n.chartOptions)==null?void 0:d.plugins)==null?void 0:l.datalabels)==null?void 0:h.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Data Labels"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"start",children:"Start"}),e.jsx(t.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"end",children:"End"})]})})]})]})}function c(){var d,l,h;return e.jsx("div",{children:e.jsxs(t.Select,{value:((h=(l=(d=n==null?void 0:n.chartOptions)==null?void 0:d.plugins)==null?void 0:l.datalabels)==null?void 0:h.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(t.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?i():c()})}function ha({cardType:s}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:i=>i.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} Chart`}),e.jsx(t.AccordionContent,{className:"space-y-4 font-mono text-xs",children:a(s)})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsx(t.AccordionContent,{className:"px-2",children:e.jsx(Be,{})})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(je,{}),e.jsx(ve,{})]})]})]})})}const xa={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},pa={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function fa(){const s=t.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(t.Accordion,{className:" ",type:"single",collapsible:!0,children:ga(s)}),!["kpi"].includes(s)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Be,{}),e.jsx(je,{}),e.jsx(ve,{})]})]})}function ga(s){if(["line","bar"].includes(s))return e.jsxs(e.Fragment,{children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT x-axis, y-axis-1, y-axis-2, y-axis-3,... FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"X-axis - Category (ex. city)"}),e.jsx("li",{children:"Y-axis - Number (ex. population)"})]})]})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(t.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and change the `type` property in the dataset."]}),e.jsx("pre",{children:JSON.stringify(xa,null,2)})]})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(t.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and add `fill` property to the dataset. See",e.jsx("a",{className:"mx-1 text-blue-500 hover:underline",href:"https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html",target:"_blank",children:"docs"}),"for more options."]}),e.jsx("pre",{children:JSON.stringify(pa,null,2)})]})]})]});if(s==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:s})," chart query?"]})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis, radius FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Bubble Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"}),e.jsx("li",{children:"Radius - Number (ex. population)"})]})]})]})});if(s==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:s})," chart query?"]})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"})]})]})]})});if(["pie","doughnut","polarArea","funnel"].includes(s))return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:s==="polarArea"?"Polar":s.charAt(0).toUpperCase()+s.slice(1)})," ","chart query"]})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Measure - Number (ex. population)"})]})]})]})})}function ja(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(t.Accordion,{type:"single",collapsible:!0,children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(t.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(t.FormatNumberSetting,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function _e({children:s,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,className:t.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(t.Label,{children:a}),e.jsx(t.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:s})]})}const ya=[{label:"Mercator",value:"mercator"},{label:"Azimuthal Equidistant",value:"azimuthalEquidistant"},{label:"Gnomonic",value:"gnomonic"},{label:"Orthographic",value:"orthographic"},{label:"Stereographic",value:"stereographic"},{label:"Equal Earth",value:"equalEarth"},{label:"Albers",value:"albers"},{label:"Albers USA",value:"albersUsa"},{label:"Conic Conformal",value:"conicConformal"},{label:"Conic Equal Area",value:"conicEqualArea"},{label:"Conic Equidistant",value:"conicEquidistant"},{label:"Equirectangular",value:"equirectangular"},{label:"Transverse Mercator",value:"transverseMercator"},{label:"Natural Earth 1",value:"naturalEarth1"}],ba=["blues","brBG","buGn","buPu","cividis","cool","cubehelixDefault","gnBu","greens","greys","inferno","magma","orRd","oranges","pRGn","piYG","plasma","puBu","puBuGn","puOr","puRd","purples","rainbow","rdBu","rdGy","rdPu","rdYlBu","rdYlGn","reds","sinebow","spectral","turbo","viridis","warm","ylGn","ylGnBu","ylOrBr","ylOrRd"],va=ba.map(s=>({label:s,value:s}));function Na(){var l,h,u,m,y,v,C,p,D,f,j,O,I,k,N,S,w,E;const s=t.useEditorStore(g=>g.card),a=(h=(l=s==null?void 0:s.preferences)==null?void 0:l.mapVisualOptions)==null?void 0:h.topoJsonUrl,[n,r]=L.useState(((m=(u=s==null?void 0:s.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:m.customTopoJsonUrl)||""),{setCardPreferences:o}=t.useEditorActions(),{data:i}=t.useTopoJson(s),c=Object.keys((i==null?void 0:i.objects)||{}).map(g=>({label:g,value:g}))||[],d=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(_e,{summary:"Map Chart",children:e.jsx("p",{className:"rounded-md bg-muted p-2 font-mono text-xs",children:"SELECT country, value FROM table"})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(_e,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(se,{className:"h-9",options:d,onValueChange:g=>{console.log("value",g),o({...s.preferences,mapVisualOptions:{topoJsonUrl:g}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(t.Input,{onChange:g=>{r(g.target.value)},onBlur:()=>{var g;console.log("onBlur",n),o({...s.preferences,mapVisualOptions:{...(g=s.preferences)==null?void 0:g.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${t.removeRing}`,placeholder:"Custom URL"}),i&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Map Object"}),e.jsx(se,{className:"h-9",options:c,value:((v=(y=s.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:v.objectKey)||"",label:"Map Object",onValueChange:g=>{var x;o({...s.preferences,mapVisualOptions:{...(x=s.preferences)==null?void 0:x.mapVisualOptions,objectKey:g}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(se,{className:"h-9",options:ya,value:((p=(C=s.preferences)==null?void 0:C.mapVisualOptions)==null?void 0:p.projection)||"",label:"Projection",onValueChange:g=>{var x;o({...s.preferences,mapVisualOptions:{...(x=s.preferences)==null?void 0:x.mapVisualOptions,projection:g}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(se,{className:"h-9",options:va,value:((f=(D=s.preferences)==null?void 0:D.mapVisualOptions)==null?void 0:f.colorScale)||"",label:"Select Color Scale",onValueChange:g=>{var x;o({...s.preferences,mapVisualOptions:{...(x=s.preferences)==null?void 0:x.mapVisualOptions,colorScale:g}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(_e,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:.1,value:((O=(j=s.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:O.projectionScale)||1,onChange:g=>{var x;o({...s.preferences,mapVisualOptions:{...(x=s.preferences)==null?void 0:x.mapVisualOptions,projectionScale:Number(g.target.value)}})}}),e.jsx(t.Label,{children:"X"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((N=(k=(I=s.preferences)==null?void 0:I.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:N[0])||0,onChange:g=>{var x,B,A,T;o({...s.preferences,mapVisualOptions:{...(x=s.preferences)==null?void 0:x.mapVisualOptions,projectionOffset:[Number(g.target.value),((T=(A=(B=s.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:T[1])||0]}})}}),e.jsx(t.Label,{children:"Y"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((E=(w=(S=s.preferences)==null?void 0:S.mapVisualOptions)==null?void 0:w.projectionOffset)==null?void 0:E[1])||0,onChange:g=>{var x,B,A,T;o({...s.preferences,mapVisualOptions:{...(x=s.preferences)==null?void 0:x.mapVisualOptions,projectionOffset:[((T=(A=(B=s.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:T[0])||0,Number(g.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(je,{})]})}function Ca(){var r;const s=t.useEditorStore(o=>o.card.preferences),{setCardPreferences:a}=t.useEditorStore(o=>o.actions);function n(o){a({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:o==="dynamic"}})}return e.jsxs(t.RadioGroup,{value:(r=s==null?void 0:s.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function ke({cardType:s,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return s==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} ${n}`}),e.jsx(t.AccordionContent,{children:a||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[s!=="text"&&e.jsx(Be,{}),s==="text"&&e.jsx(Ca,{})]})]}),!["range","text"].includes(s)&&e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(je,{}),e.jsx(ve,{})]})]})]})})}function Sa(){const s=t.useEditorStore(r=>{var o,i;return(i=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:i.sortChart}),{setSortChart:a}=t.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Sort"}),e.jsx(se,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:s||"none",onValueChange:r=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(t.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(ss,{})]})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(je,{}),e.jsx(ve,{})]})]})]})})}function wa({cardType:s="table"}){console.log("cardType",s);const a=t.useEditorStore(o=>{var i;return(i=o.card)==null?void 0:i.preferences}),n=t.useEditorStore(o=>o.actions.setCardPreferences),r=o=>{n({...a,allowDownload:o})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(t.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(je,{}),e.jsx(ve,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}const ka=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT dimension, cohort, metric FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),Ea=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),Da=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function Ta(){const s=t.useEditorStore(n=>n.card.type);function a(n){switch(n){case"stackedBar":case"stackedLine":return e.jsx(Sa,{});case"tornado":case"pyramid":return e.jsx(ke,{docContent:ka,cardType:n});case"kpi":return e.jsx(ja,{});case"line":case"bar":return e.jsx(ma,{cardType:n});case"range":return e.jsx(ke,{docContent:Ea,cardType:n});case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return e.jsx(ke,{cardType:n});case"bubble":case"scatter":return e.jsx(ha,{cardType:n});case"table":return e.jsx(wa,{cardType:n});case"text":return e.jsx(ke,{docContent:Da,cardType:n,suffix:"Visual"});case"map":return e.jsx(Na,{});case"custom":return e.jsx(la,{});default:return e.jsx(fa,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[a(s),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function os({label:s,column:a,functions:n,onFunctionChange:r}){let o=n[0];"aggregate"in a?o=n.find(c=>c.value===a.aggregate)||n[0]:"granularity"in a&&(o=n.find(c=>c.value===a.granularity)||n[0]);function i(c){r(c)}return e.jsx(se,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:o.logo,options:n,value:o.value,onValueChange:c=>i(c),label:s,showPlaceholderLabel:!1})}const Ia=[{label:"Sum",value:"SUM",logo:e.jsx(Lt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(Ze,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(Ws,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(Is,{className:"size-3.5"})},{label:"Min",value:"MIN",logo:e.jsx(t.ArrowDown,{className:"size-3.5"})},{label:"Max",value:"MAX",logo:e.jsx(t.ArrowUp,{className:"size-3.5"})}];function Ma({column:s}){const{updateMetricColumnOld:a}=t.useEditorActions();let n=Ia;t.isTextDataType(s.type)&&(n=n.filter(o=>["COUNT","DISTINCT"].includes(o.value))),t.isNumberDataType(s.type)&&(n=n.filter(o=>!["DISTINCT"].includes(o.value)));function r(o){const i={...s,aggregate:o,label:Ce(s.name,o)};a(s.id,i)}return e.jsx(os,{column:s,functions:n,onFunctionChange:o=>r(o),label:"Aggregation"})}const Aa=[{label:"Day (D)",value:"day",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"D"})},{label:"Week (W)",value:"week",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"W"})},{label:"Month (M)",value:"month",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"M"})},{label:"Year (Y)",value:"year",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"Y"})}];function La({column:s}){const{updateGroupByColumnOld:a}=t.useEditorActions();function n(r){const o={...s,granularity:r,label:be(s.name,r)};a(s.id,o)}return e.jsx(os,{column:s,functions:Aa,onFunctionChange:r=>n(r),label:"Granularity"})}function Oa({col:s,onChange:a,droppableId:n}){const{columns:r}=t.useDataColumns(),o=L.useMemo(()=>{let d=[];(n===xe||n===pe||n===fe)&&(d=r);const l=d==null?void 0:d.filter(h=>h.column_name!==s.name);return l==null?void 0:l.map(h=>({id:h.column_name,value:h.column_name}))},[r,n,s.name]),i=[{id:s.name,value:s.name}];function c(d){const l=r==null?void 0:r.find(h=>{var u;return h.column_name===((u=d[0])==null?void 0:u.id)});l&&a(l)}return o!=null&&o.length?e.jsx(t.ComboBox2,{multiple:!1,options:o,selectedOptions:i,onChange:c,selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"border-none bg-muted pl-0 pr-8"}):e.jsx("input",{disabled:!0,type:"text",className:"overflow-hidden truncate text-ellipsis whitespace-nowrap bg-muted text-sm",value:s.name})}function is({column:s}){const a=t.useEditorStore(l=>l.card.type),n=t.useEditorStore(l=>{var h,u;return(u=(h=l.card)==null?void 0:h.config)==null?void 0:u.metricColumns}),r=(n==null?void 0:n.map(l=>l.label))||[],o=r==null?void 0:r.find(l=>l===s.label||l===s.name),i=o?r.indexOf(o):-1;function c(){return e.jsx("div",{className:"pr-1",children:o&&e.jsx(as,{idx:i,col:o,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function d(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Be,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&c(),["pie","doughnut"].includes(a)&&d()]})}function Ba({column:s,type:a,onRemoveColumn:n,droppableId:r}){const[o,i]=L.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:d,updatePivotByColumnOld:l}=t.useEditorActions(),{attributes:h,listeners:u,setNodeRef:m,transform:y,transition:v,isDragging:C}=t.useSortable({id:s.id,data:{type:a}}),p=y?{opacity:C?.5:void 0,transform:t.CSS.Translate.toString(y),transition:v}:void 0,D=t.isTextDataType(s.type);function f(N){const S=t.isNumberDataType(N.data_type),w=t.isTextDataType(N.data_type),E=t.isDateDataType(N.data_type),g=S?"number":w?"string":E?"date":"string";if(r===xe){if(w){const x={id:s.id,name:N.column_name,type:g,role:"groupby"};c(s.id,x)}if(E){const x={id:s.id,name:N.column_name,type:g,role:"groupby",label:be(N.column_name,"month"),granularity:"month"};c(s.id,x)}}if(r===fe){if(w){const x={id:s.id,name:N.column_name,type:g,role:"groupby"};l(s.id,x)}if(E){const x={id:s.id,name:N.column_name,type:g,label:be(N.column_name,"month"),granularity:"month",role:"groupby"};l(s.id,x)}}if(r===pe){const x={id:s.id,name:N.column_name,type:g,role:"metric",label:Ce(N.column_name,"SUM"),aggregate:S?"SUM":"COUNT"};d(s.id,x)}}function j(){if(r===pe)return e.jsx("div",{"data-setting-container":"",className:"mt-1.5 max-h-32 overflow-y-auto rounded-md border border-border p-3 text-sm",children:e.jsx(is,{column:s})})}function O(){const N=t.isDateDataType(s.type);if(r===pe)return e.jsx(Ma,{column:s});if((r===xe||r===fe)&&N)return e.jsx(La,{column:s})}function I(){return e.jsx("div",{className:t.cn("grow",{"pl-3":(r===xe||r===fe)&&D}),children:e.jsx(Oa,{col:s,onChange:f,droppableId:r})})}function k(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>i(!o),children:o?e.jsx(fn,{className:t.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(Mt,{className:t.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...u,...h,ref:m,style:p,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[k(),O(),I()]}),o&&j()]}),e.jsx("div",{className:t.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:o}),children:e.jsx("button",{onClick:()=>n(s.id),children:e.jsx(t.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function Ge({id:s,label:a,columns:n,previewColumns:r,sortableType:o,onRemoveColumn:i}){var p,D;const{setNodeRef:c,isOver:d,over:l}=t.useDroppable({id:s}),h=t.useDndStore(f=>f.activeId),u=t.useEditorStore(f=>{var j;return(j=f.card)==null?void 0:j.type}),m=d||((D=(p=l==null?void 0:l.data)==null?void 0:p.current)==null?void 0:D.type)===o,y=h?r:n,v=o===De?"Rows":o===Te?"Pivot Columns":"Columns";function C(){if(!y||y.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(t.SortableContext,{items:n==null?void 0:n.map(f=>f.id),children:e.jsxs("div",{className:t.cn("group space-y-2 rounded-md p-4",m&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(t.Label,{className:"text-sm",children:a}),u!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:v})]}),C(),e.jsx("div",{className:"space-y-2",children:y==null?void 0:y.map(f=>f.id===qt.id?e.jsx(Fa,{},f.id):e.jsx(Ba,{droppableId:s,type:o,column:f,onRemoveColumn:i},f.id))})]})})}function Fa(){return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm",children:e.jsx("span",{className:"text-muted-foreground/70",children:"Drop here"})})}function ls({children:s,id:a,type:n}){const{attributes:r,listeners:o,setNodeRef:i,transform:c,transition:d,isDragging:l}=t.useSortable({id:a,data:{type:n}}),h=c?{opacity:l?.5:void 0,transform:t.CSS.Translate.toString(c),transition:d}:void 0;return e.jsx("div",{...o,...r,ref:i,style:h,children:s})}function za(){const s=t.useEditorStore(f=>{var j;return(j=f.card.queryConfig)==null?void 0:j.orderBy})||[],a=t.useEditorStore(f=>{var j;return(j=f.card.queryConfig)==null?void 0:j.groupByColumns})||[],n=t.useEditorStore(f=>{var j;return(j=f.card.queryConfig)==null?void 0:j.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:o,updateOrderByColumn:i}=t.useEditorActions(),c=[...a,...n];if(c.length===0)return e.jsx(e.Fragment,{});const d=e.jsx(Os,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),l=e.jsx(Ts,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=e.jsx(Ls,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(Ds,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=c==null?void 0:c.filter(f=>!s.some(j=>j.columnId===f.id)).map(f=>({id:f.id,value:f.label||f.name}));function y(f,j){const O=v(f);return O?O.role==="metric"?j==="asc"?h:u:j==="asc"?d:l:null}function v(f){return c.find(j=>j.id===f)}function C(f){const j=s.find(O=>O.columnId===f);if(j){const O={...j,direction:j.direction==="asc"?"desc":"asc"};i(O)}}const p=f=>{r({columnId:f.id,direction:"asc"})};function D(f){const j=s.find(O=>O.columnId===f);j&&o(j)}return e.jsx(t.SortableContext,{items:s.map(f=>Ne(f.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(t.Label,{className:"text-sm",children:"Sort By"}),m.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(t.ComboBox2,{multiple:!1,options:m,selectedOptions:[],onChange:f=>p(f[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),s.map(f=>{var j,O;return e.jsx(ls,{id:Ne(f.columnId),type:ot,children:e.jsx("div",{className:"group flex h-8 items-center gap-2 rounded-sm p-0",children:e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2 rounded-sm bg-muted px-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Mt,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(mt,{className:"w-[175px] text-sm",children:((j=v(f.columnId))==null?void 0:j.label)||((O=v(f.columnId))==null?void 0:O.name)})]}),e.jsx("button",{title:f.direction==="asc"?"Ascending":"Descending",onClick:()=>C(f.columnId),className:"rounded-sm p-0",children:y(f.columnId,f.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>D(f.columnId),className:"rounded-sm p-0",children:e.jsx(t.X,{className:"size-3 text-muted-foreground opacity-0 transition-opacity duration-200 hover:text-foreground group-hover:opacity-100"})})})]})},f.columnId)},Ne(f.columnId))})]})})}function Pa(){const s=t.useEditorStore(D=>{var f;return((f=D.card.queryConfig)==null?void 0:f.groupByColumns)||[]}),a=t.useEditorStore(D=>D.card.type),n=t.useDndStore(D=>D.previewGroupByColumns),r=t.useEditorStore(D=>{var f;return((f=D.card.queryConfig)==null?void 0:f.metricColumns)||[]}),o=t.useDndStore(D=>D.previewMetricColumns),i=t.useEditorStore(D=>{var f;return((f=D.card.queryConfig)==null?void 0:f.pivotColumns)||[]}),c=t.useDndStore(D=>D.previewPivotColumns),{removeColumnFromGroupBy:d,removeColumnFromMetricColumns:l,removeColumnFromPivotBy:h}=t.useEditorActions();function u(D){d(D)}function m(D){l(D)}function y(D){h(D)}let v="Group By",C="Metrics",p="Stack By";return a==="table"&&(v="Rows",C="Metrics",p="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(Xt,{iconClassName:"size-[19px]"}),e.jsxs(t.CustomScrollArea,{className:"flex min-h-0 grow basis-0 flex-col gap-4 overflow-y-auto",children:[e.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e.jsx(Ge,{onRemoveColumn:u,sortableType:De,id:xe,label:v,columns:s,previewColumns:n}),e.jsx(Ge,{onRemoveColumn:y,sortableType:Te,id:fe,label:p,columns:i,previewColumns:c}),e.jsx(Ge,{onRemoveColumn:m,sortableType:Je,id:pe,label:C,columns:r,previewColumns:o}),e.jsx(za,{})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function ht({children:s,column:a,id:n,sortableType:r,className:o}){const[i,c]=L.useState(!1),{removeEditorFilter:d,clearEditorFilter:l}=t.useEditorActions(),h=t.useEditorStore(m=>{var y,v;return(v=(y=m.card.queryConfig)==null?void 0:y.filters)==null?void 0:v.some(C=>C.filterColumnName===a.name)});function u(m){d(m)}return e.jsx(ls,{id:n,type:r,children:e.jsxs("div",{className:t.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":i}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-sm",children:a.name}),h&&e.jsx("button",{onClick:()=>l(a),children:e.jsx(t.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>u(a),children:e.jsx(t.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:t.cn("group flex items-center rounded-t-md text-sm",!i&&"rounded-b-md",i&&"border border-border"),children:[e.jsx("div",{children:e.jsx(t.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:t.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",o),children:s})]})]})})}function Ra({column:s,sortableType:a}){const n=t.useDashboardStore(O=>O.themeStyle),r=t.useEditorStore(O=>{var I,k;return(k=(I=O.card)==null?void 0:I.queryConfig)==null?void 0:k.filters}),o=t.useEditorStore(O=>{var I,k;return(k=(I=O.card.queryConfig)==null?void 0:I.filterColumns)==null?void 0:k.find(N=>N.name===s.name)}),{selectedConnectionId:i,selectedDatabaseName:c,selectedTableName:d}=t.useEditorAside(),l=L.useMemo(()=>{var O;return(O=r==null?void 0:r.find(I=>I.filterColumnName===s.name))==null?void 0:O.filterValue},[r,s.name]),h=L.useMemo(()=>Array.isArray(l)?l.map(O=>({id:O,value:O})):[],[l]),{updateEditorFilterValue:u}=t.useEditorActions(),m={column:s.name,sql:s.sql,id:s.name,connectionId:i,dataType:s.type},{data:y,isLoading:v,isFetching:C,isError:p}=t.useFilterQuery(m),D=L.useMemo(()=>{var I;return m.column?(I=y==null?void 0:y.records)==null?void 0:I.map(k=>{let N=m.column.split(".").slice(-1)[0].replace(/"/g,"");return k[N]===void 0&&(N=N.toLowerCase()),{id:k[N],value:k[N]}}):[]},[y,m.column]);function f(O){const I=O.map(k=>k.id);u(s.name,I)}function j(){return v||C?e.jsx(t.Skeleton,{style:{borderRadius:n==null?void 0:n.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):p?e.jsx("div",{className:"flex h-8 min-w-60 items-center bg-muted px-2 text-sm",children:"Error"}):e.jsx(t.ComboBox2,{renderFilterModeButton:()=>e.jsx(Va,{columnName:s.name}),showNegativeIndicator:(o==null?void 0:o.mode)==="exclude",options:D,onChange:f,selectedOptions:h,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(ht,{className:"w-60",id:s.id,sortableType:a,column:s,children:j()})}function Va({columnName:s}){const{setEditorFilterMode:a}=t.useEditorActions(),n=t.useEditorStore(o=>{var i,c;return(c=(i=o.card.queryConfig)==null?void 0:i.filterColumns)==null?void 0:c.find(d=>d.name===s)});function r(){(n==null?void 0:n.mode)==="exclude"?a(s,"include"):a(s,"exclude")}return e.jsx(t.Button,{onClick:r,variant:"secondary",size:"sm",className:t.cn("h-5 text-xs hover:underline",{}),children:t.titleCase((n==null?void 0:n.mode)==="exclude"?"exclude":"include")})}function qa({column:s,sortableType:a}){const[n,r]=L.useState(!1),{selectedConnectionId:o,selectedDatabaseName:i,selectedTableName:c}=t.useEditorAside(),d={column:s.name,sql:s.sql,id:s.name,connectionId:o,title:"",dataType:s.type},{isLoading:l,isFetching:h,isError:u,data:m}=t.useFilterQuery(d),y=m==null?void 0:m.records,{dateRange:v,setDateRange:C,initialDateRange:p}=t.useDateRangeFromRecords(y),{updateEditorFilterValue:D}=t.useEditorActions();function f(I){var N,S;const k={gte:(N=I==null?void 0:I.from)==null?void 0:N.toISOString(),lte:(S=I==null?void 0:I.to)==null?void 0:S.toISOString()};D(s.name,k)}function j(){D(s.name,null,!0),C(p)}function O(){return l||h?e.jsx("div",{children:e.jsx(t.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):u?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):y?e.jsx(t.DateRangePopover,{title:d.title,open:n,inputClassName:"h-8",setOpen:r,dateRange:v,setDateRange:C,onApply:f,onClear:j}):e.jsx(t.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(ht,{className:"w-72",id:s.id,sortableType:a,column:s,children:O()})}function _a({id:s,label:a,columns:n,previewColumns:r,sortableType:o}){var C,p;const{setNodeRef:i,isOver:c,over:d}=t.useDroppable({id:s}),l=t.useDndStore(D=>D.activeId),h={},u=c||((p=(C=d==null?void 0:d.data)==null?void 0:C.current)==null?void 0:p.type)===o;function m(){if(!v||v.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function y(D){const f=t.isDateDataType(D.type);return D.id===qt.id?e.jsx(ht,{id:D.id,sortableType:o,column:D,children:e.jsx(Ga,{})},D.id):f?e.jsx(qa,{droppableId:s,sortableType:o,column:D},D.id):e.jsx(Ra,{droppableId:s,sortableType:o,column:D},D.id)}const v=l?r:n;return e.jsx(t.SortableContext,{items:n==null?void 0:n.map(D=>D.id),children:e.jsxs("div",{className:t.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",u&&"border border-muted-foreground/20"),ref:i,style:h,children:[e.jsx(t.Label,{className:"text-sm",children:a}),m(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:v==null?void 0:v.map(D=>y(D))})]})})}function Ga(){return e.jsx("div",{className:"flex h-8 w-60 items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm text-muted-foreground",children:"Drop here"})}function $a(){const s=t.useEditorStore(o=>{var i;return((i=o.card.queryConfig)==null?void 0:i.filterColumns)||[]}),a=t.useDndStore(o=>o.previewFilterColumns),{removeColumnFromFilterColumns:n}=t.useEditorActions();function r(o){n(o)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(_a,{onRemoveColumn:r,sortableType:Ye,id:He,label:"Filters",columns:s,previewColumns:a})})}function Ja(){const s=t.useEditorStore(i=>i.card),a=t.useEditorStore(i=>i.showAIDialog),{setShowAIDialog:n}=t.useEditorActions(),{data:r,errorMessage:o}=t.useDashboardCardQuery(s);return e.jsxs("section",{className:"flex justify-between gap-2 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.EditorClearButton,{}),!a&&e.jsxs(t.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(Jt,{sql:r==null?void 0:r.sql,error:o})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-green-300 px-3 py-1 text-xs font-medium text-black",children:"Preview"}),e.jsx(t.EditorCancelButton,{}),e.jsx(t.EditorAcceptButton,{variant:"default"})]})]})}function Ha(){const s=L.useRef(null),a=L.useRef(null),n=t.useEditorStore(d=>d.isShowingVisual),r=t.useEditorStore(d=>d.showAIDialog),o=t.useEditorStore(d=>d.isDevMode);L.useEffect(()=>{var d,l,h,u;r?((d=s.current)==null||d.resize(0),(l=a.current)==null||l.resize(0)):((h=s.current)==null||h.resize(25),(u=a.current)==null||u.resize(25))},[r]);function i(){return e.jsxs(e.Fragment,{children:[e.jsx(t.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Jn,{})}),e.jsx(t.ResizableHandle,{withHandle:!0}),e.jsx(t.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!r?e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(t.ResizablePanel,{ref:s,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Ta,{})})}),!r&&e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(we,{})})]}):e.jsx(we,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:n?e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(t.ResizablePanel,{ref:a,defaultSize:25,maxSize:30,children:e.jsx(Pa,{})})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{defaultSize:75,maxSize:100,children:e.jsxs(t.ResizablePanelGroup,{direction:"vertical",children:[e.jsxs(t.ResizablePanel,{className:"flex min-h-fit flex-col",minSize:10,defaultSize:20,children:[e.jsx(Ja,{}),e.jsx($a,{})]}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(we,{})})]})})]}):e.jsx(we,{})})})}return e.jsx(t.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:o?i():c()})}function Ya(s){const a=t.useAIInteractionStore(_=>_.currentAIContext),[n,r]=L.useState(""),[o,i]=L.useState(null),{authToken:c}=t.useSemaphorContext(),d=t.useEditorStore(_=>{var K;return(K=_==null?void 0:_.card)==null?void 0:K.sql}),l=t.useEditorStore(_=>_.isDevMode),h=t.useEditorStore(_=>{var K;return(K=_==null?void 0:_.card)==null?void 0:K.python}),{setCardPython:u,setCardSql:m,setRunSql:y,switchCardType:v,setQueryConfig:C}=t.useEditorActions(),p=t.useEditorStore(_=>_.currentAssitantScope)||[],D=t.useEditorStore(_=>_.userInputForAI),f=t.useEditorStore(_=>_.triggerAIRun),j=t.useEditorStore(_=>_.card),O=t.useEditorStore(_=>_.selectedDatabaseName),I=t.useEditorStore(_=>_.selectedTableName),k=t.useEditorStore(_=>_.selectedConnectionId),N=t.useEditorStore(_=>_.selectedSchemaName),S=t.useDashboardStore(_=>_.dashboard.aiScopeTables),{errorMessage:w,refetch:E,data:g}=t.useDashboardCardQuery(j),{setTriggerAIRun:x,setCurrentAssitantScope:B,setCardConfig:A}=t.useEditorActions(),{selectedDatamodelName:T,connectionType:b,selectedDatamodelId:M}=t.useEditorAside(),{messages:F,setMessages:P,reload:V,error:z,append:U,input:R,setInput:q,status:H,handleInputChange:Q,handleSubmit:G,stop:$}=t.useChat({api:"https://semaphor.cloud/api/v1/assistant",headers:{Authorization:`Bearer ${c==null?void 0:c.accessToken}`},body:{random:Math.random(),assistantId:"editor-assistant",isDevMode:l,aiContext:a},maxSteps:10,onError:_=>{console.log("on error",_)},onToolCall:J,onFinish(_,K){X(K.usage),r(""),K.finishReason==="stop"&&r("")}});L.useEffect(()=>{f&&D&&(U({role:"user",content:D}),x(!1))},[f,D,U,x]);async function J({toolCall:_}){var K,ae,de,me;if(["createChartFromSql","createForecast"].includes(_.toolName)){const W=_.args.sql,Z=_.args.python,ee=_.args.chartType;return v(ee),m(W),u(Z),y(!0),{status:"success",message:"Let the user know that chart is created"}}else if(_.toolName==="getTableColumns")r("Getting table columns...");else{if(_.toolName==="getUserSql")return d?{status:"success",sql:d,python:h||""}:{status:"error",message:"No SQL found"};if(_.toolName==="getCurrentTableScope")return r("Getting table scope..."),oe(),{status:"success",tables:p};if(_.toolName==="generateQueryConfig"){r("Generating query config...");const W=_.args.chartType,Z=_.args.queryConfig;_.args.cardConfig,v(W),A(Z),m(void 0),u(void 0);const ee=await E();return(K=ee==null?void 0:ee.data)!=null&&K.error?{status:"error",queryConfig:Z,message:(ae=ee==null?void 0:ee.data)==null?void 0:ae.error.message}:(de=ee==null?void 0:ee.data)!=null&&de.records?{status:"success",queryConfig:Z,message:"The data has been visualized"}:{status:"success",queryConfig:Z,message:"The data has been visualized",records:(me=ee==null?void 0:ee.data)==null?void 0:me.records}}else r("Analyzing...")}}function X(_){i(K=>K?{promptTokens:K.promptTokens+_.promptTokens,completionTokens:K.completionTokens+_.completionTokens,totalTokens:K.totalTokens+_.totalTokens}:_)}function te(_){const K=t.removeFromScopeArray(p,_);ne(K)}function ne(_){const K=t.sanitizeAIScope(_);B(K),P(ae=>[...ae,{id:crypto.randomUUID(),role:"system",content:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(K)}`}])}function le(){const _={databaseName:O||"",schemaName:N||"",tableName:I||"",datamodelId:M||"",datamodelName:t.resolveDatamodelName(T),connectionId:k||"",connectionType:b||""},K=t.dedup([...p,_]);ne(K)}function oe(){const _={databaseName:O||"",schemaName:N||"",tableName:I||"",datamodelName:t.resolveDatamodelName(T),connectionId:k||"",connectionType:b||"",datamodelId:M||""};if(!t.isInAiScopeArray([...S||[],...p],_)||p.length===0){const ae=t.dedup([...S||[],...p,_]).filter(de=>de.connectionId===_.connectionId);ne(ae)}}const ce=!["ready","error"].includes(H),ie=t.getErrorMessage(z);return{messages:F,setMessages:P,reload:V,append:U,input:R,setInput:q,isLoading:ce,handleSetAIScope:oe,handleAddCurrentTableToScope:le,removeFromCurrentSelections:te,currentAssitantScope:p,setCurrentAssitantScope:B,handleInputChange:Q,handleSubmit:G,stop:$,chatStatus:H,toolStatus:n,llmUsage:o,onFinish:s,errorMessage:ie}}const Ka=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Et(){const s=L.useRef(null),a=L.useRef(null),[n,r]=L.useState(!1),[o,i]=L.useState(t.isDevEnv),[c,d]=L.useState(!1),[l,h]=L.useState(!1),u=t.useCurrentAIContext(),{setCurrentAIContext:m}=t.useAIActions(),y=t.useDashboardStore($=>$.dashboard.aiContext),v=t.useEditorStore($=>$.card.dataSource),C=t.useEditorStore($=>$.actions.setCardSql),p=t.useEditorStore($=>$.actions.setRunSql),D=t.useEditorStore($=>$.showAIDialog),f=t.useDashboardStore($=>$.handleOpenAssistantProfile),{setShowAIDialog:j,setCardPython:O}=t.useEditorActions(),{setDataSource:I}=t.useEditorActions(),{assistantProfile:k}=t.useAssistantProfile(),{messages:N,setMessages:S,reload:w,append:E,input:g,setInput:x,isLoading:B,handleInputChange:A,handleSubmit:T,stop:b,chatStatus:M,llmUsage:F,errorMessage:P}=Ya();t.useAssistantScroll({scrollContainerRef:s,inputRef:a,messages:N}),L.useEffect(()=>{var $;D&&(($=a.current)==null||$.focus(),m({selectedEntities:(v==null?void 0:v.selectedEntities)||[]}))},[D,v,m]);function V($,J){J==="sql"?(C($),p(!0)):J==="python"&&(O($),p(!0))}function z(){var $;($=y==null?void 0:y.selectedEntities)==null||$[0],h(!0)}function U(){u.selectedEntities.length===0&&m({selectedEntities:(y==null?void 0:y.selectedEntities)||[]})}function R($){U();const J={role:"user",content:$.title+" "+$.subtitle};E(J)}function q($){U(),E({role:"user",content:$})}function H(){return e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.Button,{className:"h-7 p-2",size:"sm",variant:"ghost",children:e.jsx(t.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",children:[e.jsx(t.DropdownMenuLabel,{children:"Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsx(t.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:r,children:"Token Usage"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:i,children:"Tool Invocations"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:d,children:"System Message"})]})]})}function Q(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const G=(g==null?void 0:g.length)===0&&(N==null?void 0:N.filter($=>$.role==="user").length)===0;return e.jsxs("div",{"data-role":"editor-assistant",className:"flex h-full w-full flex-col justify-between px-6 py-4",children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Q(),f&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:f,children:(k==null?void 0:k.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center gap-2",children:[H(),e.jsx(t.IconButton,{tooltip:"Add Context",className:"h-7 p-2",onClick:z,children:e.jsx(t.Settings,{className:"size-4"})}),e.jsx(t.IconButton,{className:"h-7 p-2",tooltip:"New Chat",onClick:()=>{S([]),w()},children:e.jsx(t.SquarePen,{className:"size-4"})}),e.jsx(t.Button,{variant:"ghost",className:"h-8",size:"sm",onClick:()=>{j(!1)},children:e.jsx(t.PanelRight,{className:"size-4"})})]})]}),e.jsx(t.CustomScrollArea,{ref:s,className:"mt-2 flex w-full grow basis-0",children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[e.jsx(t.PrintMessages,{messages:N,showTools:o,handleRun:V,showSystemMessage:c}),e.jsx(t.ChatStatus,{messages:N,chatStatus:M,errorMessage:P})]})}),e.jsxs("div",{className:"mb-3",children:[G&&!k&&e.jsx(t.Placeholders,{onClick:R,placeholders:Ka}),e.jsx("div",{children:G&&k&&e.jsx(t.SeedQuestions,{seedQuestions:k.seedQuestions||[],handleSeedQuestionClick:q})})]}),e.jsx(t.ChatInputWithContext,{ref:a,setInput:x,stop:b,input:g,handleInputChange:A,handleSubmit:$=>{U(),T($)},isLoading:B,onFocus:()=>{}}),F&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",F.promptTokens," prompt tokens,"," ",F.completionTokens," completion tokens,"," ",F.totalTokens," total tokens"]})}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:(v==null?void 0:v.selectedEntities)||[],open:l,onOpenChange:h,dataSource:v||t.EMPTY_DATA_SOURCE,fallbackDataSource:t.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function Ua({field:s}){const{attributes:a,listeners:n,setNodeRef:r,transform:o,transition:i,isDragging:c}=t.useSortable({id:s.id}),[d,l]=L.useState(!1),h={transform:t.CSS.Transform.toString(o),transition:i},u=t.getDataType(s.dataType),y=(v=>{const C=(v||"").toLowerCase();switch(t.getDataType(C)){case"number":return Ze;case"date":return t.Calendar;case"boolean":return Bt;case"json":return _s;case"geo":return ln;default:return Ft}})(s.dataType);return e.jsxs("div",{ref:r,style:h,...a,...n,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:border-blue-200 hover:bg-blue-50 dark:hover:border-blue-800 dark:hover:bg-blue-950"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1 p-2",onClick:()=>l(!d),children:[e.jsx("div",{className:"flex-shrink-0 hover:cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"invisible size-3.5 text-gray-400 group-hover/container:visible"})}),e.jsx(y,{className:t.cn("size-3.5 flex-shrink-0 text-gray-500",u==="string"?"text-blue-500":"",u==="number"?"text-green-500":"",u==="date"?"text-purple-500":"",u==="boolean"?"text-orange-500":"")}),e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm text-foreground/90 hover:text-foreground dark:text-muted-foreground ${d?"whitespace-normal break-words":"truncate"}`,children:s.name})})}),e.jsx(t.TooltipContent,{side:"bottom",align:"start",className:"max-w-fit",children:e.jsxs("div",{className:"overflow-x-auto",children:[e.jsx("p",{className:t.cn("font-medium",{"text-blue-500":u==="string","text-green-500":u==="number","text-purple-500":u==="date","text-orange-500":u==="boolean"}),children:s.label||s.name}),s.description&&e.jsx("div",{className:"mt-1 text-sm text-muted-foreground",children:s.description}),e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(hn,{className:"size-3.5"}),e.jsx("p",{className:"",children:s.qualifiedEntityName?`${s.qualifiedEntityName}.${s.name}`:s.name})]}),e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(y,{className:t.cn("size-3 flex-shrink-0 text-gray-500",u==="string"?"text-blue-500":"",u==="number"?"text-green-500":"",u==="date"?"text-purple-500":"",u==="boolean"?"text-orange-500":"")}),e.jsx("p",{className:t.cn("text-xs font-normal text-gray-500"),children:s.dataType})]})]})})]})}),e.jsx("button",{onClick:v=>{v.stopPropagation(),l(!d)},className:"invisible flex-shrink-0 text-gray-400 hover:text-gray-600 group-hover/container:visible",children:d?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronRight,{className:"h-4 w-4"})})]}),d&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(t.Card,{className:"",children:e.jsxs(t.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ot,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:s.label||s.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:s.name})]}),e.jsx(t.Badge,{variant:"outline",className:"mt-2 text-xs",children:s.dataType})]})})})]})}function Qa({entityGroup:s,fields:a,isOpen:n,onToggle:r}){return e.jsxs(t.Collapsible,{open:n,onOpenChange:r,children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 rounded-md px-3 py-2 hover:bg-muted",children:[e.jsx("span",{className:"flex-1 text-left text-sm font-medium",children:s.label||s.entityName}),e.jsxs("span",{className:"text-xs text-gray-500",children:["(",a.length,")"]}),n?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronRight,{className:"h-4 w-4"})]}),e.jsx(t.CollapsibleContent,{className:"mt-1 space-y-1",children:e.jsx(t.SortableContext,{items:a.map(o=>o.id),strategy:t.verticalListSortingStrategy,children:a.map(o=>e.jsx(Ua,{field:o},o.id))})})]})}function Wa(){const[s,a]=L.useState(""),[n,r]=L.useState(new Set),[o,i]=L.useState("all"),c=t.useEditorStore(I=>I.card.dataSource),{columns:d=[],columnGroups:l=[],isLoading:h,error:u}=t.useColumns(),m=d.filter(I=>I.name.toLowerCase().includes(s.toLowerCase())||I.dataType.toLowerCase().includes(s.toLowerCase())||I.qualifiedEntityName&&I.qualifiedEntityName.toLowerCase().includes(s.toLowerCase())),y=I=>I.dataType==="number"||I.dataType==="integer"||I.dataType==="float"||I.dataType==="decimal"||I.dataType==="currency"?"metrics":"dimensions",C=(o==="all"?m:m.filter(I=>y(I)===o)).reduce((I,k)=>{const N=k.qualifiedEntityName||"Other Fields";return I[N]||(I[N]={label:t.toLabel(k.entityName),fields:[]}),I[N].fields.push(k),I},{});L.useEffect(()=>{const I=Object.keys(C);r(new Set(I))},[Object.keys(C).join(",")]);const p=I=>{const k=new Set(n);k.has(I)?k.delete(I):k.add(I),r(k)},D=m.filter(I=>y(I)==="dimensions").length,f=m.filter(I=>y(I)==="metrics").length,j=m.filter(I=>y(I)==="calculated").length,O=m.length>0;return h?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(t.LoaderCircle,{className:"h-8 w-8 animate-spin text-gray-400"}),e.jsx("span",{className:"mt-2 text-sm text-gray-500",children:"Loading fields..."})]}):u?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(t.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:u.message||"Failed to load column data"})]}):!c||!c.selectedEntities||c.selectedEntities.length===0?e.jsx(t.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(t.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[d.length>0&&e.jsx("div",{className:"mb-4",children:e.jsx(t.Input$1,{type:"text",placeholder:"Search fields...",value:s,onChange:I=>a(I.target.value)})}),O&&e.jsx(t.Tabs,{defaultValue:"all",value:o,onValueChange:I=>i(I),className:"mb-4",children:e.jsxs(t.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(t.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:m.length})]}),e.jsxs(t.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(t.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:D})]}),e.jsxs(t.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(t.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:f})]}),e.jsxs(t.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(Rs,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]})]})})]}),e.jsxs(t.CustomScrollArea,{className:"py-2",children:[e.jsxs("div",{className:"space-y-2",children:[Object.entries(C).map(([I,k])=>{const N=l.find(S=>S.entityName===I)||{entityName:I,label:k.label};return e.jsx(Qa,{entityGroup:N,fields:k.fields,isOpen:n.has(I),onToggle:()=>p(I)},I)}),Object.keys(C).length===0&&d.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]}),Object.keys(C).length===0&&d.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"}),e.jsx(t.ScrollBar,{orientation:"vertical"})]})]})}function Xa(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(Wa,{})," "]})}function Za({initialJoinPlan:s,availableDataSources:a}){const[n,r]=L.useState(s),[o,i]=L.useState(new Set),c=()=>{const N=n.joins.length>0?Math.max(...n.joins.map(w=>w.sequence))+1:1,S={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:N,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,S]}),i(new Set([...o,S.id]))},d=N=>{r({...n,joins:n.joins.filter(S=>S.id!==N)}),i(new Set([...o].filter(S=>S!==N)))},l=(N,S)=>{var x,B;const w=n.joins.find(A=>A.id===N);if(!w)return;const E={...w,...S},g=n.joins.map(A=>A.id===N?E:A);if((x=E.source)!=null&&x.name&&((B=E.target)!=null&&B.name)&&E.joinKeyGroups[0].keys.length===0){const A=a.find(F=>{var P;return F.name===((P=E.source)==null?void 0:P.name)}),T=a.find(F=>{var P;return F.name===((P=E.target)==null?void 0:P.name)}),b={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(A==null?void 0:A.name)||"",entityName:(A==null?void 0:A.name)||"",entityType:(A==null?void 0:A.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(T==null?void 0:T.name)||"",entityName:(T==null?void 0:T.name)||"",entityType:(T==null?void 0:T.type)||"table"},operator:"="},M=[...E.joinKeyGroups];M[0]={...M[0],keys:[b]},E.joinKeyGroups=M,g[g.findIndex(F=>F.id===N)]=E}r({...n,joins:g})};return{joinPlan:n,expandedJoins:o,setJoinPlan:r,addJoin:c,removeJoin:d,updateJoin:l,moveJoinUp:N=>{const S=n.joins.findIndex(w=>w.id===N);if(S>0){const w=[...n.joins],E={...w[S]},g={...w[S-1]};w[S]=g,w[S-1]=E,w.forEach((B,A)=>{B.sequence=A+1});const x={...n,joins:w};r(x)}},moveJoinDown:N=>{const S=n.joins.findIndex(w=>w.id===N);if(S<n.joins.length-1){const w=[...n.joins],E={...w[S]},g={...w[S+1]};w[S]=g,w[S+1]=E,w.forEach((B,A)=>{B.sequence=A+1});const x={...n,joins:w};r(x)}},toggleJoinExpansion:N=>{const S=new Set(o);S.has(N)?S.delete(N):S.add(N),i(S)},getAvailableSourceEntities:N=>{if(n.joins.length===0)return a;const S=n.joins.findIndex(E=>E.id===N);if(S===0)return a;const w=new Set;return n.baseEntity.name&&w.add(n.baseEntity.name),n.joins.slice(0,S).forEach(E=>{w.add(E.source.name),w.add(E.target.name)}),a.filter(E=>w.has(E.name))},getAvailableTargetEntities:N=>a.filter(S=>S.name!==N),addJoinKeyGroup:N=>{const S=n.joins.find(E=>E.id===N);if(!S)return;const w=[...S.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];l(N,{joinKeyGroups:w})},updateGroupOperator:(N,S,w)=>{const E=n.joins.find(x=>x.id===N);if(!E)return;const g=[...E.joinKeyGroups];g[S]={...g[S],operator:w},l(N,{joinKeyGroups:g})},removeJoinKeyGroup:(N,S)=>{const w=n.joins.find(g=>g.id===N);if(!w)return;const E=[...w.joinKeyGroups];E.splice(S,1),l(N,{joinKeyGroups:E})},addJoinKey:(N,S)=>{const w=n.joins.find(A=>A.id===N);if(!w)return;const E=a.find(A=>A.name===w.source.name),g=a.find(A=>A.name===w.target.name),x=[...w.joinKeyGroups],B={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(E==null?void 0:E.name)||"",entityName:(E==null?void 0:E.name)||"",entityType:(E==null?void 0:E.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(g==null?void 0:g.name)||"",entityName:(g==null?void 0:g.name)||"",entityType:(g==null?void 0:g.type)||"table"},operator:"="};x[S]={...x[S],keys:[...x[S].keys,B]},l(N,{joinKeyGroups:x})},updateJoinKey:(N,S,w,E,g)=>{const x=n.joins.find(M=>M.id===N);if(!x)return;const B=a.find(M=>M.name===x.source.name),A=a.find(M=>M.name===x.target.name),T=[...x.joinKeyGroups],b=T[S].keys[w];E==="sourceColumnName"&&B?T[S].keys[w]={...b,source:{...b.source,name:g}}:E==="targetColumnName"&&A?T[S].keys[w]={...b,target:{...b.target,name:g}}:E==="operator"&&(T[S].keys[w]={...b,operator:g}),l(N,{joinKeyGroups:T})},removeJoinKey:(N,S,w)=>{const E=n.joins.find(x=>x.id===N);if(!E)return;const g=[...E.joinKeyGroups];g[S].keys.splice(w,1),l(N,{joinKeyGroups:g})},generateSQLPreview:()=>{const N=[...n.joins].sort((E,g)=>E.sequence-g.sequence),S=n.baseEntity;if(!S.name)return"SELECT * FROM table -- Please select a base entity";let w=`SELECT *
370
370
  FROM ${S.name}`;return N.forEach(E=>{const g=a.find(A=>A.name===E.target.name);if(!g)return;const x=E.joinKeyGroups.filter(A=>A.keys&&A.keys.length>0).map(A=>{const T=A.keys.filter(b=>{var M,F,P,V;return((M=b.source)==null?void 0:M.name)&&((F=b.target)==null?void 0:F.name)&&((P=b.source)==null?void 0:P.entityName)&&((V=b.target)==null?void 0:V.entityName)}).map(b=>`${b.source.entityName}.${b.source.name} ${b.operator} ${b.target.entityName}.${b.target.name}`);return T.length>1?`(${T.join(` ${A.operator} `)})`:T[0]}).filter(Boolean),B=x.length>1?x.join(" OR "):x[0]||"condition_here";w+=`
371
371
  ${E.joinType} JOIN ${g.name}
372
- ON ${B}`}),w},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(E=>!E.source.name||!E.target.name)||n.joins.some(E=>E.joinKeyGroups.some(g=>g.keys.length===0))||n.joins.some(E=>E.joinKeyGroups.some(g=>g.keys.some(x=>!x.source.name||!x.target.name||!x.operator))))}}function er({joinPlan:s,availableDataSources:a,onSave:n,onRemove:r,onCancel:o}){const{setCardConfig:i}=t.useEditorActions();t.useEditorStore(x=>x.card.config);const{columnGroups:c}=t.useColumns(),{joinPlan:d,expandedJoins:l,setJoinPlan:h,addJoin:u,removeJoin:m,updateJoin:j,moveJoinUp:v,moveJoinDown:C,toggleJoinExpansion:p,getAvailableSourceEntities:D,getAvailableTargetEntities:f,addJoinKeyGroup:y,updateGroupOperator:O,removeJoinKeyGroup:I,addJoinKey:k,updateJoinKey:N,removeJoinKey:S,generateSQLPreview:w,isValidConfiguration:E}=Za({initialJoinPlan:s,availableDataSources:a}),g=x=>{const B=c.find(A=>A.entityName===x);return(B==null?void 0:B.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(t.Select,{value:d.baseEntity.name,onValueChange:x=>{const B=a.find(A=>A.name===x);h({...d,baseEntity:{connectionId:(B==null?void 0:B.connectionId)||"",connectionType:(B==null?void 0:B.connectionType)||"none",type:(B==null?void 0:B.type)||"table",name:x,database:B==null?void 0:B.database,schema:B==null?void 0:B.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(t.SelectContent,{children:a.map(x=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:x.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:x.type}),x.name,e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},x.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:w()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(t.Label,{children:["Joins Configuration (",d.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:u,children:[e.jsx(t.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),d.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:d.joins.map(x=>{const B=a.find(b=>b.name===x.source.name),A=a.find(b=>b.name===x.target.name),T=l.has(x.id);return e.jsxs(t.Card,{className:"border",children:[e.jsx(t.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{children:x.sequence}),e.jsxs(t.CardTitle,{className:"text-sm",children:["Join ",x.sequence,B&&A&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",B.name," → ",A.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>v(x.id),disabled:x.sequence===1,children:e.jsx(t.ArrowUp,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>C(x.id),disabled:x.sequence===d.joins.length,children:e.jsx(t.ArrowDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>p(x.id),children:T?e.jsx(t.ChevronUp,{className:"h-4 w-4"}):e.jsx(t.ChevronDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>m(x.id),children:e.jsx(t.X,{className:"h-4 w-4"})})]})]})}),T&&e.jsxs(t.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Source"}),e.jsxs(t.Select,{value:x.source.name,onValueChange:b=>{const M=a.find(F=>F.name===b);j(x.id,{source:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:b,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select source..."})}),e.jsx(t.SelectContent,{children:D(x.id).map(b=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:b.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:b.type}),b.name]})},b.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Join Type"}),e.jsxs(t.Select,{value:x.joinType,onValueChange:b=>j(x.id,{joinType:b}),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Target"}),e.jsxs(t.Select,{value:x.target.name,onValueChange:b=>{const M=a.find(F=>F.name===b);j(x.id,{target:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:b,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},disabled:!x.source.name,children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select target..."})}),e.jsx(t.SelectContent,{children:x.source.name?f(x.source.name).map(b=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:b.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:b.type}),b.name,b.name===x.source.name&&e.jsx(t.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},b.name)):[]})]})]})]}),x.source.name&&x.target.name&&B&&A&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{children:"Join Conditions"}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>y(x.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),x.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:x.joinKeyGroups.map((b,M)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Label,{children:["Group ",M+1]}),M>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(t.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Select,{value:b.operator,onValueChange:F=>O(x.id,M,F),children:[e.jsx(t.SelectTrigger,{className:"w-[100px]",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>I(x.id,M),children:e.jsx(t.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[b.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:b.keys.map((F,P)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[P>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:b.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:F.source.name,onValueChange:V=>N(x.id,M,P,"sourceColumnName",V),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Source column"})}),e.jsx(t.SelectContent,{children:g(x.source.name).map(V=>e.jsx(t.SelectItem,{value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:V.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(t.Select,{value:F.operator,onValueChange:V=>N(x.id,M,P,"operator",V),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"=",children:"="}),e.jsx(t.SelectItem,{value:"<",children:"<"}),e.jsx(t.SelectItem,{value:">",children:">"}),e.jsx(t.SelectItem,{value:"<=",children:"<="}),e.jsx(t.SelectItem,{value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:F.target.name,onValueChange:V=>N(x.id,M,P,"targetColumnName",V),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Target column"})}),e.jsx(t.SelectContent,{children:g(x.target.name).map(V=>e.jsx(t.SelectItem,{value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:V.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>S(x.id,M,P),children:e.jsx(t.X,{className:"size-3.5"})})]},F.id||P))}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>k(x.id,M),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},b.id))})]})]})]},x.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>{r(),o()},children:"Remove All"}),e.jsx(t.Button,{variant:"outline",onClick:o,children:"Cancel"}),e.jsx(t.Button,{onClick:()=>n(d),disabled:!E(),children:"Save"})]})]})}function Dt({children:s,open:a,onOpenChange:n,joinPlan:r,availableDataSources:o,onRemove:i,onSave:c,onCancel:d}){return e.jsxs(t.Dialog,{open:a,onOpenChange:n,children:[e.jsxs(t.DialogContent,{className:"max-w-4xl",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Join Configuration"}),e.jsx(t.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(er,{joinPlan:r,availableDataSources:o,onSave:c,onCancel:d,onRemove:i})]}),s]})}function tr({joins:s,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[s.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const o=[...s].sort((c,d)=>c.sequence-d.sequence),i=n.find(c=>c.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(t.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name}),e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),o.map(c=>{const d=n.find(l=>l.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(t.Badge,{variant:"secondary",className:"text-xs",children:d==null?void 0:d.type}),e.jsx("span",{className:"text-xs font-medium",children:d==null?void 0:d.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",s.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...s].sort((o,i)=>o.sequence-i.sequence).map((o,i)=>{const c=n.find(l=>l.name===o.source.name),d=n.find(l=>l.name===o.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(t.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:i+1}),e.jsx(t.Badge,{variant:"outline",className:"shrink-0 text-xs",children:o.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",d==null?void 0:d.name]}),e.jsxs(t.Badge,{variant:"outline",className:"ml-auto text-xs",children:[o.joinKeyGroups.reduce((l,h)=>l+h.keys.length,0)," ","condition",o.joinKeyGroups.reduce((l,h)=>l+h.keys.length,0)>1?"s":""]})]},o.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function sr(){var u,m;const s=t.useEditorStore(j=>j.card),a=t.useEditorStore(j=>j.actions.updateCardConfig),n=((u=s==null?void 0:s.config)==null?void 0:u.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,o]=L.useState(!1),i=((m=s==null?void 0:s.dataSource)==null?void 0:m.selectedEntities)||[],c=j=>{a(s.id,{...s==null?void 0:s.config,joinPlan:j}),o(!1)},d=()=>{a(s.id,{...s==null?void 0:s.config,joinPlan:void 0})},l=()=>{o(!1)},h=()=>{const j=[...n.joins].sort((p,D)=>p.sequence-D.sequence),v=n.baseEntity;if(!v.name)return"SELECT * FROM table -- Please select a base entity";let C=`SELECT *
373
- FROM ${v.name}`;return j.forEach(p=>{const D=i.find(O=>O.name===p.target.name);if(!D)return;const f=p.joinKeyGroups.filter(O=>O.keys&&O.keys.length>0).map(O=>{const I=O.keys.filter(k=>{var N,S,w,E;return((N=k.source)==null?void 0:N.name)&&((S=k.target)==null?void 0:S.name)&&((w=k.source)==null?void 0:w.entityName)&&((E=k.target)==null?void 0:E.entityName)}).map(k=>`${k.source.entityName}.${k.source.name} ${k.operator} ${k.target.entityName}.${k.target.name}`);return I.length>1?`(${I.join(` ${O.operator} `)})`:I[0]}).filter(Boolean),y=f.length>1?f.join(" OR "):f[0]||"condition_here";C+=`
372
+ ON ${B}`}),w},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(E=>!E.source.name||!E.target.name)||n.joins.some(E=>E.joinKeyGroups.some(g=>g.keys.length===0))||n.joins.some(E=>E.joinKeyGroups.some(g=>g.keys.some(x=>!x.source.name||!x.target.name||!x.operator))))}}function er({joinPlan:s,availableDataSources:a,onSave:n,onRemove:r,onCancel:o}){const{setCardConfig:i}=t.useEditorActions();t.useEditorStore(x=>x.card.config);const{columnGroups:c}=t.useColumns(),{joinPlan:d,expandedJoins:l,setJoinPlan:h,addJoin:u,removeJoin:m,updateJoin:y,moveJoinUp:v,moveJoinDown:C,toggleJoinExpansion:p,getAvailableSourceEntities:D,getAvailableTargetEntities:f,addJoinKeyGroup:j,updateGroupOperator:O,removeJoinKeyGroup:I,addJoinKey:k,updateJoinKey:N,removeJoinKey:S,generateSQLPreview:w,isValidConfiguration:E}=Za({initialJoinPlan:s,availableDataSources:a}),g=x=>{const B=c.find(A=>A.entityName===x);return(B==null?void 0:B.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(t.Select,{value:d.baseEntity.name,onValueChange:x=>{const B=a.find(A=>A.name===x);h({...d,baseEntity:{connectionId:(B==null?void 0:B.connectionId)||"",connectionType:(B==null?void 0:B.connectionType)||"none",type:(B==null?void 0:B.type)||"table",name:x,database:B==null?void 0:B.database,schema:B==null?void 0:B.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(t.SelectContent,{children:a.map(x=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:x.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:x.type}),x.name,e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},x.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:w()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(t.Label,{children:["Joins Configuration (",d.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:u,children:[e.jsx(t.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),d.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:d.joins.map(x=>{const B=a.find(b=>b.name===x.source.name),A=a.find(b=>b.name===x.target.name),T=l.has(x.id);return e.jsxs(t.Card,{className:"border",children:[e.jsx(t.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{children:x.sequence}),e.jsxs(t.CardTitle,{className:"text-sm",children:["Join ",x.sequence,B&&A&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",B.name," → ",A.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>v(x.id),disabled:x.sequence===1,children:e.jsx(t.ArrowUp,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>C(x.id),disabled:x.sequence===d.joins.length,children:e.jsx(t.ArrowDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>p(x.id),children:T?e.jsx(t.ChevronUp,{className:"h-4 w-4"}):e.jsx(t.ChevronDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>m(x.id),children:e.jsx(t.X,{className:"h-4 w-4"})})]})]})}),T&&e.jsxs(t.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Source"}),e.jsxs(t.Select,{value:x.source.name,onValueChange:b=>{const M=a.find(F=>F.name===b);y(x.id,{source:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:b,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select source..."})}),e.jsx(t.SelectContent,{children:D(x.id).map(b=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:b.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:b.type}),b.name]})},b.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Join Type"}),e.jsxs(t.Select,{value:x.joinType,onValueChange:b=>y(x.id,{joinType:b}),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Target"}),e.jsxs(t.Select,{value:x.target.name,onValueChange:b=>{const M=a.find(F=>F.name===b);y(x.id,{target:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:b,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},disabled:!x.source.name,children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select target..."})}),e.jsx(t.SelectContent,{children:x.source.name?f(x.source.name).map(b=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:b.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:b.type}),b.name,b.name===x.source.name&&e.jsx(t.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},b.name)):[]})]})]})]}),x.source.name&&x.target.name&&B&&A&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{children:"Join Conditions"}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>j(x.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),x.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:x.joinKeyGroups.map((b,M)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Label,{children:["Group ",M+1]}),M>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(t.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Select,{value:b.operator,onValueChange:F=>O(x.id,M,F),children:[e.jsx(t.SelectTrigger,{className:"w-[100px]",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>I(x.id,M),children:e.jsx(t.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[b.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:b.keys.map((F,P)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[P>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:b.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:F.source.name,onValueChange:V=>N(x.id,M,P,"sourceColumnName",V),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Source column"})}),e.jsx(t.SelectContent,{children:g(x.source.name).map(V=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:V.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(t.Select,{value:F.operator,onValueChange:V=>N(x.id,M,P,"operator",V),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:F.target.name,onValueChange:V=>N(x.id,M,P,"targetColumnName",V),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Target column"})}),e.jsx(t.SelectContent,{children:g(x.target.name).map(V=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:V.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>S(x.id,M,P),children:e.jsx(t.X,{className:"size-3.5"})})]},F.id||P))}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>k(x.id,M),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},b.id))})]})]})]},x.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>{r(),o()},children:"Remove All"}),e.jsx(t.Button,{variant:"outline",onClick:o,children:"Cancel"}),e.jsx(t.Button,{onClick:()=>n(d),disabled:!E(),children:"Save"})]})]})}function Dt({children:s,open:a,onOpenChange:n,joinPlan:r,availableDataSources:o,onRemove:i,onSave:c,onCancel:d}){return e.jsxs(t.Dialog,{open:a,onOpenChange:n,children:[e.jsxs(t.DialogContent,{className:"max-w-4xl",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Join Configuration"}),e.jsx(t.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(er,{joinPlan:r,availableDataSources:o,onSave:c,onCancel:d,onRemove:i})]}),s]})}function tr({joins:s,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[s.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const o=[...s].sort((c,d)=>c.sequence-d.sequence),i=n.find(c=>c.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(t.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name}),e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),o.map(c=>{const d=n.find(l=>l.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(t.Badge,{variant:"secondary",className:"text-xs",children:d==null?void 0:d.type}),e.jsx("span",{className:"text-xs font-medium",children:d==null?void 0:d.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",s.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...s].sort((o,i)=>o.sequence-i.sequence).map((o,i)=>{const c=n.find(l=>l.name===o.source.name),d=n.find(l=>l.name===o.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(t.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:i+1}),e.jsx(t.Badge,{variant:"outline",className:"shrink-0 text-xs",children:o.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",d==null?void 0:d.name]}),e.jsxs(t.Badge,{variant:"outline",className:"ml-auto text-xs",children:[o.joinKeyGroups.reduce((l,h)=>l+h.keys.length,0)," ","condition",o.joinKeyGroups.reduce((l,h)=>l+h.keys.length,0)>1?"s":""]})]},o.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function sr(){var u,m;const s=t.useEditorStore(y=>y.card),a=t.useEditorStore(y=>y.actions.updateCardConfig),n=((u=s==null?void 0:s.config)==null?void 0:u.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,o]=L.useState(!1),i=((m=s==null?void 0:s.dataSource)==null?void 0:m.selectedEntities)||[],c=y=>{a(s.id,{...s==null?void 0:s.config,joinPlan:y}),o(!1)},d=()=>{a(s.id,{...s==null?void 0:s.config,joinPlan:void 0})},l=()=>{o(!1)},h=()=>{const y=[...n.joins].sort((p,D)=>p.sequence-D.sequence),v=n.baseEntity;if(!v.name)return"SELECT * FROM table -- Please select a base entity";let C=`SELECT *
373
+ FROM ${v.name}`;return y.forEach(p=>{const D=i.find(O=>O.name===p.target.name);if(!D)return;const f=p.joinKeyGroups.filter(O=>O.keys&&O.keys.length>0).map(O=>{const I=O.keys.filter(k=>{var N,S,w,E;return((N=k.source)==null?void 0:N.name)&&((S=k.target)==null?void 0:S.name)&&((w=k.source)==null?void 0:w.entityName)&&((E=k.target)==null?void 0:E.entityName)}).map(k=>`${k.source.entityName}.${k.source.name} ${k.operator} ${k.target.entityName}.${k.target.name}`);return I.length>1?`(${I.join(` ${O.operator} `)})`:I[0]}).filter(Boolean),j=f.length>1?f.join(" OR "):f[0]||"condition_here";C+=`
374
374
  ${p.joinType} JOIN ${D.name}
375
- ON ${y}`}),C};return i.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[n.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>o(!0),children:[e.jsx(t.Link,{className:t.cn("mr-1 h-3 w-3",{"text-blue-500":n.joins.length>0,"text-gray-500":n.joins.length===0})}),"Join",n.joins.length>1?"s":""," (",n.joins.length,")"]})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(tr,{joins:n.joins,baseEntityId:n.baseEntity.name,availableDataSources:i,generateSQLPreview:h})})]})}),e.jsx(Dt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:i,onSave:c,onCancel:l,onRemove:d,children:e.jsx("div",{})})]}),n.joins.length===0&&e.jsx(Dt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:i,onSave:c,onCancel:l,onRemove:d,children:e.jsxs(t.Button,{onClick:()=>o(!0),variant:"outline",className:"h-6 text-xs font-semibold",children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Configure Join"]})})]})})})}function nr(){const[s,a]=L.useState(!1),[n,r]=L.useState(!0),o=t.useEditorStore(l=>l.card.dataSource),{updateDataSource:i}=t.useEditorActions(),c={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},d={...c,...o,selectedEntities:(o==null?void 0:o.selectedEntities)||[]};return e.jsxs("div",{className:"flex w-[325px] flex-col border-r bg-background",children:[e.jsxs("div",{children:[e.jsx("div",{className:t.cn("p-4 px-6",{"pb-0":!n}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",onClick:()=>r(!n),children:[n?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronRight,{className:"h-4 w-4"}),e.jsx(t.Database,{className:"h-5 w-5 text-brand"}),e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"})]}),e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-7",onClick:()=>a(!0),children:[e.jsx(t.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${n?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[d.selectedEntities.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1",children:[d.selectedEntities.slice(0,3).map((l,h)=>e.jsxs(t.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[t.getDisplayName(l),e.jsx("button",{onClick:u=>{u.stopPropagation();const m=d.selectedEntities.filter(j=>!(j.name===l.name&&j.type===l.type));i({...c,...o,selectedEntities:m})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 hover:bg-red-100",children:e.jsx(t.X,{className:"h-2.5 w-2.5 group-hover:text-red-500"})})]},`${l.type}-${l.name}-${h}`)),d.selectedEntities.length>3&&e.jsxs(t.Badge,{variant:"outline",className:"text-xs",children:["+",d.selectedEntities.length-3," more"]})]}),e.jsx(sr,{})]})]}),e.jsx(Xa,{}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:(o==null?void 0:o.selectedEntities)||[],dialogMode:"dataSource",open:s,onOpenChange:a,dataSource:d,fallbackDataSource:c})]})}const ar=[{id:"table",icon:Oe,label:"Table"},{id:"bar",icon:Ae,label:"Bar Chart"},{id:"line",icon:Le,label:"Line Chart"},{id:"stackedBar",icon:Ke,label:"Stacked Bar Chart"},{id:"stackedLine",icon:dt,label:"Stacked Line Chart"},{id:"scatter",icon:We,label:"Scatter Chart"},{id:"bubble",icon:lt,label:"Bubble Chart"},{id:"pie",icon:Qe,label:"Pie Chart"},{id:"doughnut",icon:Xe,label:"Doughnut Chart"},{id:"funnel",icon:ct,label:"Funnel Chart"},{id:"radar",icon:tt,label:"Radar Chart"},{id:"polarArea",icon:it,label:"Polar Area Chart"},{id:"tornado",icon:nt,label:"Tornado Chart"},{id:"range",icon:Ue,label:"Range Chart"},{id:"kpi",icon:ut,label:"KPI"},{id:"text",icon:Tt,label:"Text"},{id:"map",icon:et,label:"Map"},{id:"custom",icon:st,label:"Custom"}];function rr({selectedChart:s,onChartChange:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:o}=t.useEditorStore(h=>h.actions),{setCardCustomCfg:i,setCustomCardPreferences:c,setQueryConfig:d}=t.useEditorActions();function l(h){i(null),r({}),n(h),["custom","text","map"].includes(h)&&(o(!0),d(void 0)),a(h)}return e.jsx("div",{className:"mb-6",children:e.jsxs(t.Select,{value:s,onValueChange:l,children:[e.jsx(t.SelectTrigger,{className:"w-full",children:e.jsx(t.SelectValue,{placeholder:"Select chart type"})}),e.jsx(t.SelectContent,{children:ar.map(h=>{const u=h.icon;return e.jsx(t.SelectItem,{value:h.id,className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(u,{className:"h-4 w-4"}),e.jsx("span",{children:h.label})]})},h.id)})})]})})}const cs=({dataType:s})=>{const a=t.getDataType(s);return a==="string"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-blue-500 text-xs text-white",children:"T"}):a==="number"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-green-500 text-xs text-white",children:"#"}):a==="date"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-purple-500 text-xs text-white",children:"D"}):a==="boolean"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-orange-500 text-xs text-white",children:"B"}):e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-gray-500 text-xs text-white",children:"?"})};function or({label:s,onLabelChange:a}){const[n,r]=L.useState(s??""),[o,i]=L.useState(!1);return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Display Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Input$1,{placeholder:"Display label...",value:o?n:s??"",onChange:c=>{r(c.target.value),i(!0)},onFocus:()=>i(!0),onClick:c=>c.stopPropagation(),className:"h-8 text-xs",onPointerDown:c=>c.stopPropagation(),onKeyDown:c=>{c.stopPropagation(),c.key==="Enter"&&o&&n!==(s??"")?(a(n),i(!1)):c.key==="Escape"&&(r(s??""),i(!1))},"aria-label":"Edit display label"}),o&&n!==(s??"")&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm label",onClick:()=>{a(n),i(!1)},children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel label edit",onClick:()=>{r(s??""),i(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})]})}function ir({aliasTemplate:s,onAliasTemplateChange:a}){var l;const[n,r]=L.useState(s),[o,i]=L.useState(!1),c=(l=t.useEditorStore(h=>{var u;return(u=h.card.config)==null?void 0:u.pivotByColumns}))==null?void 0:l[0],d=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Input$1,{placeholder:d,value:o?n:s,onChange:h=>{r(h.target.value),i(!0)},onFocus:()=>i(!0),onPointerDown:h=>h.stopPropagation(),className:"h-8 text-xs",onKeyDown:h=>{h.key==="Enter"&&o&&n!==s?(a(n),i(!1)):h.key==="Escape"&&(r(s),i(!1))},"aria-label":"Edit alias template"}),o&&n!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),i(!1)},children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(s),i(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function lr({valueAliases:s,onValueAliasesChange:a}){const[n,r]=L.useState(null),[o,i]=L.useState(""),[c,d]=L.useState(""),l=()=>{a({...s,"":""})},h=m=>{const j={...s};delete j[m],a(j)},u=m=>{const j={...s};delete j[m],j[o]=c,a(j),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(s).map(([m,j],v)=>e.jsx("div",{className:"flex items-center gap-2",children:n===m?e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:o,onChange:C=>i(C.target.value),className:"h-8 w-24 text-xs",onPointerDown:C=>C.stopPropagation(),onKeyDown:C=>{C.key==="Enter"?u(m):C.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{placeholder:"Alias label",value:c,onChange:C=>d(C.target.value),className:"h-8 w-24 text-xs",onPointerDown:C=>C.stopPropagation(),onKeyDown:C=>{C.key==="Enter"?u(m):C.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>u(m),children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:m,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),i(m),d(j)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{placeholder:"Alias label",value:j,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),i(m),d(j)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>h(m),"aria-label":"Remove value alias",children:e.jsx(t.X,{className:"h-3 w-3"})})]})},m+v)),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:l,children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function ds(s,a){return`${t.toLabel(a)} of ${t.toLabel(s)}`}const us=s=>{const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:o,updateSortByColumn:i,removeGroupByColumn:c,removeMetricColumn:d,removePivotByColumn:l,removeSortByColumn:h}=t.useEditorActions(),u=t.useEditorStore(g=>g.card.type),m=s==null?void 0:s.id,j=L.useCallback(g=>{if(!(s!=null&&s.config))return[];switch(g){case"groupBy":return(s.config.groupByColumns||[]).map(x=>({id:x.id,name:x.name,dataType:x.dataType,label:x.label!==void 0?x.label:x.name,qualifiedEntityName:x.qualifiedEntityName,entityId:x.entityId,entityName:x.entityName,entityType:x.entityType,dateFormat:x.dateFormat,customFormat:x.customFormat,granularity:x.granularity}));case"metrics":return s.config.metricColumns||[];case"pivotBy":return(s.config.pivotByColumns||[]).map(x=>({id:x.id,name:x.name,dataType:x.dataType,label:x.label!==void 0?x.label:x.name,qualifiedEntityName:x.qualifiedEntityName,entityId:x.entityId,entityName:x.entityName,entityType:x.entityType}));case"sortBy":return(s.config.sortByColumns||[]).map(x=>({id:x.id,name:x.name,dataType:x.dataType,label:x.label!==void 0?x.label:x.name,qualifiedEntityName:x.qualifiedEntityName,entityId:x.entityId,entityName:x.entityName,entityType:x.entityType,direction:x.direction}));case"source":return[];default:return[]}},[s]),v=L.useCallback((g,x)=>{if(m)switch(g){case"groupBy":{a(m,{groupByColumns:x});break}case"metrics":{a(m,{metricColumns:x});break}case"pivotBy":{a(m,{pivotByColumns:x});break}case"sortBy":{a(m,{sortByColumns:x});break}}},[m,a]),C=L.useCallback((g,x,B)=>{if(!m)return;const T=j(g)[x];if(T)switch(g){case"groupBy":n(m,T.id,{label:B});break;case"metrics":r(m,T.id,{label:B});break;case"pivotBy":o(m,T.id,{label:B});break;case"sortBy":i(m,T.id,{label:B});break}},[m,j,n,r,o,i]),p=L.useCallback((g,x)=>{if(!m)return;const A=j("metrics")[g];A&&r(m,A.id,{aggregate:x,label:ds(A.name,x)})},[m,j,r]),D=L.useCallback((g,x,B)=>{if(!m)return;const T=j("groupBy")[g];if(!T)return;const b={dateFormat:x};x==="custom"&&B?b.customFormat=B:b.customFormat=void 0,n(m,T.id,b)},[m,j,n]),f=L.useCallback((g,x)=>{if(!m)return;const A=j("groupBy")[g];A&&n(m,A.id,{granularity:x})},[m,j,n]),y=L.useCallback((g,x)=>{if(!m)return;const A=j("metrics")[g];A&&r(m,A.id,{aliasTemplate:x})},[m,j,r]),O=L.useCallback((g,x)=>{if(console.log("handleValueAliasesChange",g,x),!m)return;console.log("handleValueAliasesChange",g,x);const A=j("metrics")[g];A&&(console.log("handleValueAliasesChange",x),r(m,A.id,{valueAliases:x}))},[m,j,r]),I=L.useCallback(g=>{m&&a(m,{comparisonType:g})},[m,a]),k=L.useCallback(g=>{m&&a(m,{showTrendline:g})},[m,a]),N=L.useCallback(g=>{m&&a(m,{trendlineWindow:g})},[m,a]),S=L.useCallback(g=>{m&&a(m,{trendlineGranularity:g})},[m,a]),w=L.useCallback(g=>{m&&a(m,{targetValue:g})},[m,a]),E=L.useCallback((g,x)=>{if(!m)return;const A=j(g)[x];if(A){if(g!=="sortBy"){const T=j("sortBy"),b=T.filter(M=>!(M.name===A.name&&M.qualifiedEntityName===A.qualifiedEntityName));b.length!==T.length&&a(m,{sortByColumns:b})}switch(g){case"groupBy":c(m,A.id);break;case"metrics":d(m,A.id);break;case"pivotBy":l(m,A.id);break;case"sortBy":h(m,A.id);break}}},[m,j,c,d,l,h,a]);return{getFieldsForContainer:j,setFieldsForContainer:v,updateLabel:C,handleAggregationChange:p,handleDateFormatChange:D,handleGranularityChange:f,handleAliasTemplateChange:y,handleValueAliasesChange:O,removeField:E,handleKpiComparisonTypeChange:I,handleKpiShowTrendlineChange:k,handleKpiTrendlineWindowChange:N,handleKpiTrendlineGranularityChange:S,handleKpiTargetValueChange:w,cardType:u}};function cr({field:s,zone:a,index:n,sortDirection:r,onSortDirectionChange:o,hasPivotColumns:i=!1,cardType:c}){var ft;const{attributes:d,listeners:l,setNodeRef:h,transform:u,transition:m,isDragging:j}=t.useSortable({id:s.id}),v=t.useEditorStore(Y=>Y.card),{updateLabel:C,handleAggregationChange:p,handleDateFormatChange:D,handleGranularityChange:f,handleAliasTemplateChange:y,handleValueAliasesChange:O,removeField:I,handleKpiComparisonTypeChange:k,handleKpiShowTrendlineChange:N,handleKpiTrendlineWindowChange:S,handleKpiTrendlineGranularityChange:w,handleKpiTargetValueChange:E}=us(v),[g,x]=L.useState(!1),[B,A]=L.useState(s.dateFormat||"YYYY-MM-DD"),[T,b]=L.useState(s.customFormat||""),[M,F]=L.useState(!!s.customFormat),[P,V]=L.useState(s.granularity||"day"),[z,U]=L.useState(s.aliasTemplate||""),[R,q]=L.useState(s.valueAliases||{}),[H,Q]=L.useState(((ft=v.config)==null?void 0:ft.targetValue)||0),G=Y=>{Y==="custom"?F(!0):(F(!1),A(Y),a==="groupBy"&&D(n,Y,""))},$=Y=>{b(Y),a==="groupBy"&&D(n,"custom",Y)},J=Y=>{V(Y),a==="groupBy"&&f(n,Y)},X=Y=>{U(Y),a==="metrics"&&y(n,Y)},te=Y=>{q(Y),a==="metrics"&&O(n,Y)},ne=Y=>{const ue=parseFloat(Y)||0;Q(ue),E(ue)},le=Y=>{C(a,n,Y)},oe=()=>{I(a,n)},ce={transform:t.CSS.Transform.toString(u),transition:m},ie=t.getDataType(s.dataType),_=ie==="date",K=c==="kpi",ae=[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}],de=!K&&a!=="pivotBy",me=K&&_&&a==="groupBy",W=!K&&_&&a==="groupBy",Z=K&&_&&a==="groupBy",ee=K&&a==="metrics",ps=a==="metrics",fs=()=>e.jsx("div",{onPointerDown:Y=>{Y.stopPropagation()},className:"cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${s.entityName}.${s.name}`}),gs=()=>de?e.jsx(or,{label:s.label??"",onLabelChange:le}):null,pt=()=>me?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(t.Select,{value:P,onValueChange:J,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"day",children:"Day"}),e.jsx(t.SelectItem,{value:"week",children:"Week"}),e.jsx(t.SelectItem,{value:"month",children:"Month"}),e.jsx(t.SelectItem,{value:"quarter",children:"Quarter"}),e.jsx(t.SelectItem,{value:"year",children:"Year"})]})]})]}):null,js=()=>W?e.jsxs(e.Fragment,{children:[pt(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(t.Select,{value:M?"custom":B,onValueChange:G,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select date format..."})}),e.jsx(t.SelectContent,{children:ae.map(Y=>e.jsx(t.SelectItem,{value:Y.value,children:Y.label},Y.value))})]}),M&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(t.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:T,onChange:Y=>{Y.stopPropagation(),$(Y.target.value)},onClick:Y=>Y.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,ys=()=>{var Y,ue,gt,jt,yt;return Z?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(t.Select,{value:((Y=v.config)==null?void 0:Y.comparisonType)||"previous_period",onValueChange:k,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(t.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(t.SelectItem,{value:"target",children:"Target Value"})]})]})]}),e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(t.SmallSwitch,{checked:((ue=v.config)==null?void 0:ue.showTrendline)||!1,onCheckedChange:N})]})}),((gt=v.config)==null?void 0:gt.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(t.Input$1,{type:"number",min:"1",max:"365",value:((jt=v.config)==null?void 0:jt.trendlineWindow)||30,onChange:Ns=>{const Cs=parseInt(Ns.target.value)||30;S(Cs)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(t.Select,{value:((yt=v.config)==null?void 0:yt.trendlineGranularity)||"day",onValueChange:w,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"day",children:"Day"}),e.jsx(t.SelectItem,{value:"week",children:"Week"}),e.jsx(t.SelectItem,{value:"month",children:"Month"})]})]})]})]})]}):null},bs=()=>ee?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(t.Input$1,{type:"number",value:H,onChange:Y=>ne(Y.target.value),className:"h-8 text-xs",placeholder:"Enter target value..."})]}):null,vs=()=>ps?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(t.Select,{value:s.aggregate,onValueChange:Y=>{p(n,Y)},children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select function..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"COUNT",children:"Count"}),e.jsx(t.SelectItem,{value:"DISTINCT",children:"Count Distinct"}),t.getDataType(s.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(t.SelectItem,{value:"SUM",children:"Sum"}),e.jsx(t.SelectItem,{value:"AVG",children:"Average"}),e.jsx(t.SelectItem,{value:"MIN",children:"Min"}),e.jsx(t.SelectItem,{value:"MAX",children:"Max"}),e.jsx(t.SelectItem,{value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsx(is,{column:s}),i&&e.jsxs(e.Fragment,{children:[e.jsx(ir,{aliasTemplate:z,onAliasTemplateChange:X}),e.jsx(lr,{valueAliases:R,onValueAliasesChange:te})]})]}):null;return e.jsxs("div",{ref:h,style:ce,...d,...l,className:`group mx-auto flex w-full max-w-[300px] flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${j?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.GripVertical,{className:"h-3 w-3"}),e.jsx(cs,{dataType:ie}),e.jsx(mt,{className:"max-w-[180px] flex-1 text-sm",children:s.label||s.name}),a!=="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:Y=>{Y.stopPropagation(),x(!g)},children:e.jsx(t.ChevronDown,{className:`h-3 w-3 transition-transform ${g?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:Y=>{Y.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ue=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ue),o(ue)},children:r==="asc"?e.jsx(t.ArrowUp,{className:"h-3 w-3"}):e.jsx(t.ArrowDown,{className:"h-3 w-3"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:Y=>{Y.stopPropagation(),oe()},children:e.jsx(t.X,{className:"h-3 w-3"})})]}),g&&e.jsxs("div",{className:"space-y-3",children:[fs(),gs(),pt(),js(),ys(),bs(),vs()]})]})}function dr({concept:s}){const a=()=>{switch(s){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{delayDuration:300,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(t.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function Ee({zone:s,fields:a,label:n,placeholder:r,shouldShow:o,hasPivotColumns:i=!1}){const{isOver:c,setNodeRef:d}=t.useDroppable({id:s}),{updateSortByColumn:l}=t.useEditorActions(),h=t.useEditorStore(C=>C.card),u=t.useEditorStore(C=>C.card.type),m=a.length>0,j=(C,p)=>{var f;!((f=h.config)!=null&&f.sortByColumns)||h.config.sortByColumns.findIndex(y=>y.id===C)===-1||l(h.id,C,{direction:p})};if(s==="sortBy"&&o===!1)return null;const v=s!=="sortBy"&&u!=="kpi";return e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(t.Label,{className:t.cn("block text-sm font-medium",{"text-green-600":s==="metrics","text-blue-600":s==="groupBy","text-purple-600":s==="pivotBy"}),children:n}),v&&e.jsx(dr,{concept:s})]}),e.jsx("div",{ref:d,className:`min-h-[60px] rounded-lg border-2 border-dashed p-3 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":"border-muted-foreground/20 bg-muted/50"}`,children:a.length===0?e.jsxs("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),r]}):e.jsx(t.SortableContext,{items:a.map(C=>C.id),strategy:t.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((C,p)=>{const f=C.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(cr,{field:C,zone:s,index:p,sortDirection:f,onSortDirectionChange:y=>j(C.id,y),hasPivotColumns:i,cardType:u})})},C.id)})})})})]})}function ur({groupByFields:s,pivotByFields:a,metricsFields:n,sortByFields:r}){const o=t.useEditorStore(m=>m.card),i=o==null?void 0:o.type,c=s.length>0||n.length>0,d=i!=="kpi",l=i!=="kpi"&&c,h=()=>i==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},u=()=>i==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ee,{zone:"groupBy",fields:s,label:h().label,placeholder:h().placeholder}),d&&e.jsx(Ee,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Ee,{zone:"metrics",fields:n,label:u().label,placeholder:u().placeholder,hasPivotColumns:a.length>0}),l&&e.jsx(Ee,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})}function mr({selectedChart:s,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i}){const c=t.useEditorStore(m=>m.showAIDialog),d=n.length>0||r.length>0||o.length>0,{setShowAIDialog:l}=t.useEditorActions(),h=t.useEditorStore(m=>m.card),{data:u}=t.useDashboardCardQuery(h);return e.jsxs("div",{className:"flex w-96 flex-col border-r bg-background",children:[e.jsxs("div",{className:"mt-1 space-y-4 border-b px-6 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.ChartColumn,{className:"h-5 w-5 text-brand"}),e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})]}),e.jsx(rr,{selectedChart:s,onChartChange:a})]}),e.jsxs("div",{className:t.cn("flex justify-end gap-2 px-6 pt-6"),children:[e.jsx("div",{className:t.cn("invisible",{visible:d||u}),children:e.jsx(t.EditorClearButton,{})}),!c&&e.jsxs(t.Button,{onClick:()=>l(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(gn,{className:"mr-2 size-4 text-brand"}),"AI"]})]}),e.jsxs(t.ScrollArea,{className:"flex-1 basis-0 px-6",children:[e.jsx(ur,{groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function hr({initialFilters:s,availableFields:a}={}){const[n,r]=L.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(k=>k.card.dataSource);const{columns:o,isLoading:i}=t.useColumns(),d=a||o||[],l={id:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},h=k=>{const N=S=>{if(S.id===k){const w=d[0]||l;return{...S,conditions:[...S.conditions,{id:`condition-${Date.now()}`,field:w,operator:"=",value:""}]}}return{...S,groups:S.groups.map(N)}};r(N(n))},u=k=>{const N=S=>{if(S.id===k){const w=d[0]||l;return{...S,groups:[...S.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:w,operator:"=",value:""}],groups:[]}]}}return{...S,groups:S.groups.map(N)}};r(N(n))},m=(k,N)=>{const S=w=>w.id===k?{...w,conditions:w.conditions.filter(E=>E.id!==N)}:{...w,groups:w.groups.map(S)};r(S(n))},j=(k,N)=>{const S=w=>w.id===k?{...w,groups:w.groups.filter(E=>E.id!==N)}:{...w,groups:w.groups.map(S)};r(S(n))},v=(k,N,S,w)=>{if(S==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const E=g=>g.id===k?{...g,conditions:g.conditions.map(x=>x.id===N?{...x,[S]:w}:x)}:{...g,groups:g.groups.map(E)};r(E(n))},C=(k,N,S)=>{const w=E=>E.id===k?{...E,conditions:E.conditions.map(g=>g.id===N?{...g,...S}:g)}:{...E,groups:E.groups.map(w)};r(w(n))},p=(k,N)=>{const S=w=>w.id===k?{...w,logicalOperator:N}:{...w,groups:w.groups.map(S)};r(S(n))},D=(k,N)=>{const S=w=>w.id===k?{...w,negate:N}:{...w,groups:w.groups.map(S)};r(S(n))},f=(k,N,S)=>{const w=E=>E.id===k?{...E,conditions:t.arrayMove(E.conditions,N,S)}:{...E,groups:E.groups.map(w)};r(w(n))},y=(k,N,S)=>{const w=E=>E.id===k?{...E,groups:t.arrayMove(E.groups,N,S)}:{...E,groups:E.groups.map(w)};r(w(n))},O=k=>{if(!k||k.conditions.length===0&&k.groups.length===0)return"-- No filters defined";const N=w=>{let E="";typeof w.field=="object"?E=w.field.entityName?`${w.field.entityName}.${w.field.name}`:w.field.name:E=String(w.field);const g=w.operator;let x=w.value;if(w.field.dataType==="string"&&!["in","not in"].includes(w.operator))typeof x=="string"?x=`'${x}'`:Array.isArray(x)&&(x=`'${x.join(", ")}'`);else if(w.field.dataType==="date")(typeof x=="string"||x instanceof Date)&&(x=`DATE('${x}')`);else if(["in","not in"].includes(w.operator)){let B=[];Array.isArray(x)?B=x.map(A=>typeof A=="string"?`'${A}'`:String(A)):typeof x=="string"?B=x.split(",").map(A=>{const T=A.trim();return w.field.dataType==="string"?`'${T}'`:T}):typeof x=="number"&&(B=[String(x)]),x=`(${B.join(", ")})`}switch(g){case"contains":return typeof x=="string"?`${E} LIKE '%${x.replace(/'/g,"")}'`:`${E} LIKE '%${String(x)}'`;case"startsWith":return typeof x=="string"?`${E} LIKE '${x.replace(/'/g,"")}%'`:`${E} LIKE '${String(x)}%'`;case"endsWith":return typeof x=="string"?`${E} LIKE '%${x.replace(/'/g,"")}'`:`${E} LIKE '%${String(x)}'`;default:return`${E} ${g} ${x}`}},S=w=>{const E=w.conditions.map(N),g=w.groups.map(T=>S(T)),x=[...E,...g].filter(Boolean);if(x.length===0)return"";const B=x.join(` ${w.logicalOperator} `),A=x.length>1?`(${B})`:B;return w.negate?`NOT ${A}`:A};return S(k)},I=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:d,isLoading:i,addCondition:h,addGroup:u,removeCondition:m,removeGroup:j,updateCondition:v,updateConditionFields:C,updateGroupOperator:p,updateGroupNegate:D,reorderConditions:f,reorderGroups:y,generateSQLPreview:O,hasAnyFilters:I}}function xr({children:s,className:a,delayDuration:n}){return e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{delayDuration:n,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:t.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:s})}),e.jsx(t.PortalTooltipContent,{children:s})]})})}const pr=s=>{switch(s){case"table":return e.jsx(t.Table,{className:"h-3 w-3"});case"view":return e.jsx(t.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(t.ChartColumn,{className:"h-3 w-3"});case"file":return e.jsx(Qs,{className:"h-3 w-3"});default:return e.jsx(t.Table,{className:"h-3 w-3"})}},fr=s=>{if(s.qualifiedEntityName){const a=s.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function gr({value:s,onValueChange:a,availableFields:n,placeholder:r="Select field",className:o="w-64"}){const[i,c]=L.useState(!1),d=L.useMemo(()=>{const l={};return n.forEach(h=>{const u=fr(h);l[u]||(l[u]={}),l[u][h.entityId]||(l[u][h.entityId]=[]),l[u][h.entityId].push(h)}),l},[n]);return e.jsxs(t.Popover,{modal:!0,open:i,onOpenChange:c,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:t.cn("justify-between",!s&&"text-muted-foreground",o),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(xr,{children:[s.entityName,".",s.name]})}):r,e.jsx(t.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(t.CommandEmpty,{children:"No fields found."}),e.jsx(t.CommandList,{className:"max-h-80",children:Object.entries(d).map(([l,h])=>e.jsx(t.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Database,{className:"h-3 w-3"}),l]}),children:Object.entries(h).map(([u,m])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[pr(m[0].entityType),e.jsx("span",{children:m[0].entityName})]}),m.map((j,v)=>e.jsxs(t.CommandItem,{value:j.id,onSelect:()=>{a(j),c(!1)},className:"overflow-x-auto",children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",(s==null?void 0:s.id)===j.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:j.name})}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:[e.jsx("span",{children:j.dataType}),j.description&&e.jsxs("span",{children:["• ",j.description]}),j.customFormat&&e.jsxs("span",{children:["• ",j.customFormat]})]})]})]},j.id+v))]},`${l}-${u}`))},l))})]})})]})}function xt(s){var C;const a=t.useEditorStore(p=>p.card),{authToken:n}=t.useSemaphorContext(),r=t.useEditorStore(p=>p.card.config),o=r==null?void 0:r.joinPlan,i={...s,alias:s.name,label:"value",role:"groupby"},c={...s,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},d={...i,role:"sortby",direction:"asc"},l={joinPlan:o,groupByColumns:[i],metricColumns:[c],sortByColumns:[d]},h=((C=a.dataSource)==null?void 0:C.connectionId)||a.connectionId,{data:u,isPending:m,error:j}=t.useQuery({queryKey:["filterValues",s.entityId,s.name,s.qualifiedEntityName],queryFn:async()=>{try{return await t.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:h,cardConfig:l,cardDataSource:a.dataSource})}catch(p){console.log(s),console.error("error",p)}},enabled:!!h,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((u==null?void 0:u.records)||[]).map(p=>({label:p[s.name]||"BLANK",value:p[s.name]||"BLANK",count:(p==null?void 0:p.count)||0})),isPending:m,error:j}}function jr({field:s,selected:a,onChange:n,placeholder:r="Select items...",className:o}){const[i,c]=he.useState(!1),{filterValues:d}=xt(s),l=u=>{n(a.filter(m=>m!==u))},h=u=>{a.includes(u)?n(a.filter(m=>m!==u)):n([...a,u])};return e.jsx("div",{className:t.cn("w-full",o),children:e.jsxs(t.Popover,{open:i,onOpenChange:c,modal:!0,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(u=>{const m=d.find(j=>j.value===u);return e.jsxs(t.Badge,{variant:"secondary",className:"text-xs",children:[m==null?void 0:m.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:j=>{j.key==="Enter"&&l(u)},onMouseDown:j=>{j.preventDefault(),j.stopPropagation()},onClick:j=>{j.stopPropagation(),l(u)},children:e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},u)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(t.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No results found."}),e.jsx(t.CommandGroup,{children:d.map((u,m)=>e.jsxs(t.CommandItem,{onSelect:()=>h(u.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",a.includes(u.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.count})]})]},u.value+m))})]})]})})]})})}const ms=s=>{if(!s)return 0;let a=s.conditions.length;return s.groups.forEach(n=>{a+=ms(n)}),a};function yr({field:s,value:a,onChange:n,placeholder:r="Select value...",className:o}){const{filterValues:i,isPending:c,error:d}=xt(s);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):d?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(t.Select,{value:a,onValueChange:n,children:[e.jsx(t.SelectTrigger,{className:o||"flex-1",children:e.jsx(t.SelectValue,{placeholder:r,children:a})}),e.jsx(t.SelectContent,{children:i.map((l,h)=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:l.value,children:l.label},l.value+h))})]})}const br=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],vr=["=","!=","contains","startsWith","endsWith","in","not in"],Nr=["=","!=",">",">=","<","<=","in","not in"],Cr=["=","!="],Sr=["=","!=",">",">=","<","<=","in","not in"];function wr(s){switch(s){case"string":return vr;case"number":return Nr;case"boolean":return Cr;case"date":return Sr;default:return br}}function hs({condition:s,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:o,onRemoveCondition:i,onUpdateGroupOperator:c,availableFields:d,updateConditionFields:l}){const{attributes:h,listeners:u,setNodeRef:m,transform:j,transition:v,isDragging:C}=t.useSortable({id:s.id}),{isPending:p,error:D}=xt(s.field),f={transform:t.CSS.Transform.toString(j),transition:v};return e.jsxs("div",{ref:m,style:f,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${C?"z-50 opacity-50":""}`,children:[e.jsx("div",{...h,...u,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(t.Select,{value:r,onValueChange:y=>c(n,y),children:[e.jsx(t.SelectTrigger,{className:"w-24",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(gr,{value:s.field,onValueChange:y=>{l(n,s.id,{field:y,value:""})},availableFields:d,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:y=>{y==="in"||y==="not in"?l(n,s.id,{operator:y,value:[]}):l(n,s.id,{operator:y,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-28",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:wr(t.getDataType(s.field.dataType)).map(y=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:y,children:y},y))})]}),t.getDataType(s.field.dataType)==="string"?s.operator==="in"||s.operator==="not in"?p?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):D?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(jr,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(y=>typeof y=="string")?s.value:[],onChange:y=>l(n,s.id,{value:y}),placeholder:`Select values for ${s.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(s.operator)?e.jsx(t.Input$1,{value:typeof s.value=="string"?s.value:"",onChange:y=>l(n,s.id,{value:y.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(yr,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:y=>l(n,s.id,{value:y}),placeholder:"Select value...",className:"flex-1"}):t.getDataType(s.field.dataType)==="boolean"?e.jsxs(t.Select,{value:typeof s.value=="boolean"?String(s.value):"",onValueChange:y=>l(n,s.id,{value:y==="true"}),children:[e.jsx(t.SelectTrigger,{className:"flex-1",children:e.jsx(t.SelectValue,{placeholder:"Select value..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"true",children:"True"}),e.jsx(t.SelectItem,{value:"false",children:"False"})]})]}):e.jsx(t.Input$1,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:y=>o(n,s.id,"value",y.target.value),className:"flex-1",placeholder:s.operator==="in"||s.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>i(n,s.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]})}function kr({group:s,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:i,onUpdateCondition:c,onUpdateField:d,onRemoveCondition:l,onReorderConditions:h,onReorderGroups:u,onAddCondition:m,onAddGroup:j,availableFields:v,renderFilterGroup:C,updateConditionFields:p}){const{attributes:D,listeners:f,setNodeRef:y,transform:O,transition:I,isDragging:k}=t.useSortable({id:s.id}),N={transform:t.CSS.Transform.toString(O),transition:I},S=E=>{const{active:g,over:x}=E;if(x&&g.id!==x.id){const B=s.conditions.findIndex(T=>T.id===g.id),A=s.conditions.findIndex(T=>T.id===x.id);B!==-1&&A!==-1&&h(s.id,B,A)}},w=E=>{const{active:g,over:x}=E;if(x&&g.id!==x.id&&n){const B=s.groups.findIndex(T=>T.id===g.id),A=s.groups.findIndex(T=>T.id===x.id);B!==-1&&A!==-1&&u(n,B,A)}};return e.jsxs("div",{ref:y,style:N,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${k?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...D,...f,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(t.Button,{variant:s.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>o(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:E=>r(s.id,E),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&i(n,s.id),children:e.jsx(t.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:S,children:e.jsx(t.SortableContext,{items:s.conditions.map(E=>E.id),strategy:t.verticalListSortingStrategy,children:s.conditions.map((E,g)=>e.jsx(hs,{condition:E,index:g,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:c,onUpdateField:d,onRemoveCondition:l,onUpdateGroupOperator:r,availableFields:v,updateConditionFields:p},E.id))})}),e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:w,children:e.jsx(t.SortableContext,{items:s.groups.map(E=>E.id),strategy:t.verticalListSortingStrategy,children:s.groups.map(E=>C(E,a+1,s.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>m(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>j(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Er({filters:s,availableFields:a,onSave:n,onClearAll:r,onCancel:o}){const{currentFilters:i,availableFields:c,isLoading:d,addCondition:l,addGroup:h,removeCondition:u,removeGroup:m,updateCondition:j,updateConditionFields:v,updateGroupOperator:C,updateGroupNegate:p,reorderConditions:D,reorderGroups:f,generateSQLPreview:y,hasAnyFilters:O,setCurrentFilters:I}=hr({initialFilters:s,availableFields:a}),k=t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),[N,S]=L.useState(!1),w=(x,B,A)=>{const T=b=>b.id===x?{...b,conditions:b.conditions.map(M=>M.id===B?{...M,field:A,dataType:A.dataType}:M)}:{...b,groups:b.groups.map(T)};I(T(i))},E=(x,B=0,A)=>B===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(t.DndContext,{sensors:k,collisionDetection:t.closestCenter,onDragEnd:T=>{const{active:b,over:M}=T;if(M&&b.id!==M.id){const F=x.conditions.findIndex(V=>V.id===b.id),P=x.conditions.findIndex(V=>V.id===M.id);F!==-1&&P!==-1&&D(x.id,F,P)}},children:e.jsx(t.SortableContext,{items:x.conditions.map(T=>T.id),strategy:t.verticalListSortingStrategy,children:x.conditions.map((T,b)=>e.jsx(hs,{condition:T,index:b,groupId:x.id,groupLogicalOperator:x.logicalOperator,onUpdateCondition:j,onUpdateField:w,onRemoveCondition:u,onUpdateGroupOperator:C,availableFields:c,updateConditionFields:v},T.id))})}),e.jsx(t.DndContext,{sensors:k,collisionDetection:t.closestCenter,onDragEnd:T=>{const{active:b,over:M}=T;if(M&&b.id!==M.id){const F=x.groups.findIndex(V=>V.id===b.id),P=x.groups.findIndex(V=>V.id===M.id);F!==-1&&P!==-1&&f(x.id,F,P)}},children:e.jsx(t.SortableContext,{items:x.groups.map(T=>T.id),strategy:t.verticalListSortingStrategy,children:x.groups.map(T=>E(T,B+1,x.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>l(x.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),N&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>h(x.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},x.id):e.jsx(kr,{group:x,depth:B,parentGroupId:A,onUpdateGroupOperator:C,onUpdateGroupNegate:p,onRemoveGroup:m,onUpdateCondition:j,onUpdateField:w,onRemoveCondition:u,onReorderConditions:D,onReorderGroups:f,onAddCondition:l,onAddGroup:h,availableFields:c,renderFilterGroup:E,updateConditionFields:v},x.id),g=ms(s);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(t.Card,{children:e.jsx(t.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[d?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):E(i),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Checkbox,{id:"advanced-mode",checked:N,onCheckedChange:x=>S(!!x)}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),O&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:y(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:o,children:"Cancel"}),g>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>n(O?i:null),children:"Apply Filters"})]})]})}function Dr({cardId:s,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:o,isOpen:i,onOpenChange:c}){const d=h=>{n(s,h),c(!1)},l=()=>{r(s),c(!1)};return e.jsxs(t.Dialog,{modal:!1,open:i,onOpenChange:c,children:[i&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(t.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:h=>{h.preventDefault()},children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Card Filters"}),e.jsx(t.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Er,{filters:a,availableFields:o,onSave:d,onCancel:()=>c(!1),onClearAll:l})]})]})}function xs(s,a){return`${s}-${a.qualifiedEntityName}-${a.name}-${Date.now()}`}function Tr({activeCardId:s,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var D;const[o,i]=L.useState(null),c=t.useEditorStore(f=>f.card),d=(D=c==null?void 0:c.config)==null?void 0:D.joinPlan,l=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],h=L.useCallback(f=>f.startsWith("card-")?null:f.startsWith("source-")||a.find(y=>y.id===f)?"source":n("groupBy").find(y=>y.id===f)?"groupBy":n("metrics").find(y=>y.id===f)?"metrics":n("pivotBy").find(y=>y.id===f)?"pivotBy":n("sortBy").find(y=>y.id===f)?"sortBy":null,[a,n]),u=L.useCallback((f,y)=>{var O;return!d||!((O=d.baseEntity)!=null&&O.name)||!d.joins?!1:f===y||f===d.baseEntity.name||y===d.baseEntity.name?!0:d.joins.some(I=>{const k=t.getQualifiedEntityName(I.source),N=t.getQualifiedEntityName(I.target);return console.log(k,N),console.log(k===f&&N===y||k===y&&N===f),k===f&&N===y||k===y&&N===f})},[d]),m=L.useCallback(()=>{t.ue.error("Join Configuration Required",{richColors:!0,description:"To combine fields from two different tables, you need to define a join between them first.",position:"top-center",duration:4e3})},[]),j=(f,y)=>{const O=xs(y,f),I=t.getDataType(f.dataType),k=I==="date",N={id:O,name:f.name,dataType:f.dataType,label:t.toLabel(f.name),qualifiedEntityName:f.qualifiedEntityName,entityId:f.entityId,entityName:f.entityName,entityType:f.entityType};if(y==="metrics"){const S=I==="number"?"SUM":"COUNT",w=ds(f.label,S);return{...N,role:"metric",label:w,aggregate:S}}return y==="groupBy"?{...N,role:"groupby",...k&&{granularity:"month"}}:y==="pivotBy"?{...N,role:"pivotby"}:y==="sortBy"?{...N,role:"sortby",label:f.label,direction:"asc"}:null},v=L.useCallback(f=>{i(f.active.id)},[]),C=L.useCallback(f=>{const{active:y,over:O}=f;if(!O||!s){i(null);return}const I=y.id,k=O.id,N=h(I),S=h(k)||k;if(N==="source"&&S==="sortBy"){i(null);return}if(N==="source"&&S!=="source"&&S!=="sortBy"){const w=[...a].find(A=>A.id===I);if(!w){i(null);return}const E=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(E.length>0){const A=E[0].qualifiedEntityName;if(!A){i(null);return}if(A!==w.qualifiedEntityName&&w.qualifiedEntityName)if(d){if(!u(A,w.qualifiedEntityName)){m(),i(null);return}}else{m(),i(null);return}}const g=n(S);if(g.some(A=>A.name===w.name&&A.qualifiedEntityName===w.qualifiedEntityName)){i(null);return}const B=j(w,S);i(null),r(S,[...g,B]);return}if(N&&S&&N!=="source"&&S!=="source"&&N!==S){const w=n(N),E=n(S),g=w.find(A=>A.id===I);if(!g){i(null);return}const x=j(g,S);if(i(null),S==="sortBy"){if(N==="pivotBy"){i(null);return}E.some(T=>T.name===g.name&&T.qualifiedEntityName===g.qualifiedEntityName)||r(S,[...E,x]);return}const B=w.filter(A=>A.id!==I);r(N,B),r(S,[...E,x]);return}if(N&&S&&N===S&&N!=="source"){const w=n(N),E=w.findIndex(x=>x.id===I),g=w.findIndex(x=>x.id===k);if(E!==g){const x=t.arrayMove(w,E,g);r(N,x)}}i(null)},[s,a,n,r,h,d,m,u]),p=o?l.find(f=>f.id===o):null;return{activeId:o,activeField:p,handleDragStart:v,handleDragEnd:C}}function Ir({activeView:s,onViewChange:a}){const n=t.useEditorStore(o=>o.card),{errorMessage:r}=t.useDashboardCardQuery(n);return e.jsx(t.Tabs,{value:s,onValueChange:o=>a(o),children:e.jsxs(t.TabsList,{className:"h-9 w-fit gap-2 bg-background p-0",children:[e.jsx(t.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(t.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),n.type!=="kpi"&&e.jsx(t.TabsTrigger,{value:"sql",className:t.cn("rounded-md transition data-[state=active]:bg-muted",r&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:r?"Error":"Query"})]})})}const Mr=[{value:"10",label:"Top 10"},{value:"20",label:"Top 20"},{value:"50",label:"Top 50"},{value:"100",label:"Top 100"},{value:"200",label:"Top 200"},{value:"500",label:"Top 500"},{value:"1000",label:"Top 1000"}];function Ar(){var l,h;const s=t.useEditorStore(u=>u.card),{updateRowLimit:a}=t.useEditorActions(),[n,r]=L.useState(!1),[o,i]=L.useState(""),c=u=>{if(u==="custom"){r(!0);return}r(!1),a(s.id,parseInt(u))},d=u=>{const m=u.target.value;i(m),m&&!isNaN(parseInt(m))&&a(s.id,parseInt(m))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(t.Input,{type:"number",value:o,onChange:d,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((h=(l=s.config)==null?void 0:l.rowLimit)==null?void 0:h.toString())||"100",onValueChange:c,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(t.SelectValue,{placeholder:"Select limit"})}),e.jsx(t.SelectContent,{children:Mr.map(u=>e.jsx(t.SelectItem,{value:u.value,children:u.label},u.value))})]})})}function Lr({activeView:s,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:c,onFiltersClick:d,filterCount:l,activeCard:h,columns:u,columnsLoading:m,columnsError:j}){var E;const v=t.useEditorStore(g=>g.card),C=t.useDashboardStore(g=>g.filterValues),{updateCardConfig:p}=t.useEditorActions(),D=t.useEditorStore(g=>g.showAIDialog),{data:f,errorMessage:y,isPending:O,isLoading:I,isFetching:k}=t.useDashboardCardQuery(h);function N(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(v.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(C||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(h.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",u.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:m?"Loading...":j?"Error loading columns":JSON.stringify(u.slice(0,5),null,2)})]})]})})}const S=g=>{if(!v.config)return;if(!g.length){p(v.id,{...v.config,sortByColumns:[]});return}const x=v.config,B=g.map(({id:A,desc:T})=>{var P,V;const b=(P=x.metricColumns)==null?void 0:P.find(z=>z.label===A),M=(V=x.groupByColumns)==null?void 0:V.find(z=>z.label===A),F=b||M;return F?{id:xs("sortBy",F),name:F.name,dataType:F.dataType,label:F.label,qualifiedEntityName:F.qualifiedEntityName,entityId:F.entityId,entityName:F.entityName,entityType:F.entityType,role:"sortby",direction:T?"desc":"asc"}:null}).filter(A=>A!==null);p(v.id,{...x,sortByColumns:B})},w=L.useMemo(()=>{var g,x;return(x=(g=v.config)==null?void 0:g.sortByColumns)==null?void 0:x.map(B=>({id:B.label,desc:B.direction==="desc"}))},[(E=v.config)==null?void 0:E.sortByColumns]);return e.jsxs("div",{className:"flex w-0 grow flex-col",children:[e.jsx(t.ExplorerHeader,{showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:c,onFiltersClick:d,filterCount:l}),n&&N(),e.jsx(t.Separator,{}),e.jsxs("div",{className:"group/visualization flex max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"z-50 flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s==="chart"&&D&&e.jsx(Zt,{variant:"outline"}),e.jsx(Ir,{activeView:s,onViewChange:a}),d&&e.jsxs(t.IconButton,{tooltip:"Card Filters",className:"h-8 gap-1",onClick:d,children:[e.jsx(t.Filter,{className:"h-3.5 w-3.5"}),l>0&&e.jsx("span",{className:"ml-1 rounded-full bg-blue-100 px-1.5 py-0.5 text-xs text-blue-800",children:l})]}),e.jsx("div",{className:"ml-2",children:e.jsx(Ar,{})})]}),e.jsx("div",{className:t.cn("flex grow items-center justify-end"),children:s==="chart"&&e.jsx(es,{})})]}),e.jsxs("div",{className:"flex grow flex-col",children:[s==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:I||k?e.jsx("div",{className:"m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(t.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx(ts,{})}),s==="table"&&(f==null?void 0:f.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:[(I||k)&&e.jsx("div",{className:"absolute flex h-full w-full items-center justify-between",children:e.jsx("div",{className:"z-10 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(t.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}),e.jsx(t.TableVisual,{card:h,data:f==null?void 0:f.records,onSortChange:S,sortState:w})]}),s==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md border bg-background p-4",children:[(f==null?void 0:f.sql)&&e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx($t,{sql:f==null?void 0:f.sql,error:y})]})})]})]})]})}function Or({activeField:s}){const[a,n]=L.useState(!0);return L.useEffect(()=>{s&&n(!0)},[s]),s?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(t.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(cs,{dataType:s.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:s.label||s.name})]}):null}const Br=()=>{const s=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||s.apply(console,r)};const a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var o;if((o=r.reason)!=null&&o.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=s,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Fr(){var z,U;const[s,a]=L.useState("chart"),[n,r]=L.useState(!1),[o,i]=L.useState(!1),c=t.useEditorStore(R=>R.showAIDialog),{setCardType:d}=t.useEditorActions(),l=t.useEditorStore(R=>R.card.type);L.useEffect(()=>Br(),[]);const h=()=>{console.log("Accept clicked - would save/apply current configuration")},u=()=>{console.log("Clear clicked - would reset all configurations")},m=()=>{console.log("Advanced mode toggled")},j=()=>{i(!0)},v=R=>{d(R)},C=t.useEditorStore(R=>R.frame),p=t.useEditorStore(R=>R.card);t.useEditorStore(R=>R.activeTabCardId),t.useEditorStore(R=>R.actions.getAvailableFields);const{addCard:D,removeCard:f,updateCard:y,setActiveCard:O,updateFilters:I}=t.useEditorActions(),{columns:k=[],isLoading:N,error:S}=t.useColumns(),w=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),E=p,{getFieldsForContainer:g,setFieldsForContainer:x}=us(E),{activeField:B,handleDragStart:A,handleDragEnd:T}=Tr({activeCardId:C.activeCardId,sourceFields:k,getFieldsForContainer:g,setFieldsForContainer:x}),b=(R,q)=>{q&&I(R,q)},M=R=>{var q;y(R,{config:{...(q=C.cards.find(H=>H.id===R))==null?void 0:q.config,filters:void 0}})},F=k,P=R=>{if(!R)return 0;let q=R.conditions.length;return R.groups.forEach(H=>{q+=P(H)}),q},V=P(((z=E==null?void 0:E.config)==null?void 0:z.filters)||null);return e.jsxs(t.DndContext,{sensors:w,collisionDetection:t.closestCenter,onDragStart:A,onDragEnd:T,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(nr,{}),!c&&e.jsx(mr,{selectedChart:l,onChartChange:v,groupByFields:g("groupBy"),pivotByFields:g("pivotBy"),metricsFields:g("metrics"),sortByFields:g("sortBy")}),e.jsx(Lr,{selectedChart:l,activeView:s,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:h,onClear:u,onAdvancedToggle:m,onFiltersClick:j,filterCount:V,activeCard:E,dataSourceState:p.dataSource||t.EMPTY_DATA_SOURCE,columns:k,columnsLoading:N,columnsError:S,getFieldsForContainer:g,cards:C.cards,activeCardId:C.activeCardId,addCard:D,setActiveCard:O})]}),E&&e.jsx(Dr,{cardId:E.id,filters:((U=E.config)==null?void 0:U.filters)||null,onFiltersChange:b,onClearFilters:M,availableFields:F,isOpen:o,onOpenChange:i}),e.jsx(t.DragOverlay,{dropAnimation:null,children:e.jsx(Or,{activeField:B||null})})]})}function zr({authToken:s,onSave:a,onClose:n}){const r=L.useRef(null),o=t.useEditorStore(y=>y.showAIDialog),i=t.useEditorStore(y=>y.isDevMode),{setAuthToken:c}=t.useDashboardActions(),{setShowAIDialog:d,setOnSave:l,setOnClose:h}=t.useEditorActions(),{handleDragOver:u,handleDragEnd:m,handleDragStart:j,handleDragCancel:v,sensors:C}=An();L.useEffect(()=>{a&&l(a),n&&h(n)},[a,l,n,h]),L.useEffect(()=>{s&&s.accessToken&&c(s)},[s,c]),L.useEffect(()=>{var y,O;o?((y=r.current)==null||y.resize(40),d(!0)):(d(!1),(O=r.current)==null||O.resize(0))},[o,d]);function p(y){y<1?d(!1):o||d(!0)}function D(){return e.jsxs(e.Fragment,{children:[e.jsx(_t,{type:"main"}),e.jsxs(t.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Ha,{})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(Et,{})})]})]})}function f(){return e.jsxs(t.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Fr,{})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(Et,{})})]})}return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:i?e.jsx(t.DndContext,{sensors:C,onDragStart:j,onDragEnd:m,onDragOver:u,onDragCancel:v,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:D()})}):f()})}function Pr(){t.useDashboardStore(c=>c.selectedCardId);const s=t.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=t.useDashboardStore(c=>c.actions),n=t.useDashboardStore(c=>c.isVisualEditing),r=t.useDashboardStore(c=>c.actions.updateFrame);function o(c){s&&(r(s,c),a(!1))}function i(){a(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex grow",{"max-h-0 overflow-hidden":!n}),children:e.jsx(zr,{onSave:o,onClose:i})})}function Rr(){const s=t.useEditorStore(i=>i.selectedDatabaseName),a=t.useEditorStore(i=>i.selectedTableName),n=t.useDashboardStore(i=>i.dashboard.filters)||[],{columns:r}=t.useEditorAside(),{assignFilter:o}=rs();return e.jsx(t.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(i=>{const c=n==null?void 0:n.find(d=>d.column===t.fmt(i.column_name)&&d.table===a&&d.database===s);return e.jsx("div",{onClick:()=>o(i),className:t.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rt,{column:i}),e.jsx("span",{children:i.column_name})]})},i.column_name)})})}function Vr(){t.useDashboardStore(a=>a.showFilters);const s=t.useDashboardStore(a=>a.actions.setShowFilters);return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(t.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(t.Button,{onClick:()=>s(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(t.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:e.jsx(_t,{type:"filter",ColumnsComponent:()=>e.jsx(Rr,{})})})]})}function qr(){const s=t.useDashboardStore(r=>r.dashboard.filters),a=t.useDashboardStore(r=>r.theme),n=s==null?void 0:s.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:t.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(t.FilterHeader,{filter:r}),e.jsx(t.FilterComponent,{filter:r})]},r.id))}):null}function _r(){const s=t.useDashboardStore(r=>r.showFilters),a=t.useDashboardStore(r=>r.isVisualEditing),n=t.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:t.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(qr,{}),e.jsx(t.DashboardTabs,{})]}),s&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Vr,{})})]})}function Gr(){const s=t.useDashboardStore(o=>o.dashboard),a=t.useDashboardStore(o=>o.actions.setDashboard),n=t.useDashboardStore(o=>o.showDashboardJSON),r=t.useDashboardStore(o=>o.actions.setShowDashboardJSON);return e.jsxs("div",{className:t.cn("relative p-2",{hidden:!n}),children:[e.jsxs(t.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(t.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(t.de,{onChange:o=>{if(o)try{JSON.parse(o),a(JSON.parse(o))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(s,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function $r({showControls:s=!1,showFooter:a=!0,...n}){return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:e.jsxs(t.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(t.$e,{}),e.jsxs(t.UXProvider,{children:[e.jsx(Gr,{}),e.jsxs(t.DashboardPanel,{...n,children:[s&&e.jsx(En,{}),e.jsx(Pr,{}),e.jsx(_r,{})]})]})]})})}exports.DashboardPlus=$r;exports.ScheduleDashboard=Vt;exports.SelectComponent=ye;exports.cleanCard=zt;exports.downloadPdf=Rt;exports.getDashbaordStateWithoutData=at;
375
+ ON ${j}`}),C};return i.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[n.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>o(!0),children:[e.jsx(t.Link,{className:t.cn("mr-1 h-3 w-3",{"text-blue-500":n.joins.length>0,"text-gray-500":n.joins.length===0})}),"Join",n.joins.length>1?"s":""," (",n.joins.length,")"]})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(tr,{joins:n.joins,baseEntityId:n.baseEntity.name,availableDataSources:i,generateSQLPreview:h})})]})}),e.jsx(Dt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:i,onSave:c,onCancel:l,onRemove:d,children:e.jsx("div",{})})]}),n.joins.length===0&&e.jsx(Dt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:i,onSave:c,onCancel:l,onRemove:d,children:e.jsxs(t.Button,{onClick:()=>o(!0),variant:"outline",className:"h-6 text-xs font-semibold",children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Configure Join"]})})]})})})}function nr(){const[s,a]=L.useState(!1),[n,r]=L.useState(!0),o=t.useEditorStore(l=>l.card.dataSource),{updateDataSource:i}=t.useEditorActions(),c={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},d={...c,...o,selectedEntities:(o==null?void 0:o.selectedEntities)||[]};return e.jsxs("div",{className:"flex w-[325px] flex-col border-r bg-background",children:[e.jsxs("div",{children:[e.jsx("div",{className:t.cn("p-4 px-6",{"pb-0":!n}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",onClick:()=>r(!n),children:[n?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronRight,{className:"h-4 w-4"}),e.jsx(t.Database,{className:"h-5 w-5 text-brand"}),e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"})]}),e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-7",onClick:()=>a(!0),children:[e.jsx(t.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${n?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[d.selectedEntities.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1",children:[d.selectedEntities.slice(0,3).map((l,h)=>e.jsxs(t.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[t.getDisplayName(l),e.jsx("button",{onClick:u=>{u.stopPropagation();const m=d.selectedEntities.filter(y=>!(y.name===l.name&&y.type===l.type));i({...c,...o,selectedEntities:m})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 hover:bg-red-100",children:e.jsx(t.X,{className:"h-2.5 w-2.5 group-hover:text-red-500"})})]},`${l.type}-${l.name}-${h}`)),d.selectedEntities.length>3&&e.jsxs(t.Badge,{variant:"outline",className:"text-xs",children:["+",d.selectedEntities.length-3," more"]})]}),e.jsx(sr,{})]})]}),e.jsx(Xa,{}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:(o==null?void 0:o.selectedEntities)||[],dialogMode:"dataSource",open:s,onOpenChange:a,dataSource:d,fallbackDataSource:c})]})}const ar=[{id:"table",icon:Oe,label:"Table"},{id:"bar",icon:Ae,label:"Bar Chart"},{id:"line",icon:Le,label:"Line Chart"},{id:"stackedBar",icon:Ke,label:"Stacked Bar Chart"},{id:"stackedLine",icon:dt,label:"Stacked Line Chart"},{id:"scatter",icon:We,label:"Scatter Chart"},{id:"bubble",icon:lt,label:"Bubble Chart"},{id:"pie",icon:Qe,label:"Pie Chart"},{id:"doughnut",icon:Xe,label:"Doughnut Chart"},{id:"funnel",icon:ct,label:"Funnel Chart"},{id:"radar",icon:tt,label:"Radar Chart"},{id:"polarArea",icon:it,label:"Polar Area Chart"},{id:"tornado",icon:nt,label:"Tornado Chart"},{id:"range",icon:Ue,label:"Range Chart"},{id:"kpi",icon:ut,label:"KPI"},{id:"text",icon:Tt,label:"Text"},{id:"map",icon:et,label:"Map"},{id:"custom",icon:st,label:"Custom"}];function rr({selectedChart:s,onChartChange:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:o}=t.useEditorStore(h=>h.actions),{setCardCustomCfg:i,setCustomCardPreferences:c,setQueryConfig:d}=t.useEditorActions();function l(h){i(null),r({}),n(h),["custom","text","map"].includes(h)&&(o(!0),d(void 0)),a(h)}return e.jsx("div",{className:"mb-6",children:e.jsxs(t.Select,{value:s,onValueChange:l,children:[e.jsx(t.SelectTrigger,{className:"w-full",children:e.jsx(t.SelectValue,{placeholder:"Select chart type"})}),e.jsx(t.SelectContent,{children:ar.map(h=>{const u=h.icon;return e.jsx(t.SelectItem,{value:h.id,className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(u,{className:"h-4 w-4"}),e.jsx("span",{children:h.label})]})},h.id)})})]})})}const cs=({dataType:s})=>{const a=t.getDataType(s);return a==="string"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-blue-500 text-xs text-white",children:"T"}):a==="number"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-green-500 text-xs text-white",children:"#"}):a==="date"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-purple-500 text-xs text-white",children:"D"}):a==="boolean"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-orange-500 text-xs text-white",children:"B"}):e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-gray-500 text-xs text-white",children:"?"})};function or({label:s,onLabelChange:a}){const[n,r]=L.useState(s??""),[o,i]=L.useState(!1);return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Display Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Input$1,{placeholder:"Display label...",value:o?n:s??"",onChange:c=>{r(c.target.value),i(!0)},onFocus:()=>i(!0),onClick:c=>c.stopPropagation(),className:"h-8 text-xs",onPointerDown:c=>c.stopPropagation(),onKeyDown:c=>{c.stopPropagation(),c.key==="Enter"&&o&&n!==(s??"")?(a(n),i(!1)):c.key==="Escape"&&(r(s??""),i(!1))},"aria-label":"Edit display label"}),o&&n!==(s??"")&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm label",onClick:()=>{a(n),i(!1)},children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel label edit",onClick:()=>{r(s??""),i(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})]})}function ir({aliasTemplate:s,onAliasTemplateChange:a}){var l;const[n,r]=L.useState(s),[o,i]=L.useState(!1),c=(l=t.useEditorStore(h=>{var u;return(u=h.card.config)==null?void 0:u.pivotByColumns}))==null?void 0:l[0],d=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Input$1,{placeholder:d,value:o?n:s,onChange:h=>{r(h.target.value),i(!0)},onFocus:()=>i(!0),onPointerDown:h=>h.stopPropagation(),className:"h-8 text-xs",onKeyDown:h=>{h.key==="Enter"&&o&&n!==s?(a(n),i(!1)):h.key==="Escape"&&(r(s),i(!1))},"aria-label":"Edit alias template"}),o&&n!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),i(!1)},children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(s),i(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function lr({valueAliases:s,onValueAliasesChange:a}){const[n,r]=L.useState(null),[o,i]=L.useState(""),[c,d]=L.useState(""),l=()=>{a({...s,"":""})},h=m=>{const y={...s};delete y[m],a(y)},u=m=>{const y={...s};delete y[m],y[o]=c,a(y),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(s).map(([m,y],v)=>e.jsx("div",{className:"flex items-center gap-2",children:n===m?e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:o,onChange:C=>i(C.target.value),className:"h-8 w-24 text-xs",onPointerDown:C=>C.stopPropagation(),onKeyDown:C=>{C.key==="Enter"?u(m):C.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{placeholder:"Alias label",value:c,onChange:C=>d(C.target.value),className:"h-8 w-24 text-xs",onPointerDown:C=>C.stopPropagation(),onKeyDown:C=>{C.key==="Enter"?u(m):C.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>u(m),children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:m,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),i(m),d(y)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{placeholder:"Alias label",value:y,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),i(m),d(y)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>h(m),"aria-label":"Remove value alias",children:e.jsx(t.X,{className:"h-3 w-3"})})]})},m+v)),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:l,children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function ds(s,a){return`${t.toLabel(a)} of ${t.toLabel(s)}`}const us=s=>{const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:o,updateSortByColumn:i,removeGroupByColumn:c,removeMetricColumn:d,removePivotByColumn:l,removeSortByColumn:h}=t.useEditorActions(),u=t.useEditorStore(g=>g.card.type),m=s==null?void 0:s.id,y=L.useCallback(g=>{if(!(s!=null&&s.config))return[];switch(g){case"groupBy":return(s.config.groupByColumns||[]).map(x=>({id:x.id,name:x.name,dataType:x.dataType,label:x.label!==void 0?x.label:x.name,qualifiedEntityName:x.qualifiedEntityName,entityId:x.entityId,entityName:x.entityName,entityType:x.entityType,dateFormat:x.dateFormat,customFormat:x.customFormat,granularity:x.granularity}));case"metrics":return s.config.metricColumns||[];case"pivotBy":return(s.config.pivotByColumns||[]).map(x=>({id:x.id,name:x.name,dataType:x.dataType,label:x.label!==void 0?x.label:x.name,qualifiedEntityName:x.qualifiedEntityName,entityId:x.entityId,entityName:x.entityName,entityType:x.entityType}));case"sortBy":return(s.config.sortByColumns||[]).map(x=>({id:x.id,name:x.name,dataType:x.dataType,label:x.label!==void 0?x.label:x.name,qualifiedEntityName:x.qualifiedEntityName,entityId:x.entityId,entityName:x.entityName,entityType:x.entityType,direction:x.direction}));case"source":return[];default:return[]}},[s]),v=L.useCallback((g,x)=>{if(m)switch(g){case"groupBy":{a(m,{groupByColumns:x});break}case"metrics":{a(m,{metricColumns:x});break}case"pivotBy":{a(m,{pivotByColumns:x});break}case"sortBy":{a(m,{sortByColumns:x});break}}},[m,a]),C=L.useCallback((g,x,B)=>{if(!m)return;const T=y(g)[x];if(T)switch(g){case"groupBy":n(m,T.id,{label:B});break;case"metrics":r(m,T.id,{label:B});break;case"pivotBy":o(m,T.id,{label:B});break;case"sortBy":i(m,T.id,{label:B});break}},[m,y,n,r,o,i]),p=L.useCallback((g,x)=>{if(!m)return;const A=y("metrics")[g];A&&r(m,A.id,{aggregate:x,label:ds(A.name,x)})},[m,y,r]),D=L.useCallback((g,x,B)=>{if(!m)return;const T=y("groupBy")[g];if(!T)return;const b={dateFormat:x};x==="custom"&&B?b.customFormat=B:b.customFormat=void 0,n(m,T.id,b)},[m,y,n]),f=L.useCallback((g,x)=>{if(!m)return;const A=y("groupBy")[g];A&&n(m,A.id,{granularity:x})},[m,y,n]),j=L.useCallback((g,x)=>{if(!m)return;const A=y("metrics")[g];A&&r(m,A.id,{aliasTemplate:x})},[m,y,r]),O=L.useCallback((g,x)=>{if(console.log("handleValueAliasesChange",g,x),!m)return;console.log("handleValueAliasesChange",g,x);const A=y("metrics")[g];A&&(console.log("handleValueAliasesChange",x),r(m,A.id,{valueAliases:x}))},[m,y,r]),I=L.useCallback(g=>{m&&a(m,{comparisonType:g})},[m,a]),k=L.useCallback(g=>{m&&a(m,{showTrendline:g})},[m,a]),N=L.useCallback(g=>{m&&a(m,{trendlineWindow:g})},[m,a]),S=L.useCallback(g=>{m&&a(m,{trendlineGranularity:g})},[m,a]),w=L.useCallback(g=>{m&&a(m,{targetValue:g})},[m,a]),E=L.useCallback((g,x)=>{if(!m)return;const A=y(g)[x];if(A){if(g!=="sortBy"){const T=y("sortBy"),b=T.filter(M=>!(M.name===A.name&&M.qualifiedEntityName===A.qualifiedEntityName));b.length!==T.length&&a(m,{sortByColumns:b})}switch(g){case"groupBy":c(m,A.id);break;case"metrics":d(m,A.id);break;case"pivotBy":l(m,A.id);break;case"sortBy":h(m,A.id);break}}},[m,y,c,d,l,h,a]);return{getFieldsForContainer:y,setFieldsForContainer:v,updateLabel:C,handleAggregationChange:p,handleDateFormatChange:D,handleGranularityChange:f,handleAliasTemplateChange:j,handleValueAliasesChange:O,removeField:E,handleKpiComparisonTypeChange:I,handleKpiShowTrendlineChange:k,handleKpiTrendlineWindowChange:N,handleKpiTrendlineGranularityChange:S,handleKpiTargetValueChange:w,cardType:u}};function cr({field:s,zone:a,index:n,sortDirection:r,onSortDirectionChange:o,hasPivotColumns:i=!1,cardType:c}){var ft;const{attributes:d,listeners:l,setNodeRef:h,transform:u,transition:m,isDragging:y}=t.useSortable({id:s.id}),v=t.useEditorStore(Y=>Y.card),{updateLabel:C,handleAggregationChange:p,handleDateFormatChange:D,handleGranularityChange:f,handleAliasTemplateChange:j,handleValueAliasesChange:O,removeField:I,handleKpiComparisonTypeChange:k,handleKpiShowTrendlineChange:N,handleKpiTrendlineWindowChange:S,handleKpiTrendlineGranularityChange:w,handleKpiTargetValueChange:E}=us(v),[g,x]=L.useState(!1),[B,A]=L.useState(s.dateFormat||"YYYY-MM-DD"),[T,b]=L.useState(s.customFormat||""),[M,F]=L.useState(!!s.customFormat),[P,V]=L.useState(s.granularity||"day"),[z,U]=L.useState(s.aliasTemplate||""),[R,q]=L.useState(s.valueAliases||{}),[H,Q]=L.useState(((ft=v.config)==null?void 0:ft.targetValue)||0),G=Y=>{Y==="custom"?F(!0):(F(!1),A(Y),a==="groupBy"&&D(n,Y,""))},$=Y=>{b(Y),a==="groupBy"&&D(n,"custom",Y)},J=Y=>{V(Y),a==="groupBy"&&f(n,Y)},X=Y=>{U(Y),a==="metrics"&&j(n,Y)},te=Y=>{q(Y),a==="metrics"&&O(n,Y)},ne=Y=>{const ue=parseFloat(Y)||0;Q(ue),E(ue)},le=Y=>{C(a,n,Y)},oe=()=>{I(a,n)},ce={transform:t.CSS.Transform.toString(u),transition:m},ie=t.getDataType(s.dataType),_=ie==="date",K=c==="kpi",ae=[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}],de=!K&&a!=="pivotBy",me=K&&_&&a==="groupBy",W=!K&&_&&a==="groupBy",Z=K&&_&&a==="groupBy",ee=K&&a==="metrics",ps=a==="metrics",fs=()=>e.jsx("div",{onPointerDown:Y=>{Y.stopPropagation()},className:"cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${s.entityName}.${s.name}`}),gs=()=>de?e.jsx(or,{label:s.label??"",onLabelChange:le}):null,pt=()=>me?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(t.Select,{value:P,onValueChange:J,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"day",children:"Day"}),e.jsx(t.SelectItem,{value:"week",children:"Week"}),e.jsx(t.SelectItem,{value:"month",children:"Month"}),e.jsx(t.SelectItem,{value:"quarter",children:"Quarter"}),e.jsx(t.SelectItem,{value:"year",children:"Year"})]})]})]}):null,js=()=>W?e.jsxs(e.Fragment,{children:[pt(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(t.Select,{value:M?"custom":B,onValueChange:G,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select date format..."})}),e.jsx(t.SelectContent,{children:ae.map(Y=>e.jsx(t.SelectItem,{value:Y.value,children:Y.label},Y.value))})]}),M&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(t.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:T,onChange:Y=>{Y.stopPropagation(),$(Y.target.value)},onClick:Y=>Y.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,ys=()=>{var Y,ue,gt,jt,yt;return Z?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(t.Select,{value:((Y=v.config)==null?void 0:Y.comparisonType)||"previous_period",onValueChange:k,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(t.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(t.SelectItem,{value:"target",children:"Target Value"})]})]})]}),e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(t.SmallSwitch,{checked:((ue=v.config)==null?void 0:ue.showTrendline)||!1,onCheckedChange:N})]})}),((gt=v.config)==null?void 0:gt.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(t.Input$1,{type:"number",min:"1",max:"365",value:((jt=v.config)==null?void 0:jt.trendlineWindow)||30,onChange:Ns=>{const Cs=parseInt(Ns.target.value)||30;S(Cs)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(t.Select,{value:((yt=v.config)==null?void 0:yt.trendlineGranularity)||"day",onValueChange:w,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"day",children:"Day"}),e.jsx(t.SelectItem,{value:"week",children:"Week"}),e.jsx(t.SelectItem,{value:"month",children:"Month"})]})]})]})]})]}):null},bs=()=>ee?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(t.Input$1,{type:"number",value:H,onChange:Y=>ne(Y.target.value),className:"h-8 text-xs",placeholder:"Enter target value..."})]}):null,vs=()=>ps?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(t.Select,{value:s.aggregate,onValueChange:Y=>{p(n,Y)},children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select function..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"COUNT",children:"Count"}),e.jsx(t.SelectItem,{value:"DISTINCT",children:"Count Distinct"}),t.getDataType(s.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(t.SelectItem,{value:"SUM",children:"Sum"}),e.jsx(t.SelectItem,{value:"AVG",children:"Average"}),e.jsx(t.SelectItem,{value:"MIN",children:"Min"}),e.jsx(t.SelectItem,{value:"MAX",children:"Max"}),e.jsx(t.SelectItem,{value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsx(is,{column:s}),i&&e.jsxs(e.Fragment,{children:[e.jsx(ir,{aliasTemplate:z,onAliasTemplateChange:X}),e.jsx(lr,{valueAliases:R,onValueAliasesChange:te})]})]}):null;return e.jsxs("div",{ref:h,style:ce,...d,...l,className:`group mx-auto flex w-full max-w-[300px] flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${y?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.GripVertical,{className:"h-3 w-3"}),e.jsx(cs,{dataType:ie}),e.jsx(mt,{className:"max-w-[180px] flex-1 text-sm",children:s.label||s.name}),a!=="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:Y=>{Y.stopPropagation(),x(!g)},children:e.jsx(t.ChevronDown,{className:`h-3 w-3 transition-transform ${g?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:Y=>{Y.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ue=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ue),o(ue)},children:r==="asc"?e.jsx(t.ArrowUp,{className:"h-3 w-3"}):e.jsx(t.ArrowDown,{className:"h-3 w-3"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:Y=>{Y.stopPropagation(),oe()},children:e.jsx(t.X,{className:"h-3 w-3"})})]}),g&&e.jsxs("div",{className:"space-y-3",children:[fs(),gs(),pt(),js(),ys(),bs(),vs()]})]})}function dr({concept:s}){const a=()=>{switch(s){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{delayDuration:300,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(t.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function Ee({zone:s,fields:a,label:n,placeholder:r,shouldShow:o,hasPivotColumns:i=!1}){const{isOver:c,setNodeRef:d}=t.useDroppable({id:s}),{updateSortByColumn:l}=t.useEditorActions(),h=t.useEditorStore(C=>C.card),u=t.useEditorStore(C=>C.card.type),m=a.length>0,y=(C,p)=>{var f;!((f=h.config)!=null&&f.sortByColumns)||h.config.sortByColumns.findIndex(j=>j.id===C)===-1||l(h.id,C,{direction:p})};if(s==="sortBy"&&o===!1)return null;const v=s!=="sortBy"&&u!=="kpi";return e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(t.Label,{className:t.cn("block text-sm font-medium",{}),children:n}),v&&e.jsx(dr,{concept:s})]}),e.jsx("div",{ref:d,className:`min-h-[60px] rounded-lg border-2 border-dashed p-3 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":"border-muted-foreground/20 bg-muted/50"}`,children:a.length===0?e.jsxs("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),r]}):e.jsx(t.SortableContext,{items:a.map(C=>C.id),strategy:t.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((C,p)=>{const f=C.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(cr,{field:C,zone:s,index:p,sortDirection:f,onSortDirectionChange:j=>y(C.id,j),hasPivotColumns:i,cardType:u})})},C.id)})})})})]})}function ur({groupByFields:s,pivotByFields:a,metricsFields:n,sortByFields:r}){const o=t.useEditorStore(m=>m.card),i=o==null?void 0:o.type,c=s.length>0||n.length>0,d=i!=="kpi",l=i!=="kpi"&&c,h=()=>i==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},u=()=>i==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ee,{zone:"groupBy",fields:s,label:h().label,placeholder:h().placeholder}),d&&e.jsx(Ee,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Ee,{zone:"metrics",fields:n,label:u().label,placeholder:u().placeholder,hasPivotColumns:a.length>0}),l&&e.jsx(Ee,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})}function mr({selectedChart:s,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i}){const c=t.useEditorStore(m=>m.showAIDialog),d=n.length>0||r.length>0||o.length>0,{setShowAIDialog:l}=t.useEditorActions(),h=t.useEditorStore(m=>m.card),{data:u}=t.useDashboardCardQuery(h);return e.jsxs("div",{className:"flex w-96 flex-col border-r bg-background",children:[e.jsxs("div",{className:"mt-1 space-y-4 border-b px-6 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.ChartColumn,{className:"h-5 w-5 text-brand"}),e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})]}),e.jsx(rr,{selectedChart:s,onChartChange:a})]}),e.jsxs("div",{className:t.cn("flex justify-end gap-2 px-6 pt-6"),children:[e.jsx("div",{className:t.cn("invisible",{visible:d||u}),children:e.jsx(t.EditorClearButton,{})}),!c&&e.jsxs(t.Button,{onClick:()=>l(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(gn,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(t.ScrollArea,{className:"flex-1 basis-0 px-6",children:[e.jsx(ur,{groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function hr({initialFilters:s,availableFields:a}={}){const[n,r]=L.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(k=>k.card.dataSource);const{columns:o,isLoading:i}=t.useColumns(),d=a||o||[],l={id:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},h=k=>{const N=S=>{if(S.id===k){const w=d[0]||l;return{...S,conditions:[...S.conditions,{id:`condition-${Date.now()}`,field:w,operator:"=",value:""}]}}return{...S,groups:S.groups.map(N)}};r(N(n))},u=k=>{const N=S=>{if(S.id===k){const w=d[0]||l;return{...S,groups:[...S.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:w,operator:"=",value:""}],groups:[]}]}}return{...S,groups:S.groups.map(N)}};r(N(n))},m=(k,N)=>{const S=w=>w.id===k?{...w,conditions:w.conditions.filter(E=>E.id!==N)}:{...w,groups:w.groups.map(S)};r(S(n))},y=(k,N)=>{const S=w=>w.id===k?{...w,groups:w.groups.filter(E=>E.id!==N)}:{...w,groups:w.groups.map(S)};r(S(n))},v=(k,N,S,w)=>{if(S==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const E=g=>g.id===k?{...g,conditions:g.conditions.map(x=>x.id===N?{...x,[S]:w}:x)}:{...g,groups:g.groups.map(E)};r(E(n))},C=(k,N,S)=>{const w=E=>E.id===k?{...E,conditions:E.conditions.map(g=>g.id===N?{...g,...S}:g)}:{...E,groups:E.groups.map(w)};r(w(n))},p=(k,N)=>{const S=w=>w.id===k?{...w,logicalOperator:N}:{...w,groups:w.groups.map(S)};r(S(n))},D=(k,N)=>{const S=w=>w.id===k?{...w,negate:N}:{...w,groups:w.groups.map(S)};r(S(n))},f=(k,N,S)=>{const w=E=>E.id===k?{...E,conditions:t.arrayMove(E.conditions,N,S)}:{...E,groups:E.groups.map(w)};r(w(n))},j=(k,N,S)=>{const w=E=>E.id===k?{...E,groups:t.arrayMove(E.groups,N,S)}:{...E,groups:E.groups.map(w)};r(w(n))},O=k=>{if(!k||k.conditions.length===0&&k.groups.length===0)return"-- No filters defined";const N=w=>{let E="";typeof w.field=="object"?E=w.field.entityName?`${w.field.entityName}.${w.field.name}`:w.field.name:E=String(w.field);const g=w.operator;let x=w.value;if(w.field.dataType==="string"&&!["in","not in"].includes(w.operator))typeof x=="string"?x=`'${x}'`:Array.isArray(x)&&(x=`'${x.join(", ")}'`);else if(w.field.dataType==="date")(typeof x=="string"||x instanceof Date)&&(x=`DATE('${x}')`);else if(["in","not in"].includes(w.operator)){let B=[];Array.isArray(x)?B=x.map(A=>typeof A=="string"?`'${A}'`:String(A)):typeof x=="string"?B=x.split(",").map(A=>{const T=A.trim();return w.field.dataType==="string"?`'${T}'`:T}):typeof x=="number"&&(B=[String(x)]),x=`(${B.join(", ")})`}switch(g){case"contains":return typeof x=="string"?`${E} LIKE '%${x.replace(/'/g,"")}'`:`${E} LIKE '%${String(x)}'`;case"startsWith":return typeof x=="string"?`${E} LIKE '${x.replace(/'/g,"")}%'`:`${E} LIKE '${String(x)}%'`;case"endsWith":return typeof x=="string"?`${E} LIKE '%${x.replace(/'/g,"")}'`:`${E} LIKE '%${String(x)}'`;default:return`${E} ${g} ${x}`}},S=w=>{const E=w.conditions.map(N),g=w.groups.map(T=>S(T)),x=[...E,...g].filter(Boolean);if(x.length===0)return"";const B=x.join(` ${w.logicalOperator} `),A=x.length>1?`(${B})`:B;return w.negate?`NOT ${A}`:A};return S(k)},I=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:d,isLoading:i,addCondition:h,addGroup:u,removeCondition:m,removeGroup:y,updateCondition:v,updateConditionFields:C,updateGroupOperator:p,updateGroupNegate:D,reorderConditions:f,reorderGroups:j,generateSQLPreview:O,hasAnyFilters:I}}function xr({children:s,className:a,delayDuration:n}){return e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{delayDuration:n,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:t.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:s})}),e.jsx(t.PortalTooltipContent,{children:s})]})})}const pr=s=>{switch(s){case"table":return e.jsx(t.Table,{className:"h-3 w-3"});case"view":return e.jsx(t.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(t.ChartColumn,{className:"h-3 w-3"});case"file":return e.jsx(Qs,{className:"h-3 w-3"});default:return e.jsx(t.Table,{className:"h-3 w-3"})}},fr=s=>{if(s.qualifiedEntityName){const a=s.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function gr({value:s,onValueChange:a,availableFields:n,placeholder:r="Select field",className:o="w-64"}){const[i,c]=L.useState(!1),d=L.useMemo(()=>{const l={};return n.forEach(h=>{const u=fr(h);l[u]||(l[u]={}),l[u][h.entityId]||(l[u][h.entityId]=[]),l[u][h.entityId].push(h)}),l},[n]);return e.jsxs(t.Popover,{modal:!0,open:i,onOpenChange:c,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:t.cn("justify-between",!s&&"text-muted-foreground",o),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(xr,{children:[s.entityName,".",s.name]})}):r,e.jsx(t.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(t.CommandEmpty,{children:"No fields found."}),e.jsx(t.CommandList,{className:"max-h-80",children:Object.entries(d).map(([l,h])=>e.jsx(t.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Database,{className:"h-3 w-3"}),l]}),children:Object.entries(h).map(([u,m])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[pr(m[0].entityType),e.jsx("span",{children:m[0].entityName})]}),m.map((y,v)=>e.jsxs(t.CommandItem,{value:y.id,onSelect:()=>{a(y),c(!1)},className:"overflow-x-auto",children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",(s==null?void 0:s.id)===y.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:y.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:y.description&&e.jsx("span",{children:y.description})})]})]},y.id+v))]},`${l}-${u}`))},l))})]})})]})}function xt(s){var C;const a=t.useEditorStore(p=>p.card),{authToken:n}=t.useSemaphorContext(),r=t.useEditorStore(p=>p.card.config),o=r==null?void 0:r.joinPlan,i={...s,alias:s.name,label:"value",role:"groupby"},c={...s,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},d={...i,role:"sortby",direction:"asc"},l={joinPlan:o,groupByColumns:[i],metricColumns:[c],sortByColumns:[d]},h=((C=a.dataSource)==null?void 0:C.connectionId)||a.connectionId,{data:u,isPending:m,error:y}=t.useQuery({queryKey:["filterValues",s.entityId,s.name,s.qualifiedEntityName],queryFn:async()=>{try{return await t.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:h,cardConfig:l,cardDataSource:a.dataSource})}catch(p){console.log(s),console.error("error",p)}},enabled:!!h,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((u==null?void 0:u.records)||[]).map(p=>({label:p[s.name]||"BLANK",value:p[s.name]||"BLANK",count:(p==null?void 0:p.count)||0})),isPending:m,error:y}}function jr({field:s,selected:a,onChange:n,placeholder:r="Select items...",className:o}){const[i,c]=he.useState(!1),{filterValues:d}=xt(s),l=u=>{n(a.filter(m=>m!==u))},h=u=>{a.includes(u)?n(a.filter(m=>m!==u)):n([...a,u])};return e.jsx("div",{className:t.cn("w-full",o),children:e.jsxs(t.Popover,{open:i,onOpenChange:c,modal:!0,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(u=>{const m=d.find(y=>y.value===u);return e.jsxs(t.Badge,{variant:"secondary",className:"text-xs",children:[m==null?void 0:m.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:y=>{y.key==="Enter"&&l(u)},onMouseDown:y=>{y.preventDefault(),y.stopPropagation()},onClick:y=>{y.stopPropagation(),l(u)},children:e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},u)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(t.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No results found."}),e.jsx(t.CommandGroup,{children:d.map((u,m)=>e.jsxs(t.CommandItem,{onSelect:()=>h(u.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",a.includes(u.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.count})]})]},u.value+m))})]})]})})]})})}const ms=s=>{if(!s)return 0;let a=s.conditions.length;return s.groups.forEach(n=>{a+=ms(n)}),a};function yr({field:s,value:a,onChange:n,placeholder:r="Select value...",className:o}){const{filterValues:i,isPending:c,error:d}=xt(s);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):d?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(t.Select,{value:a,onValueChange:n,children:[e.jsx(t.SelectTrigger,{className:o||"flex-1",children:e.jsx(t.SelectValue,{placeholder:r,children:a})}),e.jsx(t.SelectContent,{children:i.map((l,h)=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:l.value,children:l.label},l.value+h))})]})}const br=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],vr=["=","!=","contains","startsWith","endsWith","in","not in"],Nr=["=","!=",">",">=","<","<=","in","not in"],Cr=["=","!="],Sr=["=","!=",">",">=","<","<=","in","not in"];function wr(s){switch(s){case"string":return vr;case"number":return Nr;case"boolean":return Cr;case"date":return Sr;default:return br}}function hs({condition:s,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:o,onRemoveCondition:i,onUpdateGroupOperator:c,availableFields:d,updateConditionFields:l}){const{attributes:h,listeners:u,setNodeRef:m,transform:y,transition:v,isDragging:C}=t.useSortable({id:s.id}),{isPending:p,error:D}=xt(s.field),f={transform:t.CSS.Transform.toString(y),transition:v};return e.jsxs("div",{ref:m,style:f,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${C?"z-50 opacity-50":""}`,children:[e.jsx("div",{...h,...u,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(t.Select,{value:r,onValueChange:j=>c(n,j),children:[e.jsx(t.SelectTrigger,{className:"w-24",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(gr,{value:s.field,onValueChange:j=>{l(n,s.id,{field:j,value:""})},availableFields:d,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:j=>{j==="in"||j==="not in"?l(n,s.id,{operator:j,value:[]}):l(n,s.id,{operator:j,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-28",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:wr(t.getDataType(s.field.dataType)).map(j=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:j,children:j},j))})]}),t.getDataType(s.field.dataType)==="string"?s.operator==="in"||s.operator==="not in"?p?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):D?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(jr,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(j=>typeof j=="string")?s.value:[],onChange:j=>l(n,s.id,{value:j}),placeholder:`Select values for ${s.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(s.operator)?e.jsx(t.Input$1,{value:typeof s.value=="string"?s.value:"",onChange:j=>l(n,s.id,{value:j.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(yr,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:j=>l(n,s.id,{value:j}),placeholder:"Select value...",className:"flex-1"}):t.getDataType(s.field.dataType)==="boolean"?e.jsxs(t.Select,{value:typeof s.value=="boolean"?String(s.value):"",onValueChange:j=>l(n,s.id,{value:j==="true"}),children:[e.jsx(t.SelectTrigger,{className:"flex-1",children:e.jsx(t.SelectValue,{placeholder:"Select value..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"true",children:"True"}),e.jsx(t.SelectItem,{value:"false",children:"False"})]})]}):e.jsx(t.Input$1,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:j=>o(n,s.id,"value",j.target.value),className:"flex-1",placeholder:s.operator==="in"||s.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>i(n,s.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]})}function kr({group:s,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:i,onUpdateCondition:c,onUpdateField:d,onRemoveCondition:l,onReorderConditions:h,onReorderGroups:u,onAddCondition:m,onAddGroup:y,availableFields:v,renderFilterGroup:C,updateConditionFields:p}){const{attributes:D,listeners:f,setNodeRef:j,transform:O,transition:I,isDragging:k}=t.useSortable({id:s.id}),N={transform:t.CSS.Transform.toString(O),transition:I},S=E=>{const{active:g,over:x}=E;if(x&&g.id!==x.id){const B=s.conditions.findIndex(T=>T.id===g.id),A=s.conditions.findIndex(T=>T.id===x.id);B!==-1&&A!==-1&&h(s.id,B,A)}},w=E=>{const{active:g,over:x}=E;if(x&&g.id!==x.id&&n){const B=s.groups.findIndex(T=>T.id===g.id),A=s.groups.findIndex(T=>T.id===x.id);B!==-1&&A!==-1&&u(n,B,A)}};return e.jsxs("div",{ref:j,style:N,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${k?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...D,...f,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(t.Button,{variant:s.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>o(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:E=>r(s.id,E),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&i(n,s.id),children:e.jsx(t.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:S,children:e.jsx(t.SortableContext,{items:s.conditions.map(E=>E.id),strategy:t.verticalListSortingStrategy,children:s.conditions.map((E,g)=>e.jsx(hs,{condition:E,index:g,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:c,onUpdateField:d,onRemoveCondition:l,onUpdateGroupOperator:r,availableFields:v,updateConditionFields:p},E.id))})}),e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:w,children:e.jsx(t.SortableContext,{items:s.groups.map(E=>E.id),strategy:t.verticalListSortingStrategy,children:s.groups.map(E=>C(E,a+1,s.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>m(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>y(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Er({filters:s,availableFields:a,onSave:n,onClearAll:r,onCancel:o}){const{currentFilters:i,availableFields:c,isLoading:d,addCondition:l,addGroup:h,removeCondition:u,removeGroup:m,updateCondition:y,updateConditionFields:v,updateGroupOperator:C,updateGroupNegate:p,reorderConditions:D,reorderGroups:f,generateSQLPreview:j,hasAnyFilters:O,setCurrentFilters:I}=hr({initialFilters:s,availableFields:a}),k=t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),[N,S]=L.useState(!1),w=(x,B,A)=>{const T=b=>b.id===x?{...b,conditions:b.conditions.map(M=>M.id===B?{...M,field:A,dataType:A.dataType}:M)}:{...b,groups:b.groups.map(T)};I(T(i))},E=(x,B=0,A)=>B===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(t.DndContext,{sensors:k,collisionDetection:t.closestCenter,onDragEnd:T=>{const{active:b,over:M}=T;if(M&&b.id!==M.id){const F=x.conditions.findIndex(V=>V.id===b.id),P=x.conditions.findIndex(V=>V.id===M.id);F!==-1&&P!==-1&&D(x.id,F,P)}},children:e.jsx(t.SortableContext,{items:x.conditions.map(T=>T.id),strategy:t.verticalListSortingStrategy,children:x.conditions.map((T,b)=>e.jsx(hs,{condition:T,index:b,groupId:x.id,groupLogicalOperator:x.logicalOperator,onUpdateCondition:y,onUpdateField:w,onRemoveCondition:u,onUpdateGroupOperator:C,availableFields:c,updateConditionFields:v},T.id))})}),e.jsx(t.DndContext,{sensors:k,collisionDetection:t.closestCenter,onDragEnd:T=>{const{active:b,over:M}=T;if(M&&b.id!==M.id){const F=x.groups.findIndex(V=>V.id===b.id),P=x.groups.findIndex(V=>V.id===M.id);F!==-1&&P!==-1&&f(x.id,F,P)}},children:e.jsx(t.SortableContext,{items:x.groups.map(T=>T.id),strategy:t.verticalListSortingStrategy,children:x.groups.map(T=>E(T,B+1,x.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>l(x.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),N&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>h(x.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},x.id):e.jsx(kr,{group:x,depth:B,parentGroupId:A,onUpdateGroupOperator:C,onUpdateGroupNegate:p,onRemoveGroup:m,onUpdateCondition:y,onUpdateField:w,onRemoveCondition:u,onReorderConditions:D,onReorderGroups:f,onAddCondition:l,onAddGroup:h,availableFields:c,renderFilterGroup:E,updateConditionFields:v},x.id),g=ms(s);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(t.Card,{children:e.jsx(t.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[d?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):E(i),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Checkbox,{id:"advanced-mode",checked:N,onCheckedChange:x=>S(!!x)}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),O&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:j(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:o,children:"Cancel"}),g>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>n(O?i:null),children:"Apply Filters"})]})]})}function Dr({cardId:s,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:o,isOpen:i,onOpenChange:c}){const d=h=>{n(s,h),c(!1)},l=()=>{r(s),c(!1)};return e.jsxs(t.Dialog,{modal:!1,open:i,onOpenChange:c,children:[i&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(t.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:h=>{h.preventDefault()},children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Card Filters"}),e.jsx(t.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Er,{filters:a,availableFields:o,onSave:d,onCancel:()=>c(!1),onClearAll:l})]})]})}function xs(s,a){return`${s}-${a.qualifiedEntityName}-${a.name}-${Date.now()}`}function Tr({activeCardId:s,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var D;const[o,i]=L.useState(null),c=t.useEditorStore(f=>f.card),d=(D=c==null?void 0:c.config)==null?void 0:D.joinPlan,l=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],h=L.useCallback(f=>f.startsWith("card-")?null:f.startsWith("source-")||a.find(j=>j.id===f)?"source":n("groupBy").find(j=>j.id===f)?"groupBy":n("metrics").find(j=>j.id===f)?"metrics":n("pivotBy").find(j=>j.id===f)?"pivotBy":n("sortBy").find(j=>j.id===f)?"sortBy":null,[a,n]),u=L.useCallback((f,j)=>{var O;return!d||!((O=d.baseEntity)!=null&&O.name)||!d.joins?!1:f===j||f===d.baseEntity.name||j===d.baseEntity.name?!0:d.joins.some(I=>{const k=t.getQualifiedEntityName(I.source),N=t.getQualifiedEntityName(I.target);return console.log(k,N),console.log(k===f&&N===j||k===j&&N===f),k===f&&N===j||k===j&&N===f})},[d]),m=L.useCallback(()=>{t.ue.error("Join Configuration Required",{richColors:!0,description:"To combine fields from two different tables, you need to define a join between them first.",position:"top-center",duration:4e3})},[]),y=(f,j)=>{const O=xs(j,f),I=t.getDataType(f.dataType),k=I==="date",N={id:O,name:f.name,dataType:f.dataType,label:t.toLabel(f.name),qualifiedEntityName:f.qualifiedEntityName,entityId:f.entityId,entityName:f.entityName,entityType:f.entityType};if(j==="metrics"){const S=I==="number"?"SUM":"COUNT",w=ds(f.label,S);return{...N,role:"metric",label:w,aggregate:S}}return j==="groupBy"?{...N,role:"groupby",...k&&{granularity:"month"}}:j==="pivotBy"?{...N,role:"pivotby"}:j==="sortBy"?{...N,role:"sortby",label:f.label,direction:"asc"}:null},v=L.useCallback(f=>{i(f.active.id)},[]),C=L.useCallback(f=>{const{active:j,over:O}=f;if(!O||!s){i(null);return}const I=j.id,k=O.id,N=h(I),S=h(k)||k;if(N==="source"&&S==="sortBy"){i(null);return}if(N==="source"&&S!=="source"&&S!=="sortBy"){const w=[...a].find(A=>A.id===I);if(!w){i(null);return}const E=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(E.length>0){const A=E[0].qualifiedEntityName;if(!A){i(null);return}if(A!==w.qualifiedEntityName&&w.qualifiedEntityName)if(d){if(!u(A,w.qualifiedEntityName)){m(),i(null);return}}else{m(),i(null);return}}const g=n(S);if(g.some(A=>A.name===w.name&&A.qualifiedEntityName===w.qualifiedEntityName)){i(null);return}const B=y(w,S);i(null),r(S,[...g,B]);return}if(N&&S&&N!=="source"&&S!=="source"&&N!==S){const w=n(N),E=n(S),g=w.find(A=>A.id===I);if(!g){i(null);return}const x=y(g,S);if(i(null),S==="sortBy"){if(N==="pivotBy"){i(null);return}E.some(T=>T.name===g.name&&T.qualifiedEntityName===g.qualifiedEntityName)||r(S,[...E,x]);return}const B=w.filter(A=>A.id!==I);r(N,B),r(S,[...E,x]);return}if(N&&S&&N===S&&N!=="source"){const w=n(N),E=w.findIndex(x=>x.id===I),g=w.findIndex(x=>x.id===k);if(E!==g){const x=t.arrayMove(w,E,g);r(N,x)}}i(null)},[s,a,n,r,h,d,m,u]),p=o?l.find(f=>f.id===o):null;return{activeId:o,activeField:p,handleDragStart:v,handleDragEnd:C}}function Ir({activeView:s,onViewChange:a}){const n=t.useEditorStore(o=>o.card),{errorMessage:r}=t.useDashboardCardQuery(n);return e.jsx(t.Tabs,{value:s,onValueChange:o=>a(o),children:e.jsxs(t.TabsList,{className:"h-9 w-fit gap-2 bg-background p-0",children:[e.jsx(t.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(t.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),n.type!=="kpi"&&e.jsx(t.TabsTrigger,{value:"sql",className:t.cn("rounded-md transition data-[state=active]:bg-muted",r&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:r?"Error":"Query"})]})})}const Mr=[{value:"10",label:"Top 10"},{value:"20",label:"Top 20"},{value:"50",label:"Top 50"},{value:"100",label:"Top 100"},{value:"200",label:"Top 200"},{value:"500",label:"Top 500"},{value:"1000",label:"Top 1000"}];function Ar(){var l,h;const s=t.useEditorStore(u=>u.card),{updateRowLimit:a}=t.useEditorActions(),[n,r]=L.useState(!1),[o,i]=L.useState(""),c=u=>{if(u==="custom"){r(!0);return}r(!1),a(s.id,parseInt(u))},d=u=>{const m=u.target.value;i(m),m&&!isNaN(parseInt(m))&&a(s.id,parseInt(m))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(t.Input,{type:"number",value:o,onChange:d,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((h=(l=s.config)==null?void 0:l.rowLimit)==null?void 0:h.toString())||"100",onValueChange:c,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(t.SelectValue,{placeholder:"Select limit"})}),e.jsx(t.SelectContent,{children:Mr.map(u=>e.jsx(t.SelectItem,{value:u.value,children:u.label},u.value))})]})})}function Lr({activeView:s,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:c,onFiltersClick:d,filterCount:l,activeCard:h,columns:u,columnsLoading:m,columnsError:y}){var E;const v=t.useEditorStore(g=>g.card),C=t.useDashboardStore(g=>g.filterValues),{updateCardConfig:p}=t.useEditorActions(),D=t.useEditorStore(g=>g.showAIDialog),{data:f,errorMessage:j,isPending:O,isLoading:I,isFetching:k}=t.useDashboardCardQuery(h);function N(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(v.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(C||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(h.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",u.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:m?"Loading...":y?"Error loading columns":JSON.stringify(u.slice(0,5),null,2)})]})]})})}const S=g=>{if(!v.config)return;if(!g.length){p(v.id,{...v.config,sortByColumns:[]});return}const x=v.config,B=g.map(({id:A,desc:T})=>{var P,V;const b=(P=x.metricColumns)==null?void 0:P.find(z=>z.label===A),M=(V=x.groupByColumns)==null?void 0:V.find(z=>z.label===A),F=b||M;return F?{id:xs("sortBy",F),name:F.name,dataType:F.dataType,label:F.label,qualifiedEntityName:F.qualifiedEntityName,entityId:F.entityId,entityName:F.entityName,entityType:F.entityType,role:"sortby",direction:T?"desc":"asc"}:null}).filter(A=>A!==null);p(v.id,{...x,sortByColumns:B})},w=L.useMemo(()=>{var g,x;return(x=(g=v.config)==null?void 0:g.sortByColumns)==null?void 0:x.map(B=>({id:B.label,desc:B.direction==="desc"}))},[(E=v.config)==null?void 0:E.sortByColumns]);return e.jsxs("div",{className:"flex w-0 grow flex-col",children:[e.jsx(t.ExplorerHeader,{showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:c,onFiltersClick:d,filterCount:l}),n&&N(),e.jsx(t.Separator,{}),e.jsxs("div",{className:"group/visualization flex max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"z-50 flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s==="chart"&&D&&e.jsx(Zt,{variant:"outline"}),e.jsx(Ir,{activeView:s,onViewChange:a}),d&&e.jsxs(t.IconButton,{tooltip:"Card Filters",className:"h-8 gap-1",onClick:d,children:[e.jsx(t.Filter,{className:"h-3.5 w-3.5"}),l>0&&e.jsx("span",{className:"ml-1 rounded-full bg-blue-100 px-1.5 py-0.5 text-xs text-blue-800",children:l})]}),e.jsx("div",{className:"ml-2",children:e.jsx(Ar,{})})]}),e.jsx("div",{className:t.cn("flex grow items-center justify-end"),children:s==="chart"&&e.jsx(es,{})})]}),e.jsxs("div",{className:"flex grow flex-col",children:[s==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:I||k?e.jsx("div",{className:"m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(t.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx(ts,{})}),s==="table"&&(f==null?void 0:f.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:[(I||k)&&e.jsx("div",{className:"absolute flex h-full w-full items-center justify-between",children:e.jsx("div",{className:"z-10 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(t.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}),e.jsx(t.TableVisual,{card:h,data:f==null?void 0:f.records,onSortChange:S,sortState:w})]}),s==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md border bg-background p-4",children:[(f==null?void 0:f.sql)&&e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx($t,{sql:f==null?void 0:f.sql,error:j})]})})]})]})]})}function Or({activeField:s}){const[a,n]=L.useState(!0);return L.useEffect(()=>{s&&n(!0)},[s]),s?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(t.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(cs,{dataType:s.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:s.label||s.name})]}):null}const Br=()=>{const s=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||s.apply(console,r)};const a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var o;if((o=r.reason)!=null&&o.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=s,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Fr(){var z,U;const[s,a]=L.useState("chart"),[n,r]=L.useState(!1),[o,i]=L.useState(!1),c=t.useEditorStore(R=>R.showAIDialog),{setCardType:d}=t.useEditorActions(),l=t.useEditorStore(R=>R.card.type);L.useEffect(()=>Br(),[]);const h=()=>{console.log("Accept clicked - would save/apply current configuration")},u=()=>{console.log("Clear clicked - would reset all configurations")},m=()=>{console.log("Advanced mode toggled")},y=()=>{i(!0)},v=R=>{d(R)},C=t.useEditorStore(R=>R.frame),p=t.useEditorStore(R=>R.card);t.useEditorStore(R=>R.activeTabCardId),t.useEditorStore(R=>R.actions.getAvailableFields);const{addCard:D,removeCard:f,updateCard:j,setActiveCard:O,updateFilters:I}=t.useEditorActions(),{columns:k=[],isLoading:N,error:S}=t.useColumns(),w=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),E=p,{getFieldsForContainer:g,setFieldsForContainer:x}=us(E),{activeField:B,handleDragStart:A,handleDragEnd:T}=Tr({activeCardId:C.activeCardId,sourceFields:k,getFieldsForContainer:g,setFieldsForContainer:x}),b=(R,q)=>{q&&I(R,q)},M=R=>{var q;j(R,{config:{...(q=C.cards.find(H=>H.id===R))==null?void 0:q.config,filters:void 0}})},F=k,P=R=>{if(!R)return 0;let q=R.conditions.length;return R.groups.forEach(H=>{q+=P(H)}),q},V=P(((z=E==null?void 0:E.config)==null?void 0:z.filters)||null);return e.jsxs(t.DndContext,{sensors:w,collisionDetection:t.closestCenter,onDragStart:A,onDragEnd:T,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(nr,{}),!c&&e.jsx(mr,{selectedChart:l,onChartChange:v,groupByFields:g("groupBy"),pivotByFields:g("pivotBy"),metricsFields:g("metrics"),sortByFields:g("sortBy")}),e.jsx(Lr,{selectedChart:l,activeView:s,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:h,onClear:u,onAdvancedToggle:m,onFiltersClick:y,filterCount:V,activeCard:E,dataSourceState:p.dataSource||t.EMPTY_DATA_SOURCE,columns:k,columnsLoading:N,columnsError:S,getFieldsForContainer:g,cards:C.cards,activeCardId:C.activeCardId,addCard:D,setActiveCard:O})]}),E&&e.jsx(Dr,{cardId:E.id,filters:((U=E.config)==null?void 0:U.filters)||null,onFiltersChange:b,onClearFilters:M,availableFields:F,isOpen:o,onOpenChange:i}),e.jsx(t.DragOverlay,{dropAnimation:null,children:e.jsx(Or,{activeField:B||null})})]})}function zr({authToken:s,onSave:a,onClose:n}){const r=L.useRef(null),o=t.useEditorStore(j=>j.showAIDialog),i=t.useEditorStore(j=>j.isDevMode),{setAuthToken:c}=t.useDashboardActions(),{setShowAIDialog:d,setOnSave:l,setOnClose:h}=t.useEditorActions(),{handleDragOver:u,handleDragEnd:m,handleDragStart:y,handleDragCancel:v,sensors:C}=An();L.useEffect(()=>{a&&l(a),n&&h(n)},[a,l,n,h]),L.useEffect(()=>{s&&s.accessToken&&c(s)},[s,c]),L.useEffect(()=>{var j,O;o?((j=r.current)==null||j.resize(40),d(!0)):(d(!1),(O=r.current)==null||O.resize(0))},[o,d]);function p(j){j<1?d(!1):o||d(!0)}function D(){return e.jsxs(e.Fragment,{children:[e.jsx(_t,{type:"main"}),e.jsxs(t.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Ha,{})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(Et,{})})]})]})}function f(){return e.jsxs(t.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Fr,{})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(Et,{})})]})}return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:i?e.jsx(t.DndContext,{sensors:C,onDragStart:y,onDragEnd:m,onDragOver:u,onDragCancel:v,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:D()})}):f()})}function Pr(){t.useDashboardStore(c=>c.selectedCardId);const s=t.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=t.useDashboardStore(c=>c.actions),n=t.useDashboardStore(c=>c.isVisualEditing),r=t.useDashboardStore(c=>c.actions.updateFrame);function o(c){s&&(r(s,c),a(!1))}function i(){a(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex grow",{"max-h-0 overflow-hidden":!n}),children:e.jsx(zr,{onSave:o,onClose:i})})}function Rr(){const s=t.useEditorStore(i=>i.selectedDatabaseName),a=t.useEditorStore(i=>i.selectedTableName),n=t.useDashboardStore(i=>i.dashboard.filters)||[],{columns:r}=t.useEditorAside(),{assignFilter:o}=rs();return e.jsx(t.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(i=>{const c=n==null?void 0:n.find(d=>d.column===t.fmt(i.column_name)&&d.table===a&&d.database===s);return e.jsx("div",{onClick:()=>o(i),className:t.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rt,{column:i}),e.jsx("span",{children:i.column_name})]})},i.column_name)})})}function Vr(){t.useDashboardStore(a=>a.showFilters);const s=t.useDashboardStore(a=>a.actions.setShowFilters);return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(t.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(t.Button,{onClick:()=>s(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(t.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:e.jsx(_t,{type:"filter",ColumnsComponent:()=>e.jsx(Rr,{})})})]})}function qr(){const s=t.useDashboardStore(r=>r.dashboard.filters),a=t.useDashboardStore(r=>r.theme),n=s==null?void 0:s.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:t.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(t.FilterHeader,{filter:r}),e.jsx(t.FilterComponent,{filter:r})]},r.id))}):null}function _r(){const s=t.useDashboardStore(r=>r.showFilters),a=t.useDashboardStore(r=>r.isVisualEditing),n=t.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:t.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(qr,{}),e.jsx(t.DashboardTabs,{})]}),s&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Vr,{})})]})}function Gr(){const s=t.useDashboardStore(o=>o.dashboard),a=t.useDashboardStore(o=>o.actions.setDashboard),n=t.useDashboardStore(o=>o.showDashboardJSON),r=t.useDashboardStore(o=>o.actions.setShowDashboardJSON);return e.jsxs("div",{className:t.cn("relative p-2",{hidden:!n}),children:[e.jsxs(t.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(t.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(t.de,{onChange:o=>{if(o)try{JSON.parse(o),a(JSON.parse(o))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(s,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function $r({showControls:s=!1,showFooter:a=!0,...n}){return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:e.jsxs(t.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(t.$e,{}),e.jsxs(t.UXProvider,{children:[e.jsx(Gr,{}),e.jsxs(t.DashboardPanel,{...n,children:[s&&e.jsx(En,{}),e.jsx(Pr,{}),e.jsx(_r,{})]})]})]})})}exports.DashboardPlus=$r;exports.ScheduleDashboard=Vt;exports.SelectComponent=ye;exports.cleanCard=zt;exports.downloadPdf=Rt;exports.getDashbaordStateWithoutData=at;