react-semaphor 0.1.140 → 0.1.142

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.
Files changed (28) hide show
  1. package/dist/chunks/{dashboard-controls-DCdXE-1I.js → dashboard-controls-BMLlOkS9.js} +3 -3
  2. package/dist/chunks/{dashboard-controls-ZLM2lY1W.js → dashboard-controls-BdQcYRkf.js} +1 -1
  3. package/dist/chunks/{dashboard-export-dialog-DtrfJ9Js.js → dashboard-export-dialog-BpNaUA5x.js} +1 -1
  4. package/dist/chunks/{dashboard-export-dialog-BDIPA0iP.js → dashboard-export-dialog-CbMcLZvW.js} +3 -3
  5. package/dist/chunks/{dashboard-json-C5mUnJ_6.js → dashboard-json-DD-d9gYu.js} +1 -1
  6. package/dist/chunks/{dashboard-json-CjX2S2P5.js → dashboard-json-DgQozDAv.js} +1 -1
  7. package/dist/chunks/{edit-dashboard-visual-Drzczr6I.js → edit-dashboard-visual-CR3NqJ7m.js} +10 -10
  8. package/dist/chunks/{edit-dashboard-visual-BEAVr2Mh.js → edit-dashboard-visual-CRMhXxdG.js} +2122 -2074
  9. package/dist/chunks/{editor-action-buttons-DgFLwd7e.js → editor-action-buttons-CNQtSzD5.js} +2 -2
  10. package/dist/chunks/{editor-action-buttons-5G0hV-FE.js → editor-action-buttons-DYrSZQhJ.js} +1 -1
  11. package/dist/chunks/{index-COVj17uo.js → index-CReqnEJI.js} +136 -136
  12. package/dist/chunks/{index-CnzyKX5P.js → index-QdSI9E0a.js} +10769 -10626
  13. package/dist/chunks/{resource-management-panel-4U6ulEyR.js → resource-management-panel-CBXn6QHi.js} +2 -2
  14. package/dist/chunks/{resource-management-panel-CBeNy1ff.js → resource-management-panel-CXSx9QhW.js} +1 -1
  15. package/dist/chunks/{use-visual-utils-Cyhtukxh.js → use-visual-utils-BDuNB0Iz.js} +1 -1
  16. package/dist/chunks/{use-visual-utils-C2iWEneY.js → use-visual-utils-BnCl386t.js} +1 -1
  17. package/dist/dashboard/index.cjs +1 -1
  18. package/dist/dashboard/index.js +1 -1
  19. package/dist/index.cjs +1 -1
  20. package/dist/index.js +4 -4
  21. package/dist/style.css +1 -1
  22. package/dist/surfboard/index.cjs +1 -1
  23. package/dist/surfboard/index.js +1 -1
  24. package/dist/types/dashboard.d.ts +14 -0
  25. package/dist/types/main.d.ts +14 -0
  26. package/dist/types/surfboard.d.ts +14 -0
  27. package/dist/types/types.d.ts +14 -0
  28. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),s=require("./index-COVj17uo.js"),D=require("react"),_e=require("./editor-action-buttons-5G0hV-FE.js"),nt=require("react-dom"),at=require("./use-visual-utils-Cyhtukxh.js"),rt=require("./use-click-outside-B9T3lmcw.js");function lt(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>t[a]})}}return n.default=t,Object.freeze(n)}const qe=lt(D);/**
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),s=require("./index-CReqnEJI.js"),D=require("react"),_e=require("./editor-action-buttons-DYrSZQhJ.js"),nt=require("react-dom"),at=require("./use-visual-utils-BDuNB0Iz.js"),rt=require("./use-click-outside-B9T3lmcw.js");function lt(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>t[a]})}}return n.default=t,Object.freeze(n)}const qe=lt(D);/**
2
2
  * @license lucide-react v0.453.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -173,13 +173,13 @@
173
173
  *
174
174
  * This source code is licensed under the ISC license.
175
175
  * See the LICENSE file in the root directory of this source tree.
176
- */const Dt=s.createLucideIcon("Wand",[["path",{d:"M15 4V2",key:"z1p9b7"}],["path",{d:"M15 16v-2",key:"px0unx"}],["path",{d:"M8 9h2",key:"1g203m"}],["path",{d:"M20 9h2",key:"19tzq7"}],["path",{d:"M17.8 11.8 19 13",key:"yihg8r"}],["path",{d:"M15 9h.01",key:"x1ddxp"}],["path",{d:"M17.8 6.2 19 5",key:"fd4us0"}],["path",{d:"m3 21 9-9",key:"1jfql5"}],["path",{d:"M12.2 6.2 11 5",key:"i3da3b"}]]);function Mt({initialJoinPlan:t,availableDataSources:n}){const[a,r]=D.useState(t),[o,d]=D.useState(new Set),i=()=>{const N=a.joins.length>0?Math.max(...a.joins.map(j=>j.sequence))+1:1,p={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({...a,joins:[...a.joins,p]}),d(new Set([...o,p.id]))},c=N=>{r({...a,joins:a.joins.filter(p=>p.id!==N)}),d(new Set([...o].filter(p=>p!==N)))},l=(N,p)=>{var b,I,F,T,L;const j=a.joins.find(w=>w.id===N);if(!j)return;const S={...j,...p};if((b=S.source)!=null&&b.name&&((I=S.target)!=null&&I.name)&&S.source.name===S.target.name){s.ue.error("Self-joins are not yet supported",{description:`Joining ${S.source.name} to itself is not currently supported. Please select a different target table.`});return}const M=a.joins.filter(w=>{var R;return w.id!==N&&w.target.name===((R=S.target)==null?void 0:R.name)});if((F=S.target)!=null&&F.name&&M.length>0){s.ue.error("Duplicate join targets are not supported",{description:`The table ${S.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const y=a.joins.map(w=>w.id===N?S:w);if((T=S.source)!=null&&T.name&&((L=S.target)!=null&&L.name)&&S.joinKeyGroups[0].keys.length===0){const w=n.find(G=>{var q;return G.name===((q=S.source)==null?void 0:q.name)}),R=n.find(G=>{var q;return G.name===((q=S.target)==null?void 0:q.name)}),K={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(w==null?void 0:w.name)||"",entityName:(w==null?void 0:w.name)||"",entityType:(w==null?void 0:w.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(R==null?void 0:R.name)||"",entityName:(R==null?void 0:R.name)||"",entityType:(R==null?void 0:R.type)||"table"},operator:"="},_=[...S.joinKeyGroups];_[0]={..._[0],keys:[K]},S.joinKeyGroups=_,y[y.findIndex(G=>G.id===N)]=S}r({...a,joins:y})};return{joinPlan:a,expandedJoins:o,setJoinPlan:r,addJoin:i,removeJoin:c,updateJoin:l,moveJoinUp:N=>{const p=a.joins.findIndex(j=>j.id===N);if(p>0){const j=[...a.joins],S={...j[p]},M={...j[p-1]};j[p]=M,j[p-1]=S,j.forEach((b,I)=>{b.sequence=I+1});const y={...a,joins:j};r(y)}},moveJoinDown:N=>{const p=a.joins.findIndex(j=>j.id===N);if(p<a.joins.length-1){const j=[...a.joins],S={...j[p]},M={...j[p+1]};j[p]=M,j[p+1]=S,j.forEach((b,I)=>{b.sequence=I+1});const y={...a,joins:j};r(y)}},toggleJoinExpansion:N=>{const p=new Set(o);p.has(N)?p.delete(N):p.add(N),d(p)},getAvailableSourceEntities:N=>{if(a.joins.length===0)return n;const p=a.joins.findIndex(S=>S.id===N);if(p===0)return n.filter(S=>S.name===a.baseEntity.name);const j=new Set;return a.baseEntity.name&&j.add(a.baseEntity.name),a.joins.slice(0,p).forEach(S=>{j.add(S.source.name),j.add(S.target.name)}),n.filter(S=>j.has(S.name))},getAvailableTargetEntities:N=>n.filter(p=>p.name!==N),addJoinKeyGroup:N=>{const p=a.joins.find(S=>S.id===N);if(!p)return;const j=[...p.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];l(N,{joinKeyGroups:j})},updateGroupOperator:(N,p,j)=>{const S=a.joins.find(y=>y.id===N);if(!S)return;const M=[...S.joinKeyGroups];M[p]={...M[p],operator:j},l(N,{joinKeyGroups:M})},removeJoinKeyGroup:(N,p)=>{const j=a.joins.find(M=>M.id===N);if(!j)return;const S=[...j.joinKeyGroups];S.splice(p,1),l(N,{joinKeyGroups:S})},addJoinKey:(N,p)=>{const j=a.joins.find(I=>I.id===N);if(!j)return;const S=n.find(I=>I.name===j.source.name),M=n.find(I=>I.name===j.target.name),y=[...j.joinKeyGroups],b={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(S==null?void 0:S.name)||"",entityName:(S==null?void 0:S.name)||"",entityType:(S==null?void 0:S.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(M==null?void 0:M.name)||"",entityName:(M==null?void 0:M.name)||"",entityType:(M==null?void 0:M.type)||"table"},operator:"="};y[p]={...y[p],keys:[...y[p].keys,b]},l(N,{joinKeyGroups:y})},updateJoinKey:(N,p,j,S,M)=>{const y=a.joins.find(L=>L.id===N);if(!y)return;const b=n.find(L=>L.name===y.source.name),I=n.find(L=>L.name===y.target.name),F=[...y.joinKeyGroups],T=F[p].keys[j];S==="sourceColumnName"&&b?F[p].keys[j]={...T,source:{...T.source,name:M}}:S==="targetColumnName"&&I?F[p].keys[j]={...T,target:{...T.target,name:M}}:S==="operator"&&(F[p].keys[j]={...T,operator:M}),l(N,{joinKeyGroups:F})},removeJoinKey:(N,p,j)=>{const S=a.joins.find(y=>y.id===N);if(!S)return;const M=[...S.joinKeyGroups];M[p].keys.splice(j,1),l(N,{joinKeyGroups:M})},generateSQLPreview:()=>{const N=[...a.joins].sort((S,M)=>S.sequence-M.sequence),p=a.baseEntity;if(!p.name)return"SELECT * FROM table -- Please select a base entity";let j=`SELECT *
177
- FROM ${p.name}`;return N.forEach(S=>{const M=n.find(I=>I.name===S.target.name);if(!M)return;const y=S.joinKeyGroups.filter(I=>I.keys&&I.keys.length>0).map(I=>{const F=I.keys.filter(T=>{var L,w,R,K;return((L=T.source)==null?void 0:L.name)&&((w=T.target)==null?void 0:w.name)&&((R=T.source)==null?void 0:R.entityName)&&((K=T.target)==null?void 0:K.entityName)}).map(T=>`${T.source.entityName}.${T.source.name} ${T.operator} ${T.target.entityName}.${T.target.name}`);return F.length>1?`(${F.join(` ${I.operator} `)})`:F[0]}).filter(Boolean),b=y.length>1?y.join(" OR "):y[0]||"condition_here";j+=`
176
+ */const Dt=s.createLucideIcon("Wand",[["path",{d:"M15 4V2",key:"z1p9b7"}],["path",{d:"M15 16v-2",key:"px0unx"}],["path",{d:"M8 9h2",key:"1g203m"}],["path",{d:"M20 9h2",key:"19tzq7"}],["path",{d:"M17.8 11.8 19 13",key:"yihg8r"}],["path",{d:"M15 9h.01",key:"x1ddxp"}],["path",{d:"M17.8 6.2 19 5",key:"fd4us0"}],["path",{d:"m3 21 9-9",key:"1jfql5"}],["path",{d:"M12.2 6.2 11 5",key:"i3da3b"}]]);function Mt({initialJoinPlan:t,availableDataSources:n}){const[a,r]=D.useState(t),[l,d]=D.useState(new Set),i=()=>{const N=a.joins.length>0?Math.max(...a.joins.map(j=>j.sequence))+1:1,f={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({...a,joins:[...a.joins,f]}),d(new Set([...l,f.id]))},c=N=>{r({...a,joins:a.joins.filter(f=>f.id!==N)}),d(new Set([...l].filter(f=>f!==N)))},o=(N,f)=>{var b,I,F,T,L;const j=a.joins.find(k=>k.id===N);if(!j)return;const S={...j,...f};if((b=S.source)!=null&&b.name&&((I=S.target)!=null&&I.name)&&S.source.name===S.target.name){s.ue.error("Self-joins are not yet supported",{description:`Joining ${S.source.name} to itself is not currently supported. Please select a different target table.`});return}const M=a.joins.filter(k=>{var R;return k.id!==N&&k.target.name===((R=S.target)==null?void 0:R.name)});if((F=S.target)!=null&&F.name&&M.length>0){s.ue.error("Duplicate join targets are not supported",{description:`The table ${S.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const y=a.joins.map(k=>k.id===N?S:k);if((T=S.source)!=null&&T.name&&((L=S.target)!=null&&L.name)&&S.joinKeyGroups[0].keys.length===0){const k=n.find(G=>{var q;return G.name===((q=S.source)==null?void 0:q.name)}),R=n.find(G=>{var q;return G.name===((q=S.target)==null?void 0:q.name)}),K={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(k==null?void 0:k.name)||"",entityName:(k==null?void 0:k.name)||"",entityType:(k==null?void 0:k.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(R==null?void 0:R.name)||"",entityName:(R==null?void 0:R.name)||"",entityType:(R==null?void 0:R.type)||"table"},operator:"="},_=[...S.joinKeyGroups];_[0]={..._[0],keys:[K]},S.joinKeyGroups=_,y[y.findIndex(G=>G.id===N)]=S}r({...a,joins:y})};return{joinPlan:a,expandedJoins:l,setJoinPlan:r,addJoin:i,removeJoin:c,updateJoin:o,moveJoinUp:N=>{const f=a.joins.findIndex(j=>j.id===N);if(f>0){const j=[...a.joins],S={...j[f]},M={...j[f-1]};j[f]=M,j[f-1]=S,j.forEach((b,I)=>{b.sequence=I+1});const y={...a,joins:j};r(y)}},moveJoinDown:N=>{const f=a.joins.findIndex(j=>j.id===N);if(f<a.joins.length-1){const j=[...a.joins],S={...j[f]},M={...j[f+1]};j[f]=M,j[f+1]=S,j.forEach((b,I)=>{b.sequence=I+1});const y={...a,joins:j};r(y)}},toggleJoinExpansion:N=>{const f=new Set(l);f.has(N)?f.delete(N):f.add(N),d(f)},getAvailableSourceEntities:N=>{if(a.joins.length===0)return n;const f=a.joins.findIndex(S=>S.id===N);if(f===0)return n.filter(S=>S.name===a.baseEntity.name);const j=new Set;return a.baseEntity.name&&j.add(a.baseEntity.name),a.joins.slice(0,f).forEach(S=>{j.add(S.source.name),j.add(S.target.name)}),n.filter(S=>j.has(S.name))},getAvailableTargetEntities:N=>n.filter(f=>f.name!==N),addJoinKeyGroup:N=>{const f=a.joins.find(S=>S.id===N);if(!f)return;const j=[...f.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];o(N,{joinKeyGroups:j})},updateGroupOperator:(N,f,j)=>{const S=a.joins.find(y=>y.id===N);if(!S)return;const M=[...S.joinKeyGroups];M[f]={...M[f],operator:j},o(N,{joinKeyGroups:M})},removeJoinKeyGroup:(N,f)=>{const j=a.joins.find(M=>M.id===N);if(!j)return;const S=[...j.joinKeyGroups];S.splice(f,1),o(N,{joinKeyGroups:S})},addJoinKey:(N,f)=>{const j=a.joins.find(I=>I.id===N);if(!j)return;const S=n.find(I=>I.name===j.source.name),M=n.find(I=>I.name===j.target.name),y=[...j.joinKeyGroups],b={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(S==null?void 0:S.name)||"",entityName:(S==null?void 0:S.name)||"",entityType:(S==null?void 0:S.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(M==null?void 0:M.name)||"",entityName:(M==null?void 0:M.name)||"",entityType:(M==null?void 0:M.type)||"table"},operator:"="};y[f]={...y[f],keys:[...y[f].keys,b]},o(N,{joinKeyGroups:y})},updateJoinKey:(N,f,j,S,M)=>{const y=a.joins.find(L=>L.id===N);if(!y)return;const b=n.find(L=>L.name===y.source.name),I=n.find(L=>L.name===y.target.name),F=[...y.joinKeyGroups],T=F[f].keys[j];S==="sourceColumnName"&&b?F[f].keys[j]={...T,source:{...T.source,name:M}}:S==="targetColumnName"&&I?F[f].keys[j]={...T,target:{...T.target,name:M}}:S==="operator"&&(F[f].keys[j]={...T,operator:M}),o(N,{joinKeyGroups:F})},removeJoinKey:(N,f,j)=>{const S=a.joins.find(y=>y.id===N);if(!S)return;const M=[...S.joinKeyGroups];M[f].keys.splice(j,1),o(N,{joinKeyGroups:M})},generateSQLPreview:()=>{const N=[...a.joins].sort((S,M)=>S.sequence-M.sequence),f=a.baseEntity;if(!f.name)return"SELECT * FROM table -- Please select a base entity";let j=`SELECT *
177
+ FROM ${f.name}`;return N.forEach(S=>{const M=n.find(I=>I.name===S.target.name);if(!M)return;const y=S.joinKeyGroups.filter(I=>I.keys&&I.keys.length>0).map(I=>{const F=I.keys.filter(T=>{var L,k,R,K;return((L=T.source)==null?void 0:L.name)&&((k=T.target)==null?void 0:k.name)&&((R=T.source)==null?void 0:R.entityName)&&((K=T.target)==null?void 0:K.entityName)}).map(T=>`${T.source.entityName}.${T.source.name} ${T.operator} ${T.target.entityName}.${T.target.name}`);return F.length>1?`(${F.join(` ${I.operator} `)})`:F[0]}).filter(Boolean),b=y.length>1?y.join(" OR "):y[0]||"condition_here";j+=`
178
178
  ${S.joinType} JOIN ${M.name}
179
- ON ${b}`}),j},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(S=>!S.source.name||!S.target.name)||a.joins.some(S=>S.joinKeyGroups.some(M=>M.keys.length===0))||a.joins.some(S=>S.joinKeyGroups.some(M=>M.keys.some(y=>!y.source.name||!y.target.name||!y.operator))))}}function Lt({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:o}){const{setCardConfig:d}=s.useEditorActions();s.useEditorStore(y=>y.card.config);const{columnGroups:i}=s.useColumns(),{joinPlan:c,expandedJoins:l,setJoinPlan:u,addJoin:x,removeJoin:h,updateJoin:g,moveJoinUp:k,moveJoinDown:m,toggleJoinExpansion:f,getAvailableSourceEntities:v,getAvailableTargetEntities:C,addJoinKeyGroup:A,updateGroupOperator:B,removeJoinKeyGroup:O,addJoinKey:E,updateJoinKey:N,removeJoinKey:p,generateSQLPreview:j,isValidConfiguration:S}=Mt({initialJoinPlan:t,availableDataSources:n}),M=y=>{const b=i.find(I=>I.entityName===y);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(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:c.baseEntity.name,onValueChange:y=>{const b=n.find(I=>I.name===y);u({...c,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:y,database:b==null?void 0:b.database,schema:b==null?void 0:b.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:n.map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},y.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:j()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",c.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:x,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),c.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:c.joins.map(y=>{const b=n.find(T=>T.name===y.source.name),I=n.find(T=>T.name===y.target.name),F=l.has(y.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.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(s.Badge,{children:y.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",y.sequence,b&&I&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",b.name," → ",I.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>k(y.id),disabled:y.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>m(y.id),disabled:y.sequence===c.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>f(y.id),children:F?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(y.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),F&&e.jsxs(s.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(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:y.source.name,onValueChange:T=>{const L=n.find(w=>w.name===T);g(y.id,{source:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:T,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:v(y.id).map(T=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:T.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:T.type}),T.name]})},T.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:y.joinType,onValueChange:T=>g(y.id,{joinType:T}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:y.target.name,onValueChange:T=>{const L=n.find(w=>w.name===T);g(y.id,{target:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:T,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},disabled:!y.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:y.source.name?C(y.source.name).map(T=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:T.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:T.type}),T.name,T.name===y.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},T.name)):[]})]})]})]}),y.source.name&&y.target.name&&b&&I&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>A(y.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),y.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:y.joinKeyGroups.map((T,L)=>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(s.Label,{children:["Group ",L+1]}),L>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.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(s.Select,{value:T.operator,onValueChange:w=>B(y.id,L,w),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>O(y.id,L),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[T.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:T.keys.map((w,R)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[R>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:T.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:w.source.name,onValueChange:K=>N(y.id,L,R,"sourceColumnName",K),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:M(y.source.name).map(K=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:K.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:K.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:K.dataType})]})},K.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:w.operator,onValueChange:K=>N(y.id,L,R,"operator",K),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:w.target.name,onValueChange:K=>N(y.id,L,R,"targetColumnName",K),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:M(y.target.name).map(K=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:K.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:K.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:K.dataType})]})},K.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>p(y.id,L,R),children:e.jsx(s.X,{className:"size-3.5"})})]},w.id||R))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>E(y.id,L),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},T.id))})]})]})]},y.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),o()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:o,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>a(c),disabled:!S(),children:"Save"})]})]})}function Ts({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:o,onRemove:d,onSave:i,onCancel:c}){return e.jsxs(s.Dialog,{open:n,onOpenChange:a,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(Lt,{joinPlan:r,availableDataSources:o,onSave:i,onCancel:c,onRemove:d})]}),t]})}function Ft({joins:t,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"max-h-[400px] divide-y divide-border overflow-y-auto",children:[t.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=[...t].sort((i,c)=>i.sequence-c.sequence),d=a.find(i=>i.name===n);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(s.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}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),o.map(i=>{const c=a.find(l=>l.name===i.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(s.Badge,{variant:"outline",className:"text-xs",children:i.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(s.Badge,{variant:"secondary",className:"text-xs",children:c==null?void 0:c.type}),e.jsx("span",{className:"text-xs font-medium",children:c==null?void 0:c.name})]})]},i.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((o,d)=>o.sequence-d.sequence).map((o,d)=>{const i=a.find(u=>u.name===o.source.name),c=a.find(u=>u.name===o.target.name),l=o.joinKeyGroups.reduce((u,x)=>u+x.keys.length,0);return e.jsxs("div",{className:"rounded-md bg-muted p-2 text-left",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:d+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:o.joinType}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto shrink-0 text-xs",children:[l," condition",l>1?"s":""]})]}),e.jsxs("div",{className:"mt-1 truncate pl-1 text-xs text-muted-foreground",children:[i==null?void 0:i.name," → ",c==null?void 0:c.name]})]},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 rs({open:t,onOpenChange:n,variant:a="button"}={}){var A,B;const r=s.useEditorStore(O=>O.card),{autoJoinMetadata:o}=s.useDashboardCardQuery(r),d=s.useEditorStore(O=>O.actions.updateCardConfig),i=((A=r==null?void 0:r.config)==null?void 0:A.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[c,l]=D.useState(!1),u=t!==void 0,x=u?t:c,h=u?n:l,g=((B=r==null?void 0:r.dataSource)==null?void 0:B.selectedEntities)||[],k=O=>{d(r.id,{...r==null?void 0:r.config,joinPlan:O}),h(!1)},m=()=>{d(r.id,{...r==null?void 0:r.config,joinPlan:void 0})},f=()=>{h(!1)},v=()=>{const O=[...i.joins].sort((p,j)=>p.sequence-j.sequence),E=i.baseEntity;if(!E.name)return"SELECT * FROM table -- Please select a base entity";let N=`SELECT *
180
- FROM ${E.name}`;return O.forEach(p=>{const j=g.find(y=>y.name===p.target.name);if(!j)return;const S=p.joinKeyGroups.filter(y=>y.keys&&y.keys.length>0).map(y=>{const b=y.keys.filter(I=>{var F,T,L,w;return((F=I.source)==null?void 0:F.name)&&((T=I.target)==null?void 0:T.name)&&((L=I.source)==null?void 0:L.entityName)&&((w=I.target)==null?void 0:w.entityName)}).map(I=>`${I.source.entityName}.${I.source.name} ${I.operator} ${I.target.entityName}.${I.target.name}`);return b.length>1?`(${b.join(` ${y.operator} `)})`:b[0]}).filter(Boolean),M=S.length>1?S.join(" OR "):S[0]||"condition_here";N+=`
181
- ${p.joinType} JOIN ${j.name}
182
- ON ${M}`}),N};if(g.length<2)return null;const C=i.joins.length>0&&e.jsx(s.TooltipContent,{side:"bottom",className:"ml-4 max-w-md overflow-hidden p-0",children:e.jsx(Ft,{joins:i.joins,baseEntityId:i.baseEntity.name,availableDataSources:g,generateSQLPreview:v})});return e.jsxs(e.Fragment,{children:[e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:a==="badge"?e.jsxs(s.Badge,{variant:"secondary",className:"h-5 cursor-pointer gap-1 px-1.5 text-xs transition-colors hover:bg-secondary/80",onClick:O=>{O.stopPropagation(),h(!0)},children:[e.jsx(s.Link,{className:"h-3 w-3"}),i.joins.length]}):e.jsxs(s.Button,{onClick:()=>h(!0),variant:"outline",className:"w-full bg-muted/50",children:[e.jsx(s.Link,{className:"mr-2 h-3.5 w-3.5"}),i.joins.length===0?"Configure Joins":i.joins.length===1?"Join":"Joins",i.joins.length>0&&e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1.5 text-xs font-medium text-primary-foreground",children:i.joins.length}),(o==null?void 0:o.autoResolved)&&e.jsxs(s.Badge,{variant:"secondary",className:"ml-2 h-5 gap-1 bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:[e.jsx(s.Sparkles,{className:"h-3 w-3"}),"Auto"]})]})}),C]})}),e.jsx(Ts,{open:x,onOpenChange:h,joinPlan:i,availableDataSources:g,onSave:k,onCancel:f,onRemove:m,children:e.jsx("div",{})})]})}function Bt({open:t,onOpenChange:n}){const[a,r]=D.useState([]),{updateDataSource:o}=s.useEditorActions(),d=s.useDashboardStore(m=>m.dashboard.aiContext),i=(d==null?void 0:d.selectedEntities)||[];D.useEffect(()=>{t&&r([])},[t]);const c=m=>{r(f=>f.some(C=>C.name===m.name&&C.type===m.type)?f.filter(C=>!(C.name===m.name&&C.type===m.type)):[...f,m])},l=()=>{r([...i])},u=()=>{r([])},x=()=>{if(a.length===0)return;const m=a[0],f=m.connectionId||"",v=m.connectionType||"",A=a.some(O=>O.type==="dataset")?"semanticDomain":"database";o({connectionId:f,connectionType:v,mode:A,selectedEntities:a}),n(!1)},h=m=>"label"in m&&m.label?m.label:m.name,g=m=>{if("description"in m&&m.description)return m.description;const f=[];return m.database&&f.push(m.database),m.schema&&f.push(m.schema),m.name&&f.push(m.name),f.join(".")},k=m=>a.some(f=>f.name===m.name&&f.type===m.type);return i.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>n(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:l,disabled:a.length===i.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[a.length," of ",i.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:i.map((m,f)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",k(m)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:k(m),onCheckedChange:()=>c(m)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:s.getEntityIcon(m.type)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:h(m)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:g(m)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:m.type})]},`${m.type}-${m.name}-${f}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:x,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function ls({entities:t,title:n}){const{isConsoleMode:a}=s.useDashboardPreferences();return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:n??`${t.length} more entities`}),e.jsx("div",{className:"space-y-1",children:t.map((r,o)=>{const d=s.getEntityDetails(r),i=d.find(l=>l.label==="Description"&&l.value),c=d.filter(l=>l.label==="Description"?!1:a?!0:!["Connection","Database","Schema"].includes(l.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(r)}),i&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:i.value})]}),c.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:c.map((l,u)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[l.label,":"]}),e.jsx("span",{className:"font-mono",children:l.value})]},u))})]},`remaining-${r.type}-${r.name}-${o}`)})})]})})}function Ve(t,n){const[a,r]=D.useState(()=>{const o=localStorage.getItem(t);return o?JSON.parse(o):n});return D.useEffect(()=>{localStorage.setItem(t,JSON.stringify(a))},[a,t]),[a,r]}function Es({isVisible:t}){var f,v;const n=s.useEditorStore(C=>C.isDevMode);s.useSyncLegacyEditorState();const[a,r]=D.useState(!1),[o,d]=D.useState(!1),[i,c]=Ve("semaphor:data-source-collapsed",!1),l=s.useEditorStore(C=>C.card.dataSource),u=s.useEditorStore(C=>{var A,B;return(B=(A=C.card)==null?void 0:A.config)==null?void 0:B.joinPlan}),{updateDataSource:x}=s.useEditorActions(),h=((f=l==null?void 0:l.selectedEntities)==null?void 0:f.length)||0,g=((v=u==null?void 0:u.joins)==null?void 0:v.length)||0,m={...{connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},...l,selectedEntities:(l==null?void 0:l.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[h===0&&g===0?e.jsx("div",{className:"p-4 px-6",children:e.jsxs(s.Button,{className:"w-full bg-muted/50",variant:"outline",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),"Choose Dataset"]})}):e.jsxs("div",{children:[e.jsxs("div",{className:s.cn("flex cursor-pointer items-center justify-between px-6 pt-3",!i&&"pb-3"),onClick:()=>c(!i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Data Source"}),i&&e.jsxs("div",{className:"flex items-center gap-1.5",onClick:C=>C.stopPropagation(),children:[h>0&&e.jsx(s.TooltipProvider,{delayDuration:100,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"h-5 cursor-pointer gap-1 px-1.5 text-xs transition-colors hover:bg-secondary/80",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"h-3 w-3"}),h]})}),e.jsx(ls,{entities:m.selectedEntities,title:`${h} selected ${h===1?"entity":"entities"}`})]})}),g>0&&!n&&e.jsx(rs,{variant:"badge"})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:C=>{C.stopPropagation(),c(!i)},children:i?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:s.cn("overflow-hidden transition-all duration-200 ease-in-out",i?"max-h-0 opacity-0":"max-h-96 opacity-100"),children:[e.jsx("div",{className:"px-6 pb-2",children:e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"w-full bg-muted/50",variant:"outline",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),h===1?"Dataset":"Datasets",e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1.5 text-xs font-medium text-primary-foreground",children:h})]})}),e.jsx(ls,{entities:m.selectedEntities,title:`${h} selected ${h===1?"entity":"entities"}`})]})})}),!n&&e.jsx("div",{className:"px-6 pb-2",children:e.jsx(rs,{})})]})]}),e.jsx(s.FieldsSection,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(l==null?void 0:l.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:m}),e.jsx(Bt,{open:o,onOpenChange:d})]})}function Je({error:t,errorSql:n,onSendFeedback:a,onOpenInEditor:r,className:o,showFeedbackButton:d=!0,errorTitle:i="Query Error"}){const[c,l]=D.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-destructive/30 bg-destructive/5 p-4",o),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(s.CircleAlert,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-destructive"}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:i}),e.jsxs("div",{className:"relative rounded-md bg-background/60 p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 h-6 w-6 z-10"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"font-mono text-xs text-foreground/80 break-all",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n&&e.jsx(s.Collapsible,{open:c,onOpenChange:l,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:c?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),r&&n&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:r,children:[e.jsx(ws,{className:"mr-1.5 h-3.5 w-3.5"}),"Open in Editor"]}),d&&a&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:a,children:[e.jsx(s.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),n&&e.jsx(s.Collapsible,{open:c,onOpenChange:l,children:e.jsx(s.CollapsibleContent,{className:"space-y-2",children:e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Error SQL Query"}),e.jsx(s.CopyButton,{text:n,className:"h-6 w-6"})]}),e.jsx("div",{className:"rounded-md bg-background/60 p-2 max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:n,language:"sql"})})]})})})]})]})})}function As({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){const o=s.useEditorStore(f=>f.isDevMode),{setIsDevMode:d,setCardSql:i,setRunSql:c}=s.useEditorActions(),[l,u]=D.useState(!1),x=s.useEditorStore(f=>f.card),h=s.useEditorStore(f=>f.frame),g=s.useDashboardStore(f=>f.selectedSheetId),k=s.useDashboardStore(f=>{var v;return(v=f.dashboard)==null?void 0:v.id});function m(f){d(!0),i(f||t),setTimeout(()=>{c(!0)},100)}return e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col pt-4",children:[!o&&t&&!n&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsxs(s.Button,{onClick:()=>m(),variant:"secondary",size:"sm",children:[e.jsx(ws,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),e.jsxs(s.Button,{onClick:()=>u(!l),variant:"outline",size:"sm",children:[e.jsx(s.Info,{className:"mr-2 h-4 w-4"}),"Card Details"]})]}),l&&e.jsx("div",{className:"mb-3 rounded-lg border border-border bg-muted/30 p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Card Information"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>u(!1),children:e.jsx(Cs,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID"}),e.jsx("code",{className:"text-xs font-mono",children:x.id||"N/A"})]}),e.jsx(s.CopyButton,{text:x.id||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Frame ID"}),e.jsx("code",{className:"text-xs font-mono",children:h.id||"N/A"})]}),e.jsx(s.CopyButton,{text:h.id||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Sheet ID"}),e.jsx("code",{className:"text-xs font-mono",children:g||"N/A"})]}),e.jsx(s.CopyButton,{text:g||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Dashboard ID"}),e.jsx("code",{className:"text-xs font-mono",children:k||"N/A"})]}),e.jsx(s.CopyButton,{text:k||"",className:"h-6 w-6"})]})]})]})}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-auto text-xs leading-relaxed text-foreground/80",children:[n&&e.jsx(Je,{error:n,errorSql:a,showFeedbackButton:!1,onOpenInEditor:()=>m(a)}),!n&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute right-2 top-2 z-10",children:e.jsx(s.CopyButton,{text:t,className:"h-6 w-6"})}),e.jsx(s.CodeHighlighter,{code:t,language:"sql"})]})})]}),n&&r&&e.jsx("div",{className:"mt-3",children:e.jsxs(s.Button,{onClick:r,size:"sm",variant:"outline",children:[e.jsx(ft,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})})]})}function Ot({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:n?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:n?e.jsx(Cs,{className:"h-4 w-4 text-red-500"}):e.jsx(s.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(s.HoverCardContent,{align:"start",className:"flex w-[700px]",children:e.jsx(As,{errorSql:a,sql:t,error:n,onDebugWithAssistant:r})})]})}function Rt(t){return s.GenIcon({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(t)}function Is(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(f=>f.theme),r=s.useEditorStore(f=>f.frame),o=s.useEditorStore(f=>f.card),d=s.useEditorStore(f=>f.activeTabCardId),i=s.Le(),{refetch:c}=s.useDashboardCardQuery(o),{updateCardTab:l,setRunSql:u}=s.useEditorActions(),x=D.useRef(),h=D.useRef({}),g=r.cards.find(f=>f.id===d),k=D.useCallback(()=>{let f="";return t==="python"&&(f=(g==null?void 0:g.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(f=(g==null?void 0:g.sql)||""),f},[t,g]);D.useEffect(()=>{if(d&&o.id&&o.id!==d){if(x.current&&i){const f=x.current.getModel();f&&(h.current[o.id]=f);let v=h.current[d];if(!v){const C=k();v=i.editor.createModel(C,t),h.current[d]=v}x.current.setModel(v)}l(d,o),u(!0)}},[d,o,l,i,u,t,k]),D.useEffect(()=>{if(!i)return;const f=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",v=a==="system"?f:a;i.editor.defineTheme("default",{base:v==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":v==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),i.editor.setTheme("default")},[n,a,i]),D.useEffect(()=>{const f=x.current;f&&i&&o&&f.addCommand(i.KeyMod.Shift|i.KeyCode.Enter,function(){return c(),!1})},[i,c,o]);function m(f,v){if(x.current=f,!h.current[o.id]){const C=f.getModel(),A=k();h.current[o.id]=C||(v==null?void 0:v.editor.createModel(A,t))||f.getModel()}f.setModel(h.current[o.id])}return{handleEditorDidMount:m}}function Pt(){const t=s.useEditorStore(i=>i.card.sql),n=s.useEditorStore(i=>i.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:o}=Is("sql");function d(i){a(i),s.isObjectEmpty(n)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:d,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:o})]})}function Vt(){const t=s.useEditorStore(o=>o.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=Is("python");function r(o){n(o)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:a})}function zt(){const t=s.useQueryClient(),{isConsoleMode:n}=s.useDashboardPreferences(),[a,r]=D.useState(!1);s.useEditorStore(V=>V.frame);const o=s.useEditorStore(V=>V.card);s.useEditorStore(V=>V.isShowingVisual),s.useEditorStore(V=>V.selectedConnectionId),s.useEditorStore(V=>V.tempQueryData),s.useEditorStore(V=>V.selectedDatabaseName),s.useEditorStore(V=>V.selectedDatamodelId),s.useEditorStore(V=>V.selectedSchemaName);const d=s.useEditorStore(V=>V.showAIDialog);s.useEditorStore(V=>V.selectedTableName);const i=s.useEditorStore(V=>{var z;return(z=V==null?void 0:V.card)==null?void 0:z.sql}),c=s.useEditorStore(V=>{var z;return(z=V==null?void 0:V.card)==null?void 0:z.python}),{cardFilterValues:l}=s.useCardFilterValues((o==null?void 0:o.id)??""),u=s.useDashboardStore(V=>V.inlineFilterValuesMap[(o==null?void 0:o.id)??""]),x=D.useRef(!0),{setCardCustomCfg:h,setQueryResultColumns:g,setCardSql:k,setTempQueryData:m,setPythonStdOut:f,setCardPreferences:v,setCardType:C,setCardPython:A,runAssistant:B,setShowAIDialog:O,setCard:E,updateCardInFrame:N}=s.useEditorActions();s.useEditorStore(V=>V.onSave),s.useEditorStore(V=>V.onClose),s.useEditorStore(V=>V.actions.setSqlGen);const p=s.useEditorStore(V=>V.runSql),j=s.useEditorStore(V=>V.actions.setRunSql),S=s.useEditorStore(V=>V.actions.setIsSqlRunning),{data:M,isLoading:y,isFetching:b,isSuccess:I,isError:F,error:T,errorSql:L,queryKey:w,refetch:R,errorMessage:K}=s.useDashboardCardQuery(o);D.useEffect(()=>{if(M&&(M.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),f((M==null?void 0:M.output)||""),M.records.length>0)){const{dimensionKeys:V}=s.getKeys(M.records);g(V)}},[M,g,f]),D.useEffect(()=>{(y||b)&&S(!0),(F||I)&&S(!1),F&&(g([]),f(""))},[y,b,M,f,F,I,S,g,T]),D.useEffect(()=>{p&&(t.getQueryData(w)||R(),j(!1))},[p,R,j,w,t]),D.useEffect(()=>{if(x.current){x.current=!1;return}R()},[u,R]);async function _(){const V=`Can you help me debug this query?
179
+ ON ${b}`}),j},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(S=>!S.source.name||!S.target.name)||a.joins.some(S=>S.joinKeyGroups.some(M=>M.keys.length===0))||a.joins.some(S=>S.joinKeyGroups.some(M=>M.keys.some(y=>!y.source.name||!y.target.name||!y.operator))))}}function Lt({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:l}){const{setCardConfig:d}=s.useEditorActions();s.useEditorStore(y=>y.card.config);const{columnGroups:i}=s.useColumns(),{joinPlan:c,expandedJoins:o,setJoinPlan:u,addJoin:x,removeJoin:h,updateJoin:p,moveJoinUp:w,moveJoinDown:m,toggleJoinExpansion:g,getAvailableSourceEntities:v,getAvailableTargetEntities:C,addJoinKeyGroup:A,updateGroupOperator:B,removeJoinKeyGroup:O,addJoinKey:E,updateJoinKey:N,removeJoinKey:f,generateSQLPreview:j,isValidConfiguration:S}=Mt({initialJoinPlan:t,availableDataSources:n}),M=y=>{const b=i.find(I=>I.entityName===y);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(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:c.baseEntity.name,onValueChange:y=>{const b=n.find(I=>I.name===y);u({...c,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:y,database:b==null?void 0:b.database,schema:b==null?void 0:b.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:n.map(y=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:y.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:y.type}),y.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},y.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:j()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",c.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:x,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),c.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:c.joins.map(y=>{const b=n.find(T=>T.name===y.source.name),I=n.find(T=>T.name===y.target.name),F=o.has(y.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.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(s.Badge,{children:y.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",y.sequence,b&&I&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",b.name," → ",I.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>w(y.id),disabled:y.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>m(y.id),disabled:y.sequence===c.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(y.id),children:F?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(y.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),F&&e.jsxs(s.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(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:y.source.name,onValueChange:T=>{const L=n.find(k=>k.name===T);p(y.id,{source:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:T,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:v(y.id).map(T=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:T.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:T.type}),T.name]})},T.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:y.joinType,onValueChange:T=>p(y.id,{joinType:T}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:y.target.name,onValueChange:T=>{const L=n.find(k=>k.name===T);p(y.id,{target:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:T,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},disabled:!y.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:y.source.name?C(y.source.name).map(T=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:T.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:T.type}),T.name,T.name===y.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},T.name)):[]})]})]})]}),y.source.name&&y.target.name&&b&&I&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>A(y.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),y.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:y.joinKeyGroups.map((T,L)=>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(s.Label,{children:["Group ",L+1]}),L>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.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(s.Select,{value:T.operator,onValueChange:k=>B(y.id,L,k),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>O(y.id,L),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[T.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:T.keys.map((k,R)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[R>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:T.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:k.source.name,onValueChange:K=>N(y.id,L,R,"sourceColumnName",K),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:M(y.source.name).map(K=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:K.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:K.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:K.dataType})]})},K.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:k.operator,onValueChange:K=>N(y.id,L,R,"operator",K),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:k.target.name,onValueChange:K=>N(y.id,L,R,"targetColumnName",K),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:M(y.target.name).map(K=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:K.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:K.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:K.dataType})]})},K.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>f(y.id,L,R),children:e.jsx(s.X,{className:"size-3.5"})})]},k.id||R))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>E(y.id,L),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},T.id))})]})]})]},y.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>a(c),disabled:!S(),children:"Save"})]})]})}function Ts({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:l,onRemove:d,onSave:i,onCancel:c}){return e.jsxs(s.Dialog,{open:n,onOpenChange:a,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(Lt,{joinPlan:r,availableDataSources:l,onSave:i,onCancel:c,onRemove:d})]}),t]})}function Ft({joins:t,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"max-h-[400px] divide-y divide-border overflow-y-auto",children:[t.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 l=[...t].sort((i,c)=>i.sequence-c.sequence),d=a.find(i=>i.name===n);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(s.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}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(i=>{const c=a.find(o=>o.name===i.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(s.Badge,{variant:"outline",className:"text-xs",children:i.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(s.Badge,{variant:"secondary",className:"text-xs",children:c==null?void 0:c.type}),e.jsx("span",{className:"text-xs font-medium",children:c==null?void 0:c.name})]})]},i.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((l,d)=>l.sequence-d.sequence).map((l,d)=>{const i=a.find(u=>u.name===l.source.name),c=a.find(u=>u.name===l.target.name),o=l.joinKeyGroups.reduce((u,x)=>u+x.keys.length,0);return e.jsxs("div",{className:"rounded-md bg-muted p-2 text-left",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:d+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto shrink-0 text-xs",children:[o," condition",o>1?"s":""]})]}),e.jsxs("div",{className:"mt-1 truncate pl-1 text-xs text-muted-foreground",children:[i==null?void 0:i.name," → ",c==null?void 0:c.name]})]},l.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 rs({open:t,onOpenChange:n,variant:a="button"}={}){var A,B;const r=s.useEditorStore(O=>O.card),{autoJoinMetadata:l}=s.useDashboardCardQuery(r),d=s.useEditorStore(O=>O.actions.updateCardConfig),i=((A=r==null?void 0:r.config)==null?void 0:A.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[c,o]=D.useState(!1),u=t!==void 0,x=u?t:c,h=u?n:o,p=((B=r==null?void 0:r.dataSource)==null?void 0:B.selectedEntities)||[],w=O=>{d(r.id,{...r==null?void 0:r.config,joinPlan:O}),h(!1)},m=()=>{d(r.id,{...r==null?void 0:r.config,joinPlan:void 0})},g=()=>{h(!1)},v=()=>{const O=[...i.joins].sort((f,j)=>f.sequence-j.sequence),E=i.baseEntity;if(!E.name)return"SELECT * FROM table -- Please select a base entity";let N=`SELECT *
180
+ FROM ${E.name}`;return O.forEach(f=>{const j=p.find(y=>y.name===f.target.name);if(!j)return;const S=f.joinKeyGroups.filter(y=>y.keys&&y.keys.length>0).map(y=>{const b=y.keys.filter(I=>{var F,T,L,k;return((F=I.source)==null?void 0:F.name)&&((T=I.target)==null?void 0:T.name)&&((L=I.source)==null?void 0:L.entityName)&&((k=I.target)==null?void 0:k.entityName)}).map(I=>`${I.source.entityName}.${I.source.name} ${I.operator} ${I.target.entityName}.${I.target.name}`);return b.length>1?`(${b.join(` ${y.operator} `)})`:b[0]}).filter(Boolean),M=S.length>1?S.join(" OR "):S[0]||"condition_here";N+=`
181
+ ${f.joinType} JOIN ${j.name}
182
+ ON ${M}`}),N};if(p.length<2)return null;const C=i.joins.length>0&&e.jsx(s.TooltipContent,{side:"bottom",className:"ml-4 max-w-md overflow-hidden p-0",children:e.jsx(Ft,{joins:i.joins,baseEntityId:i.baseEntity.name,availableDataSources:p,generateSQLPreview:v})});return e.jsxs(e.Fragment,{children:[e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:a==="badge"?e.jsxs(s.Badge,{variant:"secondary",className:"h-5 cursor-pointer gap-1 px-1.5 text-xs transition-colors hover:bg-secondary/80",onClick:O=>{O.stopPropagation(),h(!0)},children:[e.jsx(s.Link,{className:"h-3 w-3"}),i.joins.length]}):e.jsxs(s.Button,{onClick:()=>h(!0),variant:"outline",className:"w-full bg-muted/50",children:[e.jsx(s.Link,{className:"mr-2 h-3.5 w-3.5"}),i.joins.length===0?"Configure Joins":i.joins.length===1?"Join":"Joins",i.joins.length>0&&e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1.5 text-xs font-medium text-primary-foreground",children:i.joins.length}),(l==null?void 0:l.autoResolved)&&e.jsxs(s.Badge,{variant:"secondary",className:"ml-2 h-5 gap-1 bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:[e.jsx(s.Sparkles,{className:"h-3 w-3"}),"Auto"]})]})}),C]})}),e.jsx(Ts,{open:x,onOpenChange:h,joinPlan:i,availableDataSources:p,onSave:w,onCancel:g,onRemove:m,children:e.jsx("div",{})})]})}function Bt({open:t,onOpenChange:n}){const[a,r]=D.useState([]),{updateDataSource:l}=s.useEditorActions(),d=s.useDashboardStore(m=>m.dashboard.aiContext),i=(d==null?void 0:d.selectedEntities)||[];D.useEffect(()=>{t&&r([])},[t]);const c=m=>{r(g=>g.some(C=>C.name===m.name&&C.type===m.type)?g.filter(C=>!(C.name===m.name&&C.type===m.type)):[...g,m])},o=()=>{r([...i])},u=()=>{r([])},x=()=>{if(a.length===0)return;const m=a[0],g=m.connectionId||"",v=m.connectionType||"",A=a.some(O=>O.type==="dataset")?"semanticDomain":"database";l({connectionId:g,connectionType:v,mode:A,selectedEntities:a}),n(!1)},h=m=>"label"in m&&m.label?m.label:m.name,p=m=>{if("description"in m&&m.description)return m.description;const g=[];return m.database&&g.push(m.database),m.schema&&g.push(m.schema),m.name&&g.push(m.name),g.join(".")},w=m=>a.some(g=>g.name===m.name&&g.type===m.type);return i.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>n(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:o,disabled:a.length===i.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[a.length," of ",i.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:i.map((m,g)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",w(m)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:w(m),onCheckedChange:()=>c(m)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:s.getEntityIcon(m.type)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:h(m)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:p(m)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:m.type})]},`${m.type}-${m.name}-${g}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:x,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function ls({entities:t,title:n}){const{isConsoleMode:a}=s.useDashboardPreferences();return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:n??`${t.length} more entities`}),e.jsx("div",{className:"space-y-1",children:t.map((r,l)=>{const d=s.getEntityDetails(r),i=d.find(o=>o.label==="Description"&&o.value),c=d.filter(o=>o.label==="Description"?!1:a?!0:!["Connection","Database","Schema"].includes(o.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(r)}),i&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:i.value})]}),c.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:c.map((o,u)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[o.label,":"]}),e.jsx("span",{className:"font-mono",children:o.value})]},u))})]},`remaining-${r.type}-${r.name}-${l}`)})})]})})}function Ve(t,n){const[a,r]=D.useState(()=>{const l=localStorage.getItem(t);return l?JSON.parse(l):n});return D.useEffect(()=>{localStorage.setItem(t,JSON.stringify(a))},[a,t]),[a,r]}function Es({isVisible:t}){var g,v;const n=s.useEditorStore(C=>C.isDevMode);s.useSyncLegacyEditorState();const[a,r]=D.useState(!1),[l,d]=D.useState(!1),[i,c]=Ve("semaphor:data-source-collapsed",!1),o=s.useEditorStore(C=>C.card.dataSource),u=s.useEditorStore(C=>{var A,B;return(B=(A=C.card)==null?void 0:A.config)==null?void 0:B.joinPlan}),{updateDataSource:x}=s.useEditorActions(),h=((g=o==null?void 0:o.selectedEntities)==null?void 0:g.length)||0,p=((v=u==null?void 0:u.joins)==null?void 0:v.length)||0,m={...{connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},...o,selectedEntities:(o==null?void 0:o.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[h===0&&p===0?e.jsx("div",{className:"p-4 px-6",children:e.jsxs(s.Button,{className:"w-full bg-muted/50",variant:"outline",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),"Choose Dataset"]})}):e.jsxs("div",{children:[e.jsxs("div",{className:s.cn("flex cursor-pointer items-center justify-between px-6 pt-3",!i&&"pb-3"),onClick:()=>c(!i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Data Source"}),i&&e.jsxs("div",{className:"flex items-center gap-1.5",onClick:C=>C.stopPropagation(),children:[h>0&&e.jsx(s.TooltipProvider,{delayDuration:100,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"h-5 cursor-pointer gap-1 px-1.5 text-xs transition-colors hover:bg-secondary/80",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"h-3 w-3"}),h]})}),e.jsx(ls,{entities:m.selectedEntities,title:`${h} selected ${h===1?"entity":"entities"}`})]})}),p>0&&!n&&e.jsx(rs,{variant:"badge"})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:C=>{C.stopPropagation(),c(!i)},children:i?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:s.cn("overflow-hidden transition-all duration-200 ease-in-out",i?"max-h-0 opacity-0":"max-h-96 opacity-100"),children:[e.jsx("div",{className:"px-6 pb-2",children:e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"w-full bg-muted/50",variant:"outline",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),h===1?"Dataset":"Datasets",e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1.5 text-xs font-medium text-primary-foreground",children:h})]})}),e.jsx(ls,{entities:m.selectedEntities,title:`${h} selected ${h===1?"entity":"entities"}`})]})})}),!n&&e.jsx("div",{className:"px-6 pb-2",children:e.jsx(rs,{})})]})]}),e.jsx(s.FieldsSection,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(o==null?void 0:o.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:m}),e.jsx(Bt,{open:l,onOpenChange:d})]})}function Je({error:t,errorSql:n,onSendFeedback:a,onOpenInEditor:r,className:l,showFeedbackButton:d=!0,errorTitle:i="Query Error"}){const[c,o]=D.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-destructive/30 bg-destructive/5 p-4",l),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(s.CircleAlert,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-destructive"}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:i}),e.jsxs("div",{className:"relative rounded-md bg-background/60 p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 h-6 w-6 z-10"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"font-mono text-xs text-foreground/80 break-all",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n&&e.jsx(s.Collapsible,{open:c,onOpenChange:o,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:c?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),r&&n&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:r,children:[e.jsx(ws,{className:"mr-1.5 h-3.5 w-3.5"}),"Open in Editor"]}),d&&a&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:a,children:[e.jsx(s.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),n&&e.jsx(s.Collapsible,{open:c,onOpenChange:o,children:e.jsx(s.CollapsibleContent,{className:"space-y-2",children:e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Error SQL Query"}),e.jsx(s.CopyButton,{text:n,className:"h-6 w-6"})]}),e.jsx("div",{className:"rounded-md bg-background/60 p-2 max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:n,language:"sql"})})]})})})]})]})})}function As({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){const l=s.useEditorStore(g=>g.isDevMode),{setIsDevMode:d,setCardSql:i,setRunSql:c}=s.useEditorActions(),[o,u]=D.useState(!1),x=s.useEditorStore(g=>g.card),h=s.useEditorStore(g=>g.frame),p=s.useDashboardStore(g=>g.selectedSheetId),w=s.useDashboardStore(g=>{var v;return(v=g.dashboard)==null?void 0:v.id});function m(g){d(!0),i(g||t),setTimeout(()=>{c(!0)},100)}return e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col pt-4",children:[!l&&t&&!n&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsxs(s.Button,{onClick:()=>m(),variant:"secondary",size:"sm",children:[e.jsx(ws,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),e.jsxs(s.Button,{onClick:()=>u(!o),variant:"outline",size:"sm",children:[e.jsx(s.Info,{className:"mr-2 h-4 w-4"}),"Card Details"]})]}),o&&e.jsx("div",{className:"mb-3 rounded-lg border border-border bg-muted/30 p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Card Information"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>u(!1),children:e.jsx(Cs,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID"}),e.jsx("code",{className:"text-xs font-mono",children:x.id||"N/A"})]}),e.jsx(s.CopyButton,{text:x.id||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Frame ID"}),e.jsx("code",{className:"text-xs font-mono",children:h.id||"N/A"})]}),e.jsx(s.CopyButton,{text:h.id||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Sheet ID"}),e.jsx("code",{className:"text-xs font-mono",children:p||"N/A"})]}),e.jsx(s.CopyButton,{text:p||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Dashboard ID"}),e.jsx("code",{className:"text-xs font-mono",children:w||"N/A"})]}),e.jsx(s.CopyButton,{text:w||"",className:"h-6 w-6"})]})]})]})}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-auto text-xs leading-relaxed text-foreground/80",children:[n&&e.jsx(Je,{error:n,errorSql:a,showFeedbackButton:!1,onOpenInEditor:()=>m(a)}),!n&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute right-2 top-2 z-10",children:e.jsx(s.CopyButton,{text:t,className:"h-6 w-6"})}),e.jsx(s.CodeHighlighter,{code:t,language:"sql"})]})})]}),n&&r&&e.jsx("div",{className:"mt-3",children:e.jsxs(s.Button,{onClick:r,size:"sm",variant:"outline",children:[e.jsx(ft,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})})]})}function Ot({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:n?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:n?e.jsx(Cs,{className:"h-4 w-4 text-red-500"}):e.jsx(s.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(s.HoverCardContent,{align:"start",className:"flex w-[700px]",children:e.jsx(As,{errorSql:a,sql:t,error:n,onDebugWithAssistant:r})})]})}function Rt(t){return s.GenIcon({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(t)}function Is(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(g=>g.theme),r=s.useEditorStore(g=>g.frame),l=s.useEditorStore(g=>g.card),d=s.useEditorStore(g=>g.activeTabCardId),i=s.Le(),{refetch:c}=s.useDashboardCardQuery(l),{updateCardTab:o,setRunSql:u}=s.useEditorActions(),x=D.useRef(),h=D.useRef({}),p=r.cards.find(g=>g.id===d),w=D.useCallback(()=>{let g="";return t==="python"&&(g=(p==null?void 0:p.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(g=(p==null?void 0:p.sql)||""),g},[t,p]);D.useEffect(()=>{if(d&&l.id&&l.id!==d){if(x.current&&i){const g=x.current.getModel();g&&(h.current[l.id]=g);let v=h.current[d];if(!v){const C=w();v=i.editor.createModel(C,t),h.current[d]=v}x.current.setModel(v)}o(d,l),u(!0)}},[d,l,o,i,u,t,w]),D.useEffect(()=>{if(!i)return;const g=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",v=a==="system"?g:a;i.editor.defineTheme("default",{base:v==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":v==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),i.editor.setTheme("default")},[n,a,i]),D.useEffect(()=>{const g=x.current;g&&i&&l&&g.addCommand(i.KeyMod.Shift|i.KeyCode.Enter,function(){return c(),!1})},[i,c,l]);function m(g,v){if(x.current=g,!h.current[l.id]){const C=g.getModel(),A=w();h.current[l.id]=C||(v==null?void 0:v.editor.createModel(A,t))||g.getModel()}g.setModel(h.current[l.id])}return{handleEditorDidMount:m}}function Pt(){const t=s.useEditorStore(i=>i.card.sql),n=s.useEditorStore(i=>i.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=Is("sql");function d(i){a(i),s.isObjectEmpty(n)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:d,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function Vt(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=Is("python");function r(l){n(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:a})}function zt(){const t=s.useQueryClient(),{isConsoleMode:n}=s.useDashboardPreferences(),[a,r]=D.useState(!1);s.useEditorStore(V=>V.frame);const l=s.useEditorStore(V=>V.card);s.useEditorStore(V=>V.isShowingVisual),s.useEditorStore(V=>V.selectedConnectionId),s.useEditorStore(V=>V.tempQueryData),s.useEditorStore(V=>V.selectedDatabaseName),s.useEditorStore(V=>V.selectedDatamodelId),s.useEditorStore(V=>V.selectedSchemaName);const d=s.useEditorStore(V=>V.showAIDialog);s.useEditorStore(V=>V.selectedTableName);const i=s.useEditorStore(V=>{var z;return(z=V==null?void 0:V.card)==null?void 0:z.sql}),c=s.useEditorStore(V=>{var z;return(z=V==null?void 0:V.card)==null?void 0:z.python}),{cardFilterValues:o}=s.useCardFilterValues((l==null?void 0:l.id)??""),u=s.useDashboardStore(V=>V.inlineFilterValuesMap[(l==null?void 0:l.id)??""]),x=D.useRef(!0),{setCardCustomCfg:h,setQueryResultColumns:p,setCardSql:w,setTempQueryData:m,setPythonStdOut:g,setCardPreferences:v,setCardType:C,setCardPython:A,runAssistant:B,setShowAIDialog:O,setCard:E,updateCardInFrame:N}=s.useEditorActions();s.useEditorStore(V=>V.onSave),s.useEditorStore(V=>V.onClose),s.useEditorStore(V=>V.actions.setSqlGen);const f=s.useEditorStore(V=>V.runSql),j=s.useEditorStore(V=>V.actions.setRunSql),S=s.useEditorStore(V=>V.actions.setIsSqlRunning),{data:M,isLoading:y,isFetching:b,isSuccess:I,isError:F,error:T,errorSql:L,queryKey:k,refetch:R,errorMessage:K}=s.useDashboardCardQuery(l);D.useEffect(()=>{if(M&&(M.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),g((M==null?void 0:M.output)||""),M.records.length>0)){const{dimensionKeys:V}=s.getKeys(M.records);p(V)}},[M,p,g]),D.useEffect(()=>{(y||b)&&S(!0),(F||I)&&S(!1),F&&(p([]),g(""))},[y,b,M,g,F,I,S,p,T]),D.useEffect(()=>{f&&(t.getQueryData(k)||R(),j(!1))},[f,R,j,k,t]),D.useEffect(()=>{if(x.current){x.current=!1;return}R()},[u,R]);async function _(){const V=`Can you help me debug this query?
183
183
 
184
184
  Error:
185
185
 
@@ -195,6 +195,6 @@ ${p.joinType} JOIN ${j.name}
195
195
 
196
196
  ${c?`Python:
197
197
  ${c}`:""}
198
- `;B(V)}function G(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.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(Pt,{})}),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(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.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(Vt,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function q(){var V,z,H,P,W,Y;return e.jsx("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-4",children:[e.jsxs(s.Button,{title:"Shift + Enter",disabled:y||b,onClick:()=>{R()},className:"h-8 shrink-0",size:"sm",children:[y||b?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(s.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(Ot,{errorSql:L,sql:M==null?void 0:M.sql,error:K,onDebugWithAssistant:_}),e.jsx(_e.EditorClearButton,{}),e.jsxs(s.Toggle,{pressed:a,onPressedChange:ee=>r(ee),className:"h-8",size:"sm",variant:"outline",children:[e.jsx(Rt,{className:"mr-2 size-4 text-foreground/70"}),"Python"]}),!d&&e.jsxs("button",{disabled:d,onClick:()=>{O(!0)},className:"flex h-8 w-full cursor-text items-center justify-start rounded-md bg-muted/50 px-3 text-left text-sm text-muted-foreground",children:[e.jsx(s.Sparkles,{className:"mr-3 size-4 text-foreground/70"}),"Type your question..."]}),e.jsxs("div",{className:"flex flex-1 items-center justify-end gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((z=(V=o.preferences)==null?void 0:V.tablePrefs)==null?void 0:z.enableDevModePagination)??!1,onCheckedChange:ee=>{var J;v({...o.preferences,tablePrefs:{...(J=o.preferences)==null?void 0:J.tablePrefs,enableDevModePagination:ee}})}}),e.jsx(s.Label,{htmlFor:"pagination",className:"cursor-pointer text-sm",children:"Paginate"}),((P=(H=o.preferences)==null?void 0:H.tablePrefs)==null?void 0:P.enableDevModePagination)&&e.jsxs(s.Select,{value:String(((Y=(W=o.preferences)==null?void 0:W.tablePrefs)==null?void 0:Y.pageSize)||50),onValueChange:ee=>{var le,Z,oe;const J=Number(ee),ne={...o,preferences:{...o.preferences,tablePrefs:{...(le=o.preferences)==null?void 0:le.tablePrefs,pageSize:J}},paginationConfig:{page:1,pageSize:J}};E(ne),N(ne),o.sql&&((oe=(Z=o.preferences)==null?void 0:Z.tablePrefs)!=null&&oe.enableDevModePagination)&&j(!0)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"10",children:"10"}),e.jsx(s.SelectItem,{value:"25",children:"25"}),e.jsx(s.SelectItem,{value:"50",children:"50"}),e.jsx(s.SelectItem,{value:"100",children:"100"}),e.jsx(s.SelectItem,{value:"500",children:"500"}),e.jsx(s.SelectItem,{value:"1000",children:"1000"})]})]})]}),l&&l.length>0&&e.jsxs(s.HoverCard,{openDelay:200,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",className:"h-8 gap-2 px-2",children:[e.jsx(s.Filter,{className:"size-4"}),e.jsx(s.Badge,{className:"h-5 min-w-5 bg-purple-100 px-1.5 text-purple-700 hover:bg-purple-100 dark:bg-purple-950 dark:text-purple-300",children:l.length})]})}),e.jsx(s.HoverCardContent,{className:"mr-4 max-h-[400px] w-[500px] overflow-auto p-0",children:e.jsxs("div",{className:"p-3",children:[e.jsx("div",{className:"mb-2 text-sm font-semibold",children:"Active Dashboard Filters"}),e.jsx(s.CodeHighlighter,{code:JSON.stringify(l,null,2),language:"json"})]})})]})]})]})})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsx("div",{className:"relative flex grow overflow-y-scroll",children:G()}),q()]})}const $t=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:s.Grid3x3}];function Kt({className:t}){const n=s.useEditorStore(l=>l.card),{setCardType:a,setCard:r,updateCardInFrame:o}=s.useEditorActions(),d=["table","aggregateTable","pivotTable"].includes(n.type),i=s.hasValidCardConfig(n.config);if(!d||!i)return null;const c=l=>{var x;const u=l;if(u==="aggregateTable"&&((x=n.config)!=null&&x.pivotByColumns)&&n.config.pivotByColumns.length>0){const h={...n,type:u,config:{...n.config,pivotByColumns:[]}};r(h),o(h)}else{a(u);const h={...n,type:u};o(h)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:n.type,onValueChange:c,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:$t.map(l=>{const u=l.icon,x=n.type===l.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:l.value,id:`table-type-${l.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${l.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all",x?"bg-muted text-foreground shadow-sm":"text-muted-foreground hover:bg-muted/50"),children:[e.jsx(u,{className:"h-3.5 w-3.5"}),l.label]})]},l.value)})})})}function Gt({type:t,isLinked:n,className:a}){const r=s.useDashboardStore(g=>g.selectedFrameId),o=s.useManagementStore(g=>g.selectedVisual),d=s.useEditorStore(g=>g.frame);let i;if(t)i=t;else if(n!==void 0)i=n?"linked":"library";else if(!!!(d!=null&&d.visualId||o!=null&&o.id)&&r)i="local";else if(o&&!r)i="library";else if(d!=null&&d.visualId&&r)i="linked";else if(o!=null&&o.id&&r)i="library";else return null;if(i==="local")return null;const c={linked:"border-purple-200/70 bg-gradient-to-r from-purple-50/50 to-purple-100/30 text-purple-900 shadow-sm hover:from-purple-100/60 hover:to-purple-100/50 hover:shadow-md dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100 dark:hover:from-purple-950/60 dark:hover:to-purple-900/50",library:"border-blue-200/70 bg-gradient-to-r from-blue-50/50 to-blue-100/30 text-blue-900 shadow-sm hover:from-blue-100/60 hover:to-blue-100/50 hover:shadow-md dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30 dark:text-blue-100 dark:hover:from-blue-950/60 dark:hover:to-blue-900/50"},l={linked:"Linked to library: Changes made here update the library visual and all linked instances.",library:"Library visual: Share and reuse this visual across multiple dashboards."},u={linked:"border-purple-200 bg-purple-50 text-purple-900 dark:border-purple-800 dark:bg-purple-950 dark:text-purple-100",library:"border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-800 dark:bg-blue-950 dark:text-blue-100"},x={linked:"fill-purple-50 dark:fill-purple-950",library:"fill-blue-50 dark:fill-blue-950"},h={linked:e.jsx(bt,{className:"h-3.5 w-3.5"}),library:e.jsx(jt,{className:"h-3.5 w-3.5"})};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:s.cn("cursor-help select-none transition-all",c[i],a),children:h[i]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:s.cn("max-w-xs",u[i]),children:[e.jsx(s.TooltipArrow,{className:x[i]}),e.jsx("p",{children:l[i]})]})]})})}function Ds({className:t,...n}){var G,q,V;const a=s.useEditorStore(z=>z.card),r=((G=a.customCardPreferences)==null?void 0:G.showCardHeader)??!0,o=((V=(q=a.preferences)==null?void 0:q.displayOptions)==null?void 0:V.showInlineFilterBar)??!0,d=s.useEditorStore(z=>z.frame),i=s.useDashboardStore(z=>z.dashboard.filters),c=s.useDashboardStore(z=>z.selectedSheetId),[l,u]=D.useState(!1),{currentUser:x}=s.useCurrentUserInfo(),{tokenProps:h}=D.useContext(s.SemaphorContext),g=s.useEditorStore(z=>z.actions.setRunSql),{updateFilter:k}=s.useDashboardActions(),m=i==null?void 0:i.find(z=>z.id===d.filterId),{data:f,isLoading:v,isFetching:C,errorMessage:A,errorSql:B,pagination:O}=s.useDashboardCardQuery(a),E=D.useMemo(()=>(f==null?void 0:f.records)||[],[f==null?void 0:f.records]),{setCard:N,updateCardInFrame:p,setIsDevMode:j,setCardSql:S}=s.useEditorActions(),{data:M}=s.useTopoJson(a),y=D.useMemo(()=>{var z;return a.type!=="pivotTable"||!((z=f==null?void 0:f.records)!=null&&z.length)?null:{records:f.records,columnSubtotalMeta:f.columnSubtotalMeta,subtotalColumns:f.subtotalColumns||[],pivotSchema:f.pivotSchema||[],groupByColumns:f.groupByColumns}},[a.type,f==null?void 0:f.records,f==null?void 0:f.columnSubtotalMeta,f==null?void 0:f.subtotalColumns,f==null?void 0:f.pivotSchema,f==null?void 0:f.groupByColumns]),b=s.usePivotTableConfig(a,y),I=z=>{j(!0),S(z||B||a.sql||a.python||""),setTimeout(()=>{g(!0)},100)},F=()=>{u(!0)},T=D.useMemo(()=>{const z=typeof window<"u"?window.location.href:"",H=typeof navigator<"u"?navigator.userAgent:"",P=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:s.FeedbackCategory.QUERY_GENERATION,user:x,tokenContext:h,systemState:{cardConfig:a.config,dataSource:a.dataSource,dashboardFilters:i,errorMessage:A||void 0,errorSql:B||a.sql||a.python,generatedSql:B||a.sql},metadata:{url:z,userAgent:H,timestamp:new Date().toISOString(),viewport:P}}},[x,h,a,i,A,B]),L=(z,H)=>{var W,Y;const P={...a,paginationConfig:{page:z+1,pageSize:H}};N(P),p(P),a.sql&&((Y=(W=a.preferences)==null?void 0:W.tablePrefs)!=null&&Y.enableDevModePagination)&&g(!0)},w=z=>{var W,Y,ee,J;const H=s.sortStateToSortByColumns(z,(W=a.config)==null?void 0:W.metricColumns,(Y=a.config)==null?void 0:Y.groupByColumns),P={...a,config:{...a.config||{},sortByColumns:H}};N(P),p(P),a.sql&&((J=(ee=a.preferences)==null?void 0:ee.tablePrefs)!=null&&J.enableDevModePagination)&&g(!0)},R=D.useMemo(()=>!a.id||!(f!=null&&f.records)?null:s.createChartConfig({card:a,data:f==null?void 0:f.records,cardType:a.type,queryConfig:a.queryConfig,customCfg:a.customCfg,preferences:a.preferences,topoJson:M}),[a.id,f==null?void 0:f.records,a.type,a.customCfg,a.preferences,M]);function K(z){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(s.EditorCustomVisual,{card:z})})}function _(){if(f!=null&&f.records&&(f==null?void 0:f.records.length)===0&&!v&&!C)return A?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(Je,{error:A,errorSql:B||a.sql||a.python,onOpenInEditor:I,onSendFeedback:F,showFeedbackButton:!0,errorTitle:"Unable to Create Visual"})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((v||C)&&(!(f!=null&&f.records)||f.records.length===0))return a.type==="table"?e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableSkeleton,{})}):e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!a.id)return null;if(a.type==="custom")return K(a);if(!["table","pivotTable","aggregateTable","custom"].includes(a.type)&&R)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:v||C?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:R})});if(a.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:a,data:E,paginationMetadata:O,onPaginationChange:L,onSortChange:w,isLoading:v||C})});if(a.type==="pivotTable"&&b)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.PivotTableTanstack,{card:a,data:b.data,options:b.options,onAggregationChange:z=>{const H=s.handleAggregationChange(z,a.config),P={...a,config:H};N(P),p(P)},onAggregationLabelChange:z=>{const H=s.handleAggregationLabelChange(z,a.config),P={...a,config:H};N(P),p(P)}})});if(a.type==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:a,data:(f==null?void 0:f.records)||[],groupByColumns:f==null?void 0:f.groupByColumns,pivotSchema:f==null?void 0:f.pivotSchema,paginationMetadata:O,onPaginationChange:L,onAggregationChange:z=>{const H=s.handleAggregationChange(z,a.config),P={...a,config:H};N(P),p(P)},isLoading:v||C})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[(v||C)&&(f==null?void 0:f.records)&&f.records.length>0&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),r&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:a.title,onSave:z=>N({...a,title:z}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(Gt,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(Kt,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:a.description||"",onSave:z=>N({...a,description:z}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),m&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:m.title||m.column,onSave:z=>k({...m,title:z}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:m})]})]}),o&&a.inlineFilters&&a.inlineFilters.length>0&&e.jsx("div",{className:"px-6 pb-3",children:e.jsx(s.InlineFilterBar,{card:a,sheetId:c||""})}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:_()}),e.jsx(s.FeedbackDialog,{open:l,onOpenChange:u,feedbackData:T,showDebugInfo:!0})]})}const Ke=({language:t,value:n,onChange:a,readonly:r})=>e.jsx(s.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:t,value:n,onChange:a}),qt=()=>e.jsxs(s.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.DialogTitle,{children:"Customize Card"})}),e.jsxs(s.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."})]})]}),Ut=({customCode:t,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:o})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Ke,{language:"json",value:a,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Ke,{readonly:!0,language:"json",value:n,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Ke,{language:"javascript",value:t,onChange:o})})]}),_t=({error:t,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:o})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!n,onClick:a,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:o,variant:"outline",children:"Close"})]});function Ht(){const[t,n]=D.useState(!1),[a,r]=D.useState(""),[o,d]=D.useState(""),[i,c]=D.useState(""),[l,u]=D.useState(""),x=s.useEditorStore(E=>E.card),h=s.useEditorStore(E=>E.card.customCfg),g=h?JSON.stringify(h,null,2):"",{data:k}=s.useDashboardCardQuery(x),{data:m}=s.useTopoJson(x),{setCardCustomCfg:f,setCustomVisualCode:v}=s.useEditorActions(),C=E=>{var N,p;return JSON.stringify({...E,data:{...E.data,datasets:(p=(N=E.data)==null?void 0:N.datasets)==null?void 0:p.map(j=>({...j,data:[]}))}},null,2)},A=()=>{var N,p;if(!((N=k==null?void 0:k.records)!=null&&N.length))return;const E=s.createChartConfig({card:x,data:k.records,cardType:x.type,queryConfig:x.queryConfig,preferences:x.preferences,topoJson:m});if(E){r(C(E)),c(((p=x.preferences)==null?void 0:p.customVisualCode)||"");const j=s.merge(E,h);d(C(j))}},B=()=>{try{if(i&&v(i),o){const E=JSON.parse(o),N=s.getObjectDiff(JSON.parse(a),E);f(N),u("")}}catch{u("Invalid JSON configuration")}},O=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:n,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:A,className:O?"":"text-green-600 hover:text-green-700",children:e.jsx(s.Settings,{className:"h-4 w-4"})})}),e.jsxs(s.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(qt,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Ds,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Ut,{customCode:i,cardCustomCfgString:g,mergedConfig:o,onConfigChange:E=>d(E??""),onCodeChange:E=>c(E??"")})]}),e.jsx(_t,{error:l,hasCardCustomConfig:!!h,onReset:()=>{d(a),f(null)},onApply:B,onClose:()=>n(!1)})]})]})}function Jt({onChartTypeChange:t}){const{setCardCustomCfg:n,setCardPreferences:a,setCardType:r,setCustomCardPreferences:o}=s.useEditorActions(),{data:d,isLoading:i,isError:c}=s.useCustomVisualsQuery(),l=D.useCallback((u,x)=>{n(null),a({}),r(u),x&&o({type:"component",visualType:"single",url:x.url,componentName:x.name,icon:x.icon}),t==null||t()},[n,a,r,o,t]);return i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-muted-foreground",children:"Loading custom visuals..."})]}):c?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-destructive",children:"Failed to load custom visuals"})]}):!d||d.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"mb-2",children:e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Custom Charts"})}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:d.map((u,x)=>e.jsx(Qt,{text:u.name,onClick:()=>l("custom",u),icon:u.icon},`${u.url}-${u.name}-${x}`))})]})}const Qt=({text:t,icon:n,onClick:a})=>{const r=s.useDynamicIcon();return e.jsxs("button",{onClick:a,className:"flex flex-col items-center gap-2 rounded-lg border border-border bg-background p-3 transition-all hover:border-primary/50 hover:bg-muted/50 hover:shadow-sm",children:[r?e.jsx(r,{className:"h-6 w-6"}):e.jsx(De,{className:"h-6 w-6 text-muted-foreground"}),e.jsx("span",{title:t,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:t})]})};function Yt({onChartTypeChange:t,iconClassName:n,searchQuery:a=""}){const{setCardType:r,setCardPreferences:o,setIsDevMode:d}=s.useEditorStore(g=>g.actions),{setCardCustomCfg:i,setCustomCardPreferences:c,setQueryConfig:l}=s.useEditorActions();function u(g,k){i(null),o({}),r(g),["custom","text","map"].includes(g)&&(d(!0),l(void 0)),t==null||t()}const h=[{type:"table",name:"Table",icon:s.Table2},{type:"bar",name:"Bar Chart",icon:s.ChartColumnIncreasing},{type:"line",name:"Line Chart",icon:s.ChartLine},{type:"stackedBar",name:"Stacked Bar",icon:s.ChartColumnStacked},{type:"stackedLine",name:"Stacked Line",icon:s.MdStackedLineChart},{type:"scatter",name:"Scatter",icon:s.ChartScatter},{type:"bubble",name:"Bubble",icon:s.TbChartBubble},{type:"pie",name:"Pie Chart",icon:s.ChartPie},{type:"doughnut",name:"Doughnut",icon:s.Donut},{type:"funnel",name:"Funnel",icon:s.TbChartFunnel},{type:"radar",name:"Radar",icon:s.Radar},{type:"polarArea",name:"Polar Area",icon:s.PiChartPolar},{type:"tornado",name:"Tornado",icon:s.Tornado},{type:"range",name:"Range",icon:s.ChartNoAxesGantt},{type:"bullet",name:"Bullet Chart",icon:s.BulletChartIcon},{type:"treemap",name:"Treemap",icon:s.TbChartTreemap},{type:"kpi",name:"KPI",icon:s.TiSortNumerically},{type:"text",name:"Text",icon:s.BookType},{type:"map",name:"Map",icon:s.Map},{type:"custom",name:"Custom",icon:De}].filter(g=>g.name.toLowerCase().includes(a.toLowerCase()));return e.jsx("div",{className:"grid grid-cols-3 gap-2",children:h.map(g=>{const k=g.icon;return e.jsxs("button",{onClick:()=>u(g.type),className:"flex flex-col items-center gap-2 rounded-lg border border-border bg-background p-3 transition-all hover:border-primary/50 hover:bg-muted/50 hover:shadow-sm",children:[e.jsx(k,{className:s.cn("h-6 w-6",n),strokeWidth:g.icon===s.MdStackedLineChart?0:void 0}),e.jsx("span",{className:"text-xs font-medium text-foreground",children:g.name})]},g.type)})})}function Wt({chartType:t,className:n,customIcon:a,componentName:r}){const o=s.useDynamicIcon();switch(t){case"bar":return e.jsx(s.ChartColumnIncreasing,{className:n});case"line":return e.jsx(s.ChartLine,{className:n});case"pie":return e.jsx(s.ChartPie,{className:n});case"radar":return e.jsx(s.Radar,{className:n});case"scatter":return e.jsx(s.ChartScatter,{className:n});case"bubble":return e.jsx(s.TbChartBubble,{className:n});case"doughnut":return e.jsx(s.Donut,{className:n});case"stackedBar":return e.jsx(s.ChartColumnStacked,{className:n});case"stackedLine":return e.jsx(s.MdStackedLineChart,{className:n});case"polarArea":return e.jsx(s.PiChartPolar,{className:n});case"treemap":return e.jsx(s.TbChartTreemap,{className:n});case"bullet":return e.jsx(s.BulletChartIcon,{className:n});case"funnel":return e.jsx(s.TbChartFunnel,{className:n});case"tornado":case"pyramid":return e.jsx(s.Tornado,{className:n});case"range":return e.jsx(s.ChartNoAxesGantt,{className:n});case"kpi":return e.jsx(s.TiSortNumerically,{className:n});case"text":return e.jsx(s.Type,{className:n});case"map":return e.jsx(s.Map,{className:n});case"custom":return a&&o?e.jsx(o,{className:n}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(De,{className:n});default:return e.jsx(s.Table2,{className:n})}}function Ms({variant:t="ghost"}){var c,l;const[n,a]=D.useState(!1),[r,o]=D.useState(""),d=s.useEditorStore(u=>u.card),i=d.type;return e.jsxs(s.Popover,{open:n,onOpenChange:u=>{a(u),u||o("")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(Wt,{className:"size-4",chartType:i,customIcon:(c=d.customCardPreferences)==null?void 0:c.icon,componentName:(l=d.customCardPreferences)==null?void 0:l.componentName})})}),e.jsxs(s.PopoverContent,{onOpenAutoFocus:u=>u.preventDefault(),className:"z-[70] w-[360px] p-3",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-sm border border-border bg-background px-3 py-2",children:[e.jsx(s.Search,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search charts...",value:r,onChange:u=>o(u.target.value),className:"h-auto border-0 p-0 text-sm focus-visible:ring-0 focus-visible:ring-offset-0"})]}),e.jsxs("div",{className:"max-h-[400px] overflow-y-auto",children:[e.jsx(Yt,{onChartTypeChange:()=>a(!1),searchQuery:r}),e.jsx(Jt,{onChartTypeChange:()=>a(!1)})]})]})]})}function Xt({error:t,className:n="",textClassName:a="",copyButtonClassName:r=""}){const[o,d]=D.useState(!1),i=D.useRef(null),c=D.useRef(!1);function l(){t&&!c.current&&navigator.clipboard.writeText(t)}function u(g){(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),l())}function x(){const g=window.getSelection();if(g&&g.toString().trim()!==""){const k=g.toString();navigator.clipboard.writeText(k),d(!0),c.current=!0,setTimeout(()=>{d(!1),c.current=!1},1e3)}else c.current=!1}function h(){d(!1),c.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 ${n}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,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:i,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${a}`,onClick:l,onKeyDown:u,onMouseUp:x,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),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 Zt(){const t=s.useEditorStore(l=>{var u,x;return(x=(u=l.card.preferences)==null?void 0:u.chartOptions)==null?void 0:x.indexAxis}),n=s.useEditorStore(l=>l.card.type),{setChartOrientation:a,setCardPreferences:r}=s.useEditorStore(l=>l.actions),o=l=>{if(a(l),n!=="bullet")return;const u=l==="y"?"horizontal":"vertical",x=s.useEditorStore.getState().card.preferences,h={...x||{},bulletConfig:{...(x==null?void 0:x.bulletConfig)||{},orientation:u}};r(h)};function d(){const l=t??"x",u=()=>{o(l==="x"?"y":"x")};return e.jsx(s.IconButton,{onClick:u,tooltip:"Chart Orientation",children:l==="x"?e.jsx($e,{className:"size-4"}):e.jsx(ze,{className:"size-4"})})}function i(){const l=()=>{o(t==="y"||t===void 0?"x":"y")};return e.jsx(s.IconButton,{onClick:l,tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx($e,{className:"size-4"}):e.jsx(ze,{className:"size-4"})})}function c(){const l=t??"y",u=()=>{o(l==="y"?"x":"y")};return e.jsx(s.IconButton,{onClick:u,tooltip:"Chart Orientation",children:l==="y"?e.jsx(ze,{className:"size-4"}):e.jsx($e,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?i():n==="bullet"?c():d()})}function en({className:t}){var k,m,f,v,C,A,B,O,E,N;const n=s.useEditorStore(p=>p.card),{setCardPreferences:a,updateCardInFrame:r,setCard:o}=s.useEditorActions(),[d,i]=D.useState(!1),c=((m=(k=n.preferences)==null?void 0:k.displayOptions)==null?void 0:m.showFilterInfo)??!0,l=((v=(f=n.preferences)==null?void 0:f.displayOptions)==null?void 0:v.showCardToolbar)??!0,u=((A=(C=n.preferences)==null?void 0:C.displayOptions)==null?void 0:A.showChrome)??!0,x=((O=(B=n.preferences)==null?void 0:B.displayOptions)==null?void 0:O.allowScroll)??!0,h=((N=(E=n.preferences)==null?void 0:E.displayOptions)==null?void 0:N.showInlineFilterBar)??!0,g=(p,j)=>{var y;const S={...n.preferences,displayOptions:{...(y=n.preferences)==null?void 0:y.displayOptions,[p]:j}};a(S);const M={...n,preferences:S};o(M),r(M)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:d,onOpenChange:i,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(ks,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"Display Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Changes apply to dashboard view only"})}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:p=>{g("showFilterInfo",p)},onSelect:p=>p.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Filter Info"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Badge"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:p=>{g("showCardToolbar",p)},onSelect:p=>p.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Toolbar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Hover actions"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:p=>{g("showChrome",p)},onSelect:p=>p.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Chrome"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Frame & padding"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:p=>{g("allowScroll",p)},onSelect:p=>p.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Allow Scroll"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card content scroll"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:h,onCheckedChange:p=>{g("showInlineFilterBar",p)},onSelect:p=>p.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Inline Filter Bar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card filters"})]})]})]})})}function sn(){const[t,n]=D.useState(!1),a=s.useEditorStore(h=>h.card),r=s.useEditorStore(h=>h.selectedConnectionId),{setCard:o}=s.useEditorActions(),d=s.useDashboardStore(h=>h.actions.removeCardInlineFilterValue),i=(a==null?void 0:a.inlineFilters)||[];function c(h){const g=h.qualifiedFieldName||h.name;if(i.find(A=>A.column===g))return;const m=h.qualifiedFieldName?h.qualifiedFieldName.split(".").slice(0,-1).join("."):h.qualifiedEntityName||h.entityName,f=s.fmt(h.name),v=h.qualifiedFieldName||f,C={id:s.v4(),column:g,title:h.label||h.name,dataType:h.dataType,table:h.entityName||"",database:"",connectionId:r||"",operation:"in",sql:s.getDefaultFilterSql(h.dataType,m,v),width:250};o({...a,inlineFilters:[...i,C]})}function l(h){const g=i.filter(k=>k.id!==h);o({...a,inlineFilters:g}),d(a.id,h)}function u(h,g){const k=i.map(m=>m.id===h?{...m,...g}:m);o({...a,inlineFilters:k})}return["bar","line","pie","doughnut","table","stackedBar","stackedLine","horizontalBar","radar","polarArea","scatter","bubble","funnel","aggregateTable","custom"].includes(a==null?void 0:a.type)?e.jsx("div",{className:"flex items-center gap-1",children:e.jsxs(s.Popover,{open:t,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.IconButton,{tooltip:"Add Inline Filter",className:s.cn("relative",{"text-primary":i.length>0}),children:[e.jsx(yt,{className:"h-4 w-4"}),i.length>0&&e.jsx("span",{className:"absolute -right-1 -top-1 flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] font-medium text-primary-foreground",children:i.length})]})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80 p-0",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"border-b px-4 py-3",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Inline Filters"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"On-card filters for fast, focused exploration."})]}),e.jsx("div",{className:"flex max-h-[300px] flex-col overflow-hidden",children:e.jsx(s.DndContext,{collisionDetection:s.closestCenter,children:e.jsx(s.SortableContext,{items:[],strategy:s.verticalListSortingStrategy,children:e.jsx(s.FieldsList,{context:"inline-filter",onFieldSelect:c,inlineFilters:i})})})}),i.length>0&&e.jsxs("div",{className:"border-t px-4 py-3",children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Active Filters"}),e.jsx("div",{className:"space-y-1",children:i.map(h=>e.jsx(tn,{filter:h,onUpdate:g=>u(h.id,g),onRemove:()=>l(h.id)},h.id))})]})]})})]})}):null}function tn({filter:t,onUpdate:n,onRemove:a}){return e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-muted px-2 py-1.5 text-sm",children:[e.jsx("span",{className:"truncate",title:t.column,children:t.title}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(s.CustomFilterPopover,{filter:t,variant:"inline",onAccept:r=>n(r),trigger:e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0",title:"Configure filter",children:e.jsx(s.Settings2,{className:"h-3 w-3"})})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0 hover:bg-destructive/10 hover:text-destructive",onClick:a,children:e.jsx(s.X,{className:"h-3 w-3"})})]})]})}function Ls(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var i,c;return(c=(i=d.card)==null?void 0:i.preferences)==null?void 0:c.chartOptions}),a=s.getChartGridStyle(n),{setChartGrid:r}=s.useEditorActions();function o(){const d=["xy","none","x","y"],c=(d.indexOf(a)+1)%d.length;r(d[c])}return e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(Zt,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsx(e.Fragment,{}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:o,children:[(a==="xy"||!a)&&e.jsx(s.Grid3x3,{className:"size-4"}),a==="x"&&e.jsx(Ss,{className:"size-4"}),a==="y"&&e.jsx(He,{className:"size-4"}),a==="none"&&e.jsx(At,{className:"size-4"})]}),e.jsx(sn,{}),e.jsx(en,{})]})}function nn(){const t=s.useEditorStore(m=>m.frame),n=s.useEditorStore(m=>m.card),{setFrame:a,setActiveTabCardId:r,setCard:o,updateCardInFrame:d}=s.useEditorActions(),i=(m,f)=>{m.dataTransfer.setData("tabIndex",f.toString())},c=m=>{m.preventDefault()},l=(m,f)=>{const v=m.dataTransfer.getData("tabIndex");if(v===f.toString())return;const C=Array.from(t.cards),[A]=C.splice(parseInt(v),1);C.splice(f,0,A),a({...t,cards:C})};function u(m){const f=t.cards.filter(A=>A.id!==m),v=f[0],C={...t,cards:f,activeCardId:v.id};a(C),r(v.id),o(v)}function x(m,f){const v={...t,cards:[...t.cards,f],activeCardId:m.id};a(v),r(f.id)}function h(){const m={...n,id:s.v4(),title:`${n.title} Copy`,tabTitle:`${n.tabTitle||n.title} Copy`};x(n,m)}function g(m){const f={dataSource:m.dataSource,connectionId:m.connectionId,lastSelectedDatabase:m.lastSelectedDatabase,lastSelectedSchema:m.lastSelectedSchema,lastSelectedTable:m.lastSelectedTable,lastSelectedDatamodelId:m.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};x(m,f)}function k(m,f){return m.cards.length===1&&(f.displayTab===!0||f.displayTab===void 0)||m.activeCardId!==f.id&&(f.displayTab===!0||f.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const v=f.displayTab===void 0?!1:!f.displayTab;o({...f,displayTab:v}),d({...f,displayTab:v})},children:f.displayTab===!0||f.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(mt,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((m,f)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:v=>i(v,f),onDragOver:c,onDrop:v=>l(v,f),className:"",value:m.id,children:[k(t,m),e.jsx(s.Editable,{enabled:t.activeCardId===m.id,text:m.tabTitle||m.title,onSave:v=>{o({...n,tabTitle:v}),d({...n,tabTitle:v})},children:m.tabTitle||m.title},m.id),t.activeCardId===m.id&&e.jsx(s.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:v=>{v.stopPropagation(),h()}}),t.activeCardId===m.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(m.id)})]},m.id)),e.jsx(s.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>g(n),children:e.jsx(s.Plus,{className:"h-4 w-4"})})]})})}function Ue(){const t=s.useEditorStore(v=>v.frame),n=s.useEditorStore(v=>v.card),a=s.useEditorStore(v=>v.isSqlRunning),r=s.useEditorStore(v=>v.isDevMode),{setFrame:o,setActiveTabCardId:d,setCard:i,setIsDevMode:c,setRunSql:l}=s.useEditorActions(),{data:u,isLoading:x,isFetching:h,isError:g}=s.useDashboardCardQuery(n);function k(v){const C=t.cards.find(A=>A.id===v);if(C!=null&&C.sql){r||c(!0),d(v);return}if(C!=null&&C.queryConfig){r&&c(!1),m(v),d(v);return}r||m(v),d(v)}function m(v){const C={...t,cards:t.cards.map(B=>B.id===n.id?n:B),activeCardId:v};o(C);const A=C.cards.find(B=>B.id===v);A.sql&&l(!0),i(A)}function f(){return n.type==="kpi"?x||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:n,data:u==null?void 0:u.records,isPending:x||h,isError:g})})}):n.type==="text"?x||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):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(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:a,card:n,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Ds,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:k,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(v=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:v.id,children:f()},v.id)),e.jsx(nn,{})]})}function os({children:t}){const n=s.useEditorStore(b=>b.frame),a=s.useEditorStore(b=>b.card),r=s.useEditorStore(b=>b.isDevMode),o=s.useEditorStore(b=>b.isShowingVisual),d=s.useDashboardStore(b=>b.isVisualEditing),i=s.useEditorStore(b=>b.pythonStdOut),c=s.useEditorStore(b=>b.actions.setRunSql),{setFrame:l,setCard:u,setActiveTabCardId:x,runAssistant:h,setIsDevMode:g,setCardPreferences:k}=s.useEditorActions(),{data:m,isLoading:f,isFetching:v,errorMessage:C,refetch:A,pagination:B}=s.useDashboardCardQuery(a),O=D.useMemo(()=>(m==null?void 0:m.records)||[],[m==null?void 0:m.records]),[E,N]=D.useState(!1);D.useEffect(()=>{v||N(!1)},[v]);function p(b,I){var L,w;const F={...a,paginationConfig:{page:b+1,pageSize:I}};u(F);const T={...n,cards:n.cards.map(R=>R.id===a.id?F:R)};l(T),a.sql&&((w=(L=a.preferences)==null?void 0:L.tablePrefs)!=null&&w.enableDevModePagination)&&c(!0)}function j(b){var L,w,R,K;const I=s.sortStateToSortByColumns(b,(L=a.config)==null?void 0:L.metricColumns,(w=a.config)==null?void 0:w.groupByColumns),F={...a,config:{...a.config||{},sortByColumns:I}};u(F);const T={...n,cards:n.cards.map(_=>_.id===a.id?F:_)};l(T),a.sql&&((K=(R=a.preferences)==null?void 0:R.tablePrefs)!=null&&K.enableDevModePagination)&&c(!0)}function S(){const b=JSON.stringify(m==null?void 0:m.records,null,2),I=new Blob([b],{type:"application/json"}),F=URL.createObjectURL(I),T=document.createElement("a");T.href=F,T.download=`${a.title}.json`,T.click()}function M(){const I=[Object.keys(m==null?void 0:m.records.reduce((w,R)=>({...w,...R}),{})).join(","),...((m==null?void 0:m.records)||[]).map(w=>Object.values(w).join(","))].join(`
199
- `),F=new Blob([I],{type:"text/csv"}),T=URL.createObjectURL(F),L=document.createElement("a");L.href=T,L.download=`${a.title}.csv`,L.click()}function y(){const b=`Can you get the documentation for ${a.type} chart?`;h(b)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[o&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(Ms,{}),d&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:y,children:e.jsx(ct,{className:"size-4"})}),!["table","custom"].includes(a.type)&&d&&e.jsx(Ht,{})]}),!o&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:M,children:e.jsx(s.PiFileCsv,{className:"size-4"})}),e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:S,children:e.jsx(xt,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.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:[t,e.jsx(s.IconButton,{tooltip:"Refresh",disabled:f||v,onClick:()=>{N(!0),A()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":E})})}),e.jsx(Ls,{})]}),r&&e.jsx(rn,{})]}),o?e.jsx(Ue,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[i&&e.jsxs(e.Fragment,{children:[e.jsx(s.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(an,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":i}),children:[(m==null?void 0:m.records)&&(m==null?void 0:m.records.length)>0&&e.jsx(s.TableVisual,{card:a,data:O,paginationMetadata:B,onPaginationChange:p,onSortChange:j,isLoading:f||v}),C&&e.jsx(Xt,{error:C})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function an(){const t=s.useEditorStore(a=>a.pythonStdOut);if(!t)return null;const n=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:n}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function rn(){const t=s.useEditorStore(a=>a.isShowingVisual),n=s.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs(s.Toggle,{pressed:!t,onPressedChange:()=>n(!t),variant:"outline",size:"sm",className:"h-8 gap-2",children:[e.jsx(s.Table2,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:"Results"})]})}function ce({value:t,onCommit:n,type:a="text",placeholder:r,className:o}){const[d,i]=D.useState(t),c=D.useRef(!1);D.useEffect(()=>{i(t)},[t]);const l=()=>{if(c.current){c.current=!1;return}d!==t&&n(d)},u=x=>{if(x.key==="Enter"){x.currentTarget.blur();return}x.key==="Escape"&&(c.current=!0,i(t),x.currentTarget.blur())};return e.jsx(s.Input$1,{type:a,placeholder:r,value:d,onChange:x=>i(x.target.value),onBlur:l,onKeyDown:u,className:o})}function he({defaultValue:t,label:n,options:a,value:r,onValueChange:o,className:d,icon:i,showPlaceholderLabel:c=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:o,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",d),children:e.jsxs("div",{className:"flex items-center gap-2",children:[i&&e.jsx("span",{children:i}),c&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(l=>e.jsx(s.SelectItem,{value:l.value,children:l.label},l.value))]})})]})}const ln={table:({children:t})=>e.jsx("table",{className:"my-3 w-full border-collapse overflow-hidden rounded-md border border-border text-sm",children:t}),thead:({children:t})=>e.jsx("thead",{className:"bg-muted",children:t}),th:({children:t})=>e.jsx("th",{className:"border border-border px-3 py-2 text-left font-medium",children:t}),td:({children:t})=>e.jsx("td",{className:"border border-border px-3 py-2",children:t}),code:({children:t,className:n})=>(n==null?void 0:n.includes("language-"))?e.jsx("pre",{className:"my-3 overflow-x-auto rounded-md bg-muted p-3 text-xs",children:e.jsx("code",{children:t})}):e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:t}),pre:({children:t})=>e.jsx(e.Fragment,{children:t})};function Fs(){var f,v;const t=s.useEditorStore(C=>C.card.customCardPreferences),{data:n}=s.usePluginQuery(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(C=>C.card),o=s.useEditorStore(C=>C.frame),d=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:i}=s.useEditorActions(),{components:c,manifest:l}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(f=l==null?void 0:l.visuals)==null?void 0:f.find(C=>C.name===(t==null?void 0:t.componentName));function x(C,A){if(!t)return;const O={...(t==null?void 0:t.dataInputCardIds)||{},[C]:{cardId:A,hookRef:null}};i({...t,dataInputCardIds:O})}function h(C){var B,O;const A=(B=o==null?void 0:o.cards)==null?void 0:B.filter(E=>{var N;return((N=E==null?void 0:E.customCardPreferences)==null?void 0:N.visualType)!=="multiple"}).map(E=>({value:E.id,label:E.tabTitle||E.title}));return e.jsx("div",{className:"space-y-2",children:(O=C==null?void 0:C.dataInputs)==null?void 0:O.map((E,N)=>{var p,j;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:E}),e.jsx(he,{className:"col-span-6 h-8 w-full justify-between",label:"",options:A||[],value:((j=(p=t==null?void 0:t.dataInputCardIds)==null?void 0:p[N])==null?void 0:j.cardId)||"",onValueChange:S=>x(N,S)})]},N+Math.random())})})}function g(C,A,B=[],O=""){var E,N;return t?C==="input"?e.jsx(ce,{className:`h-8 w-full ${s.removeRing}`,value:String(((E=t==null?void 0:t.settings)==null?void 0:E[A])??O??""),onCommit:p=>{i({...t,settings:{...t==null?void 0:t.settings,[A]:p}})}},A):C==="select"?e.jsx(he,{className:"h-8 w-full",label:"",options:B,value:((N=t==null?void 0:t.settings)==null?void 0:N[A])||O,onValueChange:p=>{i({...t,settings:{...t==null?void 0:t.settings,[A]:p}})}}):null:null}function k(C){const A=Object.entries((C==null?void 0:C.settings)||{});return e.jsx("div",{className:"space-y-3",children:A.map(([B,O])=>{var E;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:O.title}),((E=O.docs)==null?void 0:E.description)&&e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:O.docs.description})})]})})]}),g(O.ui,B,O.options,O.defaultValue)]},B)})})}function m(C){t&&i({...t,visualType:C,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"",children:[e.jsxs(s.AccordionItem,{value:"plugin-settings",children:[e.jsx(s.AccordionTrigger,{children:"Plugin"}),e.jsx(s.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(he,{icon:e.jsx(Ns,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(t==null?void 0:t.url)||"",onValueChange:C=>i({...t||{url:"",componentName:""},url:C})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:d,onValueChange:m,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:c&&e.jsx(he,{icon:e.jsx(ut,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(c==null?void 0:c.filter(C=>C.type===d).map(C=>({value:C.name,label:C.name})))||[],value:t.componentName,onValueChange:C=>{console.log("changing value",C),i({...t,componentName:C})}})})]})})]}),((v=r==null?void 0:r.customCardPreferences)==null?void 0:v.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:(u==null?void 0:u.name)||"Settings"}),(u==null?void 0:u.docs)&&e.jsxs(s.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,onClick:C=>C.stopPropagation(),children:e.jsx(s.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground transition-colors hover:text-foreground"})}),e.jsx(s.HoverCardContent,{side:"right",align:"start",className:"max-h-[40vh] w-[500px] overflow-y-auto text-left",children:e.jsxs("div",{className:"space-y-4 text-left",children:[u.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:u.docs.description}),u.docs.dataSchema&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Data Schema"}),e.jsx("div",{className:"prose prose-sm dark:prose-invert prose-pre:bg-muted prose-pre:text-xs max-w-none",children:e.jsx(s.Markdown,{remarkPlugins:[s.remarkGfm],components:ln,children:u.docs.dataSchema})})]}),u.docs.useCases&&u.docs.useCases.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Use Cases"}),e.jsx("ul",{className:"space-y-1 text-sm",children:u.docs.useCases.map((C,A)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:C})]},A))})]})]})})]})]})}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:k(u)})})]})]})]})}function Se(){const[t,n]=D.useState([]),a=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:o}=s.useEditorStore(u=>u.actions),d=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var x;return(x=u.card.preferences)==null?void 0:x.filterOnClickColumnIndex}),D.useEffect(()=>{d&&n(new Array(d.length).fill(!1))},[d]);function i(u,x){var h,g;x?a!=null&&a.onClickFilter&&((h=a==null?void 0:a.onClickFilter)==null?void 0:h.length)>0?o({...a,onClickFilter:[...a.onClickFilter,{columnIndex:u,expression:""}]}):o({...a,onClickFilter:[{columnIndex:u,expression:""}]}):(o({...a,onClickFilter:(g=a==null?void 0:a.onClickFilter)==null?void 0:g.filter(k=>k.columnIndex!==u)}),n(k=>{const m=[...k];return m[u]=!1,m}))}function c(u,x){var g;const h=(g=a==null?void 0:a.onClickFilter)==null?void 0:g.map(k=>k.columnIndex===u?{...k,expression:x.target.value}:k);o({...a,onClickFilter:h})}function l(u){var x,h,g,k;if(t!=null&&t[u]||(h=(x=a==null?void 0:a.onClickFilter)==null?void 0:x.find(m=>m.columnIndex===u))!=null&&h.expression)return e.jsx(s.Input$1,{value:(k=(g=a==null?void 0:a.onClickFilter)==null?void 0:g.find(m=>m.columnIndex===u))==null?void 0:k.expression,onChange:m=>c(u,m),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.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:d==null?void 0:d.map((u,x)=>{var h,g;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(s.Checkbox,{checked:!!((h=a==null?void 0:a.onClickFilter)!=null&&h.find(k=>k.columnIndex===x)),onCheckedChange:k=>i(x,k)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((g=a==null?void 0:a.onClickFilter)==null?void 0:g.find(k=>k.columnIndex===x))&&e.jsx(s.Pencil,{onClick:()=>{n(k=>{const m=[...k];return m[x]=!k[x],m})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),l(x)]})},u)})})}function on({idx:t}){var c;const n=s.useEditorStore(l=>{var u;return(u=l.card)==null?void 0:u.preferences}),a=s.useEditorStore(l=>{var u;return(u=l.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(l=>l.actions.setCardPreferences),o=(c=n==null?void 0:n.chartOptions)==null?void 0:c.indexAxis,d=a==null?void 0:a.find(l=>l.idx===t);function i(l,u){(l==="end"||l==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const x={display:l!=="none",align:l,anchor:l,clamp:!0};if(!d)r({...n,datasetOptions:[...a||[],{idx:u,datalabels:x}]});else{const h={...d};h.datalabels=x;const g=a==null?void 0:a.map(k=>k.idx===u?h:k);r({...n,datasetOptions:g})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(s.Tag,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>i("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>i("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(vt,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>i("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ct,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>i("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Nt,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})})]})})]})}function cn(){const t=s.useEditorStore(d=>d.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(d=>!s.METADATA_KEYS.includes(d));let o=r;if(["stackedBar","stackedLine"].includes(t.type)){const d=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:i}=s.getKeys(d);o=i.slice(1)}return{transformedMetricKeys:o,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}function Qe({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",n),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Bs(){const t=s.useEditorStore(l=>l.card),n=s.useEditorStore(l=>{var u,x,h;return(h=(x=(u=l==null?void 0:l.card)==null?void 0:u.preferences)==null?void 0:x.chartOptions)==null?void 0:h.indexAxis}),{data:a}=s.useDashboardCardQuery(t),r=n==="y"?"Metric":"Dimension",o=n==="y"?"Dimension":"Metric",{dimensionKeys:d,transformedMetricKeys:i,keys:c}=cn();return c.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:d.map(l=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:l,children:Os(l)},l))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:o}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:i.map((l,u)=>e.jsx(Rs,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:l,idx:u},l))})]})]})}function Os(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function Rs({col:t,idx:n,className:a,iconClassName:r,children:o}){const d=s.useEditorStore(x=>{var h;return(h=x.card)==null?void 0:h.preferences}),i=s.useEditorStore(x=>{var h,g;return(g=(h=x.card)==null?void 0:h.preferences)==null?void 0:g.datasetOptions}),c=i==null?void 0:i.find(x=>x.idx===n),{setCardPreferences:l}=s.useEditorStore(x=>x.actions);function u(x){if(!c)l({...d,datasetOptions:[...i||[],{idx:n,type:x==="area"?"line":x,fill:x==="area"?"origin":""}]});else{const h={...c};h.type=x==="area"?"line":x,h.fill=x==="area"?"origin":"";const g=i==null?void 0:i.map(k=>k.idx===n?h:k);l({...d,datasetOptions:g})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[o||e.jsx(Qe,{className:"max-w-[100px]",title:t,children:Os(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>u("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>u("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>u("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(on,{idx:n})]})]})}function Me(){const t=s.useDashboardStore(c=>c.dashboard.filters),n=s.useEditorStore(c=>c.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:o}=s.useAssignFilter();function d(c){const l=o(c,"frame");a({...n,filterId:l})}const i=t==null?void 0:t.find(c=>c.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(dn,{onSelect:d,columns:r}),i&&e.jsx(s.FilterHeader,{filter:i})]})}function dn({columns:t,onSelect:n}){var i;const[a,r]=qe.useState(!1),[o,d]=qe.useState("");return e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[o?(i=t.find(c=>c.column_name===o))==null?void 0:i.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(c=>e.jsxs(s.CommandItem,{value:c.column_name,onSelect:l=>{const u=l===o?"":l;d(u),r(!1),u&&n(c)},children:[c.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",o===c.column_name?"opacity-100":"opacity-0")})]},c.column_name))})]})]})})]})}function un({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.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:n=>n.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(Bs,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(Me,{})]})]})]})})}function mn({cardType:t}){function n(a){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:a==="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"}),a==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:d=>d.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(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:n(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(Me,{})]})]})]})})}function Ps(){const t=s.useEditorStore(c=>c.card.type),n=s.useEditorStore(c=>c.isDevMode),a=s.useEditorStore(c=>c.card.preferences),{setCardPreferences:r}=s.useEditorStore(c=>c.actions);function o(c){var x;const l={datalabels:{display:c!=="none",align:c,anchor:c,clamp:!0}},u={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(x=a==null?void 0:a.chartOptions)==null?void 0:x.plugins,...l}}};r(u)}function d(){var c,l,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(l=(c=a==null?void 0:a.chartOptions)==null?void 0:c.plugins)==null?void 0:l.datalabels)==null?void 0:u.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function i(){var c,l,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(l=(c=a==null?void 0:a.chartOptions)==null?void 0:c.plugins)==null?void 0:l.datalabels)==null?void 0:u.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:n?d():i()})}const xn={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},hn={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function pn(){const t=s.useEditorStore(n=>n.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:fn(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ps,{}),e.jsx(Se,{}),e.jsx(Me,{})]})]})}function fn(t){if(["line","bar"].includes(t))return e.jsxs(e.Fragment,{children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(s.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(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(s.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(xn,null,2)})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(s.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(hn,null,2)})]})]})]});if(t==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.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(t==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.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(t))return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:t==="polarArea"?"Polar":t.charAt(0).toUpperCase()+t.slice(1)})," ","chart query"]})}),e.jsxs(s.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 gn({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(i,c,l){const u=[...t];u[i]={...u[i],[c]:l},n(u)}function o(i){const c=[...t];c.splice(i,1),n(c)}function d(){n([...t,a])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:"Color Range"}),e.jsx(s.Button,{onClick:d,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((i,c)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input$1,{onChange:l=>r(c,"start",l.target.value),value:i.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input$1,{value:i.end,onChange:l=>r(c,"end",l.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input$1,{onChange:l=>r(c,"color",l.target.value),value:i.color,className:s.cn(`h-7 min-w-14 p-0 ${s.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:s.colors.green[600]}),e.jsx("option",{children:s.colors.red[500]}),e.jsx("option",{children:s.colors.yellow[400]}),e.jsx("option",{children:s.colors.orange[500]})]}),e.jsx(s.Button,{onClick:()=>o(c),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},c))]})}function jn(){var x,h,g,k,m;const t=s.useEditorStore(f=>f.card.preferences),n=s.useEditorStore(f=>f.actions.setCardPreferences),a=s.useEditorStore(f=>f.card),r=s.hasValidCardConfig(a.config),o=s.useEditorStore(f=>f.actions.setNumberFormat);s.useEditorStore(f=>{var v,C;return(C=(v=f.card.preferences)==null?void 0:v.formatNumber)==null?void 0:C.decimalPlaces});const d=s.useEditorStore(f=>{var v,C;return(C=(v=f.card.preferences)==null?void 0:v.formatNumber)==null?void 0:C.locale}),i=s.useEditorStore(f=>{var v,C;return(C=(v=f.card.preferences)==null?void 0:v.formatNumber)==null?void 0:C.currency});s.useEditorStore(f=>f.actions.setFilterOnClickField);const c=s.useEditorStore(f=>{var v,C;return(C=(v=f.card.preferences)==null?void 0:v.formatNumber)==null?void 0:C.colorRanges})||[],l=s.useEditorStore(f=>f.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(f=>f.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((x=t==null?void 0:t.formatNumber)!=null&&x.enabled),onCheckedChange:f=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:f}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:d||"none",onValueChange:f=>{var v,C,A;return o(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,((C=t==null?void 0:t.formatNumber)==null?void 0:C.currency)||"",f,((A=t==null?void 0:t.formatNumber)==null?void 0:A.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Format"}),e.jsx(s.SelectItem,{value:"none",children:"Auto"},"none"),s.LOCALE_CURRENCY_PAIRS.map(f=>e.jsx(s.SelectItem,{value:f.locale,children:f.locale},f.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:i||"none",onValueChange:f=>{var v,C,A;console.log("currency",f),o(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,f==="none"?"":f,((C=t==null?void 0:t.formatNumber)==null?void 0:C.locale)||"",((A=t==null?void 0:t.formatNumber)==null?void 0:A.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),u.map(f=>e.jsx(s.SelectItem,{value:f,children:f},f))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Decimals"}),e.jsxs(s.Select,{value:((k=(g=t==null?void 0:t.formatNumber)==null?void 0:g.decimalPlaces)==null?void 0:k.toString())||"0",onValueChange:f=>{var v,C,A;return o(Number(f),((v=t==null?void 0:t.formatNumber)==null?void 0:v.currency)||"",((C=t==null?void 0:t.formatNumber)==null?void 0:C.locale)||"",((A=t==null?void 0:t.formatNumber)==null?void 0:A.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["0","1","2","3","4"].map(f=>e.jsx(s.SelectItem,{value:f,children:f},f))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input$1,{value:((m=t==null?void 0:t.formatNumber)==null?void 0:m.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:f=>{var v,C,A;return o(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,((C=t==null?void 0:t.formatNumber)==null?void 0:C.currency)||"",((A=t==null?void 0:t.formatNumber)==null?void 0:A.locale)||"",f.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(gn,{colorRanges:c,setColorRanges:l})]})]})}function bn(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{type:"single",collapsible:!0,children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(s.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:t=>t.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(jn,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function Ge({children:t,summary:n,open:a,className:r}){return e.jsxs("details",{open:a,className:s.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(s.Label,{children:n}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const vn=[{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"}],yn=["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"],Nn=yn.map(t=>({label:t,value:t}));function Cn(){var l,u,x,h,g,k,m,f,v,C,A,B,O,E,N,p,j,S;const t=s.useEditorStore(M=>M.card),n=(u=(l=t==null?void 0:t.preferences)==null?void 0:l.mapVisualOptions)==null?void 0:u.topoJsonUrl,[a,r]=D.useState(((h=(x=t==null?void 0:t.preferences)==null?void 0:x.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:o}=s.useEditorActions(),{data:d}=s.useTopoJson(t),i=Object.keys((d==null?void 0:d.objects)||{}).map(M=>({label:M,value:M}))||[],c=[{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(Ge,{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(s.Separator,{className:"my-4"}),e.jsx(Ge,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(he,{className:"h-9",options:c,onValueChange:M=>{console.log("value",M),o({...t.preferences,mapVisualOptions:{topoJsonUrl:M}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input$1,{onChange:M=>{r(M.target.value)},onBlur:()=>{var M;console.log("onBlur",a),o({...t.preferences,mapVisualOptions:{...(M=t.preferences)==null?void 0:M.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),d&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(he,{className:"h-9",options:i,value:((k=(g=t.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:k.objectKey)||"",label:"Map Object",onValueChange:M=>{var y;o({...t.preferences,mapVisualOptions:{...(y=t.preferences)==null?void 0:y.mapVisualOptions,objectKey:M}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(he,{className:"h-9",options:vn,value:((f=(m=t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:f.projection)||"",label:"Projection",onValueChange:M=>{var y;o({...t.preferences,mapVisualOptions:{...(y=t.preferences)==null?void 0:y.mapVisualOptions,projection:M}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(he,{className:"h-9",options:Nn,value:((C=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:C.colorScale)||"",label:"Select Color Scale",onValueChange:M=>{var y;o({...t.preferences,mapVisualOptions:{...(y=t.preferences)==null?void 0:y.mapVisualOptions,colorScale:M}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Ge,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input$1,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((B=(A=t.preferences)==null?void 0:A.mapVisualOptions)==null?void 0:B.projectionScale)||1,onChange:M=>{var y;o({...t.preferences,mapVisualOptions:{...(y=t.preferences)==null?void 0:y.mapVisualOptions,projectionScale:Number(M.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input$1,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((N=(E=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:N[0])||0,onChange:M=>{var y,b,I,F;o({...t.preferences,mapVisualOptions:{...(y=t.preferences)==null?void 0:y.mapVisualOptions,projectionOffset:[Number(M.target.value),((F=(I=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:F[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input$1,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((S=(j=(p=t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:j.projectionOffset)==null?void 0:S[1])||0,onChange:M=>{var y,b,I,F;o({...t.preferences,mapVisualOptions:{...(y=t.preferences)==null?void 0:y.mapVisualOptions,projectionOffset:[((F=(I=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:F[0])||0,Number(M.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Se,{})]})}function Sn(){var r;const t=s.useEditorStore(o=>o.card.preferences),{setCardPreferences:n}=s.useEditorStore(o=>o.actions);function a(o){n({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:o==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:a,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.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(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Oe({cardType:t,docContent:n,suffix:a="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${a}`}),e.jsx(s.AccordionContent,{children:n||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."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(Sn,{})})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(Me,{})]})]})]})})}function wn(){const t=s.useEditorStore(r=>{var o,d;return(d=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:d.sortChart}),{setSortChart:n}=s.useEditorActions();function a(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(he,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{n(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.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(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[a(),e.jsx(Bs,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(Me,{})]})]})]})})}function kn({cardType:t="table"}){console.log("cardType",t);const n=s.useEditorStore(o=>{var d;return(d=o.card)==null?void 0:d.preferences}),a=s.useEditorStore(o=>o.actions.setCardPreferences),r=o=>{a({...n,allowDownload:o})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(Me,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.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"})]})]})}function Vs({color:t,onColorChange:n,onClose:a}){const[r,o]=D.useState(0),[d,i]=D.useState(100),[c,l]=D.useState(50),[u,x]=D.useState(t);D.useEffect(()=>{const v=is(t);if(v){const C=cs(v.r,v.g,v.b);o(C.h),i(C.s),l(C.l),x(t)}},[t]);const h=v=>{o(v),k(v,d,c)},g=v=>{const C=v.currentTarget.getBoundingClientRect(),A=Math.max(0,Math.min(1,(v.clientX-C.left)/C.width)),B=Math.max(0,Math.min(1,(v.clientY-C.top)/C.height)),O=A*100,E=(1-B)*100;i(O),l(E),k(r,O,E)},k=(v,C,A)=>{const B=En(v,C,A),O=Tn(B.r,B.g,B.b);x(O)},m=v=>{if(x(v),/^#[0-9A-Fa-f]{6}$/.test(v)){const C=is(v);if(C){const A=cs(C.r,C.g,C.b);o(A.h),i(A.s),l(A.l)}}},f=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(n(u),a())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:g,onMouseMove:v=>{v.buttons===1&&g(v)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${d}%`,top:`${100-c}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:v=>h(Number(v.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"HEX"}),e.jsx(s.Input$1,{value:u,onChange:v=>m(v.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:u}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:a,children:"Cancel"}),e.jsx(s.Button,{onClick:f,children:"OK"})]})]})}function is(t){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function Tn(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function cs(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),o=Math.min(t,n,a);let d=0,i=0;const c=(r+o)/2;if(r!==o){const l=r-o;switch(i=c>.5?l/(2-r-o):l/(r+o),r){case t:d=((n-a)/l+(n<a?6:0))/6;break;case n:d=((a-t)/l+2)/6;break;case a:d=((t-n)/l+4)/6;break}}return{h:Math.round(d*360),s:Math.round(i*100),l:Math.round(c*100)}}function En(t,n,a){t/=360,n/=100,a/=100;let r,o,d;if(n===0)r=o=d=a;else{const i=(u,x,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?u+(x-u)*6*h:h<.5?x:h<.6666666666666666?u+(x-u)*(.6666666666666666-h)*6:u),c=a<.5?a*(1+n):a+n-a*n,l=2*a-c;r=i(l,c,t+1/3),o=i(l,c,t),d=i(l,c,t-1/3)}return{r:Math.round(r*255),g:Math.round(o*255),b:Math.round(d*255)}}const An=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function zs(){var B,O,E,N,p,j,S,M,y,b;const t=s.useEditorStore(I=>I.card),n=s.useEditorStore(I=>{var F;return(F=I.card)==null?void 0:F.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),{data:o}=s.useDashboardCardQuery(t),[d,i]=D.useState({}),[c,l]=D.useState(null),[u,x]=D.useState(null),h=D.useMemo(()=>{var L,w,R,K,_,G,q;if(!(o!=null&&o.records)||o.records.length===0)return[];const I=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",F=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line"||(t==null?void 0:t.type)==="horizontalBar"||(t==null?void 0:t.type)==="bullet",T=((L=t==null?void 0:t.config)==null?void 0:L.pivotByColumns)&&t.config.pivotByColumns.length>0;if((I||F)&&T){if(o.pivotSchema&&Array.isArray(o.pivotSchema)){const V=new Set;return o.pivotSchema.forEach(z=>{z.alias&&V.add(z.alias)}),Array.from(V)}if(o.records.length>0){const V=o.records[0],z=Object.keys(V),H=new Set;(w=t==null?void 0:t.config)!=null&&w.groupByColumns&&t.config.groupByColumns.forEach(Y=>{H.add(Y.label||Y.name),H.add(Y.alias||Y.name)});const P=new Set;return(R=t==null?void 0:t.config)!=null&&R.metricColumns&&t.config.metricColumns.forEach(Y=>{const ee=Y.alias||Y.name;P.add(ee),P.add(`${ee}_count`),P.add(`${ee}_sum`),P.add(`${ee}_avg`),P.add(`${ee}_min`),P.add(`${ee}_max`);const J=Y.entityName||Y.qualifiedEntityName;J&&(P.add(`${J}_${ee}`),P.add(`${J}_${ee}_count`))}),z.filter(Y=>!H.has(Y)&&!P.has(Y))}}if((F||I)&&!T&&((_=(K=t==null?void 0:t.config)==null?void 0:K.metricColumns)!=null&&_.length))return t.config.metricColumns.map(V=>V.alias||V.label||V.name);if((q=(G=t==null?void 0:t.config)==null?void 0:G.groupByColumns)!=null&&q.length){const V=t.config.groupByColumns[0],z=V.label||V.name,H=new Set;return o.records.forEach(P=>{const W=P[z];W!=null&&H.add(String(W))}),Array.from(H)}return[]},[o,(B=t==null?void 0:t.config)==null?void 0:B.groupByColumns,(O=t==null?void 0:t.config)==null?void 0:O.pivotByColumns,(E=t==null?void 0:t.config)==null?void 0:E.metricColumns,t==null?void 0:t.type]),g=D.useMemo(()=>s.getDefaultChartColors(),[]);D.useEffect(()=>{const I={};h.forEach((F,T)=>{I[F]=s.getColorForValue(F,T,n==null?void 0:n.colorConfig)}),i(I)},[h,n==null?void 0:n.colorConfig,g]);const k=(I,F)=>{const T={...d,[I]:F};i(T);const L={...n||{},colorConfig:{segments:T}};a(L);const w={...t,preferences:L};r(w)},m=(I,F)=>{var _;const T=g[F%g.length],{[I]:L,...w}=((_=n==null?void 0:n.colorConfig)==null?void 0:_.segments)||{},R={...n||{},colorConfig:{segments:w}};a(R);const K={...t,preferences:R};r(K),i(G=>({...G,[I]:T}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((p=(N=t==null?void 0:t.config)==null?void 0:N.groupByColumns)==null?void 0:p.length)||((S=(j=t==null?void 0:t.config)==null?void 0:j.pivotByColumns)==null?void 0:S.length):(y=(M=t==null?void 0:t.config)==null?void 0:M.groupByColumns)==null?void 0:y.length)||["table","kpi","text","custom","heatmap"].includes(t.type))return null;const C=()=>{const I={...n||{},colorConfig:{segments:{}}};a(I);const F={...t,preferences:I};r(F);const T={};h.forEach((L,w)=>{T[L]=s.getColorForValue(L,w,void 0)}),i(T)},A=Object.keys(((b=n==null?void 0:n.colorConfig)==null?void 0:b.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(St,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(s.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:A&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:C,children:[e.jsx(as,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((I,F)=>{const T=s.isDefaultColor(d[I],F),L=!T;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:c===I,onOpenChange:w=>l(w?I:null),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:d[I]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:g.slice(0,10).map((w,R)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",d[I]===w?"border-gray-900":"border-transparent"),style:{backgroundColor:w},onClick:()=>{k(I,w),l(null)},children:[R===F%g.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:w})]},`default-${R}`))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Popular Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:An.map((w,R)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",d[I]===w?"border-2 border-gray-900":w==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:w},onClick:()=>{k(I,w),l(null)},children:e.jsx("span",{className:"sr-only",children:w})},`preset-${R}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{x({value:I,color:d[I]}),l(null)},children:"Custom color"}),!T&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{m(I,F),l(null)},children:[e.jsx(as,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:I}),L&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},I)})}),u&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>x(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Vs,{color:u.color,onColorChange:I=>{k(u.value,I),x(null)},onClose:()=>x(null)})})]})]})})]})}function pe({value:t,onSave:n,placeholder:a="",type:r="text",className:o=""}){const[d,i]=D.useState(t??""),[c,l]=D.useState(!1);D.useEffect(()=>{i(t??"")},[t]);const u=()=>{n(d),l(!1)},x=()=>{i(t??""),l(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${o}`,children:[e.jsx(s.Input,{placeholder:a,type:r,value:c?d:t??"",onChange:h=>{i(h.target.value),l(!0)},onFocus:()=>l(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&c&&d!==t?u():h.key==="Escape"&&x()},"aria-label":a||"Edit field"}),c&&d!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:x,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const In=["auto","number","currency","percent","scientific","date"],Dn=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"GBP",label:"GBP - British Pound"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"CHF",label:"CHF - Swiss Franc"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"},{value:"HKD",label:"HKD - Hong Kong Dollar"},{value:"SGD",label:"SGD - Singapore Dollar"},{value:"NZD",label:"NZD - New Zealand Dollar"},{value:"SEK",label:"SEK - Swedish Krona"},{value:"NOK",label:"NOK - Norwegian Krone"},{value:"DKK",label:"DKK - Danish Krone"},{value:"KRW",label:"KRW - South Korean Won"},{value:"INR",label:"INR - Indian Rupee"},{value:"RUB",label:"RUB - Russian Ruble"},{value:"BRL",label:"BRL - Brazilian Real"},{value:"MXN",label:"MXN - Mexican Peso"},{value:"TRY",label:"TRY - Turkish Lira"},{value:"ZAR",label:"ZAR - South African Rand"},{value:"SAR",label:"SAR - Saudi Riyal"},{value:"AED",label:"AED - UAE Dirham"},{value:"ARS",label:"ARS - Argentine Peso"},{value:"CLP",label:"CLP - Chilean Peso"},{value:"COP",label:"COP - Colombian Peso"},{value:"THB",label:"THB - Thai Baht"},{value:"IDR",label:"IDR - Indonesian Rupiah"},{value:"MYR",label:"MYR - Malaysian Ringgit"},{value:"PHP",label:"PHP - Philippine Peso"},{value:"PLN",label:"PLN - Polish Zloty"},{value:"NGN",label:"NGN - Nigerian Naira"},{value:"KES",label:"KES - Kenyan Shilling"},{value:"GHS",label:"GHS - Ghanaian Cedi"},{value:"ZMW",label:"ZMW - Zambian Kwacha"},{value:"ZWL",label:"ZWL - Zimbabwean Dollar"},{value:"EGP",label:"EGP - Egyptian Pound"},{value:"MAD",label:"MAD - Moroccan Dirham"},{value:"UAH",label:"UAH - Ukrainian Hryvnia"},{value:"HUF",label:"HUF - Hungarian Forint"},{value:"CZK",label:"CZK - Czech Koruna"},{value:"RON",label:"RON - Romanian Leu"},{value:"PKR",label:"PKR - Pakistani Rupee"},{value:"BDT",label:"BDT - Bangladeshi Taka"},{value:"VND",label:"VND - Vietnamese Dong"},{value:"TWD",label:"TWD - New Taiwan Dollar"},{value:"ILS",label:"ILS - Israeli New Shekel"}],Mn=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"en-IN",label:"English (India)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"},{value:"ja-JP",label:"Japanese"},{value:"ko-KR",label:"Korean"},{value:"ru-RU",label:"Russian"},{value:"ar-SA",label:"Arabic"},{value:"hi-IN",label:"Hindi"},{value:"nl-NL",label:"Dutch"},{value:"sv-SE",label:"Swedish"}],Ln=t=>t.charAt(0).toUpperCase()+t.slice(1);function Ye({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const o=t.type||"auto",d=(c,l)=>{n({...t,[c]:l})},i=()=>o==="currency"?2:o==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:o,onValueChange:c=>d("type",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:In.map(c=>e.jsx(s.SelectItem,{value:c,className:"text-xs",children:c==="auto"?"Auto (Default)":Ln(c)},c))})]})]}),o!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(o)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??i(),onChange:c=>d("decimalPlaces",parseInt(c.target.value)||0),className:"h-8 text-xs"})})]}),o==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:c=>d("currency",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Dn.map(c=>e.jsx(s.SelectItem,{value:c.value,className:"text-xs",children:c.label},c.value))})]})]}),["number","currency"].includes(o)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:c=>d("useSuffix",c)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:c=>d("locale",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Mn.map(c=>e.jsx(s.SelectItem,{value:c.value,className:"text-xs",children:c.label},c.value))})]})]}),o==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{placeholder:"e.g., $",value:t.prefix||"",onChange:c=>d("prefix",c.target.value),className:"h-8 text-xs"})})]}),o==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{placeholder:"e.g., units",value:t.suffix||"",onChange:c=>d("suffix",c.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(o)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:c=>d("negativeInParentheses",c)})]}),o==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:c=>d("multiplyBy",c.target.value?parseFloat(c.target.value):void 0),className:"h-8 text-xs"})})]}),o==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:c=>d("dateFormat",c.target.value),className:"h-8 text-xs"})})]})]})]})}function ds({axis:t,label:n,type:a,config:r,onChange:o}){var h,g,k,m,f,v,C,A,B,O,E,N;const d=(p,j)=>{o({...r,[p]:j})},i=(p,j)=>{var S,M;o({...r,name:{enabled:p==="enabled"?j:((S=r==null?void 0:r.name)==null?void 0:S.enabled)??!1,text:p==="text"?j:(M=r==null?void 0:r.name)==null?void 0:M.text}})},c=(p,j)=>{var S,M;o({...r,labels:{enabled:p==="enabled"?j:((S=r==null?void 0:r.labels)==null?void 0:S.enabled)??!0,rotation:p==="rotation"?j:(M=r==null?void 0:r.labels)==null?void 0:M.rotation}})},l=(p,j)=>{o({...r,scale:{...r==null?void 0:r.scale,[p]:j===""?"auto":Number(j)}})},u=t==="x"?["auto","top","bottom"]:["auto","left","right"],x=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:n})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:p=>d("enabled",p),onClick:p=>p.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:p=>i("enabled",p)})]}),((g=r==null?void 0:r.name)==null?void 0:g.enabled)&&e.jsx(pe,{placeholder:`${n} title`,value:((k=r==null?void 0:r.name)==null?void 0:k.text)||"",onSave:p=>i("text",p),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:p=>d("position",p),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(p=>e.jsx(s.SelectItem,{value:p,className:"text-xs",children:p==="auto"?"Auto (Default)":s.titleCase(p)},p))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((m=r==null?void 0:r.labels)==null?void 0:m.enabled)!==!1,onCheckedChange:p=>c("enabled",p)})]}),((f=r==null?void 0:r.labels)==null?void 0:f.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((v=r==null?void 0:r.labels)==null?void 0:v.rotation)||"auto"),onValueChange:p=>c("rotation",p==="auto"?"auto":Number(p)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:x.map(p=>e.jsx(s.SelectItem,{value:p,className:"text-xs",children:p==="auto"?"Auto (Default)":`${p}°`},p))})]})]})]}),a==="value"&&e.jsx(Ye,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:p=>o({...r,formatOptions:p}),showTitle:!0,title:"FORMAT"}),a==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"auto",value:((C=r==null?void 0:r.scale)==null?void 0:C.min)==="auto"||((A=r==null?void 0:r.scale)==null?void 0:A.min)===void 0?"":String(r.scale.min),onSave:p=>l("min",p),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"auto",value:((B=r==null?void 0:r.scale)==null?void 0:B.max)==="auto"||((O=r==null?void 0:r.scale)==null?void 0:O.max)===void 0?"":String(r.scale.max),onSave:p=>l("max",p),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"auto",value:((E=r==null?void 0:r.scale)==null?void 0:E.stepSize)==="auto"||((N=r==null?void 0:r.scale)==null?void 0:N.stepSize)===void 0?"":String(r.scale.stepSize),onSave:p=>l("stepSize",p),className:""})})]})]})]})]})]})}function $s(){const t=s.useEditorStore(i=>i.card),n=s.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi","treemap"].includes(t.type))return null;const o=s.AxisConfigurator.getAxisInfo(t.type,n);if(!o.hasXAxis&&!o.hasYAxis)return null;const d=(i,c)=>{const u={...n||{},[i==="x"?"xAxisConfig":"yAxisConfig"]:c};a(u);const x={...t,preferences:u};r(x)};return e.jsxs(s.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ks,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[o.hasXAxis&&e.jsx(ds,{axis:"x",label:"X-Axis",type:o.xAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(t.type,"x"),n==null?void 0:n.xAxisConfig),onChange:i=>d("x",i)}),o.hasYAxis&&e.jsx(ds,{axis:"y",label:"Y-Axis",type:o.yAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(t.type,"y"),n==null?void 0:n.yAxisConfig),onChange:i=>d("y",i)})]})})]})}function Ks(){const t=s.useEditorStore(x=>x.card),n=s.useEditorStore(x=>{var h,g,k,m;return(m=(k=(g=(h=x.card)==null?void 0:h.preferences)==null?void 0:g.chartOptions)==null?void 0:k.plugins)==null?void 0:m.legend}),{setLegendOptions:a}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r=s.getDefaultLegendConfig(t.type),o=(r==null?void 0:r.display)??!0,d=(r==null?void 0:r.position)??"top",i=(r==null?void 0:r.align)??"center",c=(x,h)=>{const g={...n,[x]:h};a(g)},l=["top","bottom","left","right"],u=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.display)??o,onCheckedChange:x=>c("display",x)})]}),((n==null?void 0:n.display)??o)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||d,onValueChange:x=>c("position",x),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:l.map(x=>e.jsx(s.SelectItem,{value:x,className:"text-xs",children:s.titleCase(x)},x))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(n==null?void 0:n.align)||i,onValueChange:x=>c("align",x),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(x=>e.jsx(s.SelectItem,{value:x,className:"text-xs",children:s.titleCase(x)},x))})]})]})]})]})})]})}function Gs(){var T,L,w,R,K,_,G,q,V,z,H;const t=s.useEditorStore(P=>P.card),n=s.useEditorStore(P=>{var W,Y;return(Y=(W=P.card)==null?void 0:W.preferences)==null?void 0:Y.dataLabelsConfig}),a=s.useEditorStore(P=>{var W;return(W=P.card)==null?void 0:W.preferences}),{setCardPreferences:r,updateCardInFrame:o}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const d=t.type==="bullet"?((T=a==null?void 0:a.bulletConfig)==null?void 0:T.orientation)??(((L=a==null?void 0:a.chartOptions)==null?void 0:L.indexAxis)==="x"?"vertical":"horizontal"):void 0,i=d!=null?d==="horizontal":((w=a==null?void 0:a.chartOptions)==null?void 0:w.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",l=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",u=!l,x=t.type==="bubble"||t.type==="scatter",h=(K=(R=a==null?void 0:a.chartOptions)==null?void 0:R.plugins)==null?void 0:K.datalabels,g=(h==null?void 0:h.display)!==!1&&((h==null?void 0:h.anchor)||(h==null?void 0:h.align)),k=s.getDefaultDataLabelsConfig(t.type,t.preferences),m=n??k,f=(k==null?void 0:k.enabled)??g??!1,v=(n==null?void 0:n.enabled)!==void 0?n.enabled:f,C=(P,W)=>{const J={...k??{},...n??{},[P]:W};P==="enabled"&&(J.display=W,W&&x&&!J.position&&(J.position="bottom")),P==="position"&&x&&(J.position="bottom");const ne={...t.preferences||{},dataLabelsConfig:J};r(ne);const le={...t,preferences:ne};o(le)},A=(P,W)=>{const Y=n??{},J={...k??{},...Y,font:{...Y.font||{},[P]:W}},ne={...t.preferences||{},dataLabelsConfig:J};r(ne);const le={...t,preferences:ne};o(le)},B=(P,W)=>{const Y=n??{},J={...k??{},...Y,formatOptions:{...Y.formatOptions||{},[P]:W}},ne={...t.preferences||{},dataLabelsConfig:J};r(ne);const le={...t,preferences:ne};o(le)},O=()=>{const P=t.type;return P==="stackedBar"||P==="stackedLine"||P==="pie"||P==="doughnut"?"center":i?"right":"top"},E=t.type!=="treemap"&&t.type!=="heatmap",N=t.type!=="treemap",p=O();let j=[];if(E)if(x)j=["bottom"];else if(c||l)j=["center"];else{const P=i?["center","left","right"]:["center","top","bottom"];j=["auto",...t.type==="bullet"?P:P.filter(Y=>Y!==p),"custom"]}const S=()=>s.titleCase(p),M=["center","start","end"],y=["center","start","end","top","bottom"],b=u?["auto","number","currency","percent","none"]:["number","currency","percent","none"],I=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"}],F=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(It,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:v,onCheckedChange:P=>C("enabled",P)})]}),v&&e.jsxs(e.Fragment,{children:[E&&!c&&!l&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:x?(m==null?void 0:m.position)||"bottom":(m==null?void 0:m.position)||"auto",onValueChange:P=>C("position",P),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:j.map(P=>e.jsx(s.SelectItem,{value:P,className:"text-xs",children:P==="auto"?S():P==="custom"?"Custom (Advanced)":s.titleCase(P)},P))})]})]}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.showTotal)??!1,onCheckedChange:P=>C("showTotal",P)})]}),(m==null?void 0:m.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(s.Select,{value:(m==null?void 0:m.anchor)||"center",onValueChange:P=>C("anchor",P),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:M.map(P=>e.jsx(s.SelectItem,{value:P,className:"text-xs",children:s.titleCase(P)},P))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(s.Select,{value:String((m==null?void 0:m.align)||"center"),onValueChange:P=>C("align",P),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:y.map(P=>e.jsx(s.SelectItem,{value:P,className:"text-xs",children:s.titleCase(P)},P))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(m==null?void 0:m.format)||(u?"auto":"none"),onValueChange:P=>C("format",P),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:b.map(P=>e.jsx(s.SelectItem,{value:P,className:"text-xs",children:P==="auto"&&u?"Auto (Use Axis)":P==="none"?"None (Raw Value)":s.titleCase(P)},P))})]})]}),(m==null?void 0:m.format)&&!["auto","none"].includes(m.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(m.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"0",value:String(((_=m==null?void 0:m.formatOptions)==null?void 0:_.decimalPlaces)??(m.format==="currency"?2:m.format==="percent"?1:0)),onSave:P=>B("decimalPlaces",Number(P)),className:""})})]}),m.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((G=m==null?void 0:m.formatOptions)==null?void 0:G.currency)||"USD",onValueChange:P=>B("currency",P),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:I.map(P=>e.jsx(s.SelectItem,{value:P.value,className:"text-xs",children:P.label},P.value))})]})]}),["number","currency"].includes(m.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((q=m==null?void 0:m.formatOptions)==null?void 0:q.useSuffix)??!1,onCheckedChange:P=>B("useSuffix",P)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Locale"}),e.jsxs(s.Select,{value:((V=m==null?void 0:m.formatOptions)==null?void 0:V.locale)||"en-US",onValueChange:P=>B("locale",P),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:F.map(P=>e.jsx(s.SelectItem,{value:P.value,className:"text-xs",children:P.label},P.value))})]})]})]}),N&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"12",value:String(((z=m==null?void 0:m.font)==null?void 0:z.size)||12),onSave:P=>A("size",Number(P)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(s.Select,{value:((H=m==null?void 0:m.font)==null?void 0:H.weight)||"normal",onValueChange:P=>A("weight",P),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(s.Select,{value:(m==null?void 0:m.color)==="auto"||!(m!=null&&m.color)?"auto":"custom",onValueChange:P=>{P==="auto"&&C("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"0",value:String((m==null?void 0:m.rotation)||0),onSave:P=>C("rotation",Number(P)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const us=["poor","satisfactory","good"];function ms(t){if(!t)return;const n={...t};return n.targetMetricKey||delete n.targetMetricKey,n.comparativeMetricKey||delete n.comparativeMetricKey,!n.targetValue&&n.targetValue!==0&&delete n.targetValue,(!n.rangeKeys||Object.keys(n.rangeKeys).length===0)&&delete n.rangeKeys,(!n.ranges||Object.keys(n.ranges).length===0)&&delete n.ranges,(!n.rangeLabels||Object.keys(n.rangeLabels).length===0)&&delete n.rangeLabels,n}function qs(){var I,F;const t=s.useEditorStore(T=>T.card.preferences),n=s.useEditorStore(T=>T.card),a=s.useEditorStore(T=>T.isDevMode),{setCardPreferences:r,setChartOrientation:o}=s.useEditorActions(),d=D.useMemo(()=>(t==null?void 0:t.bulletConfig)||{},[t==null?void 0:t.bulletConfig]),c=s.hasValidCardConfig(n==null?void 0:n.config)&&!a,[l,u]=D.useState(d.showRanges??!1),[x,h]=D.useState(d.rangesArePercentages??!1),g=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!c,[k,m]=D.useState(g);D.useEffect(()=>{u(d.showRanges??!1)},[d.showRanges]),D.useEffect(()=>{h(d.rangesArePercentages??!1)},[d.rangesArePercentages]);const f=d.targetValue===void 0?"":String(d.targetValue);D.useEffect(()=>{const T=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!c;m(T)},[d.disableAutoComparative,d.comparativeMetricKey,c]);const v=D.useMemo(()=>{var T,L;return((L=(T=n==null?void 0:n.config)==null?void 0:T.metricColumns)==null?void 0:L.map(w=>{const R=w.label||w.name||w.alias||"";return{value:R,label:R}}))||[]},[(I=n==null?void 0:n.config)==null?void 0:I.metricColumns]);D.useEffect(()=>{var q,V;if(!t||v.length===0)return;const T={};let L=!1;const w=(q=v[1])==null?void 0:q.value;!d.targetMetricKey&&w&&(T.targetMetricKey=w,L=!0);const R=(V=v[2])==null?void 0:V.value;!d.comparativeMetricKey&&!d.disableAutoComparative&&R&&(T.comparativeMetricKey=R,L=!0);const K=v.slice(3),_={...d.rangeKeys||{}};let G=!1;if(us.forEach((z,H)=>{!_[z]&&K[H]&&(_[z]=K[H].value,G=!0)}),G&&(T.rangeKeys=_,L=!0,d.showRanges===void 0&&(T.showRanges=!0)),L){const z=ms({...d,...T});r({...t,bulletConfig:z})}},[v,d,t,r]);const C=T=>{const L=ms({...d,...T});r({...t,bulletConfig:L})},A=(T,L)=>{const w={...d.rangeKeys||{},[T]:L.trim()};L.trim()||delete w[T],C({rangeKeys:Object.keys(w).length>0?w:void 0})},B=(T,L)=>{const w=L===""?void 0:Number(L),R={...d.ranges||{}};w===void 0||Number.isNaN(w)?delete R[T]:R[T]=w,C({ranges:Object.keys(R).length?R:void 0})},O=T=>{if(T===""){C({targetValue:void 0});return}const L=Number(T);C({targetValue:Number.isNaN(L)?void 0:L})},E=(T,L)=>{const w=L.trim(),R={...d.rangeLabels||{}};w?R[T]=w:delete R[T],C({rangeLabels:Object.keys(R).length>0?R:void 0})},N=T=>{u(T),C({showRanges:T})},p=T=>{h(T),C({rangesArePercentages:T})},j=d.orientation||(((F=t==null?void 0:t.chartOptions)==null?void 0:F.indexAxis)==="y"?"horizontal":"vertical"),S=T=>{C({orientation:T}),o(T==="horizontal"?"y":"x")},M=[{value:"__none",label:"None"},...v.map(T=>({value:T.value,label:T.label}))],y=M,b=T=>{if(m(T),!T){C({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!c){C({disableAutoComparative:!1});return}if(d.comparativeMetricKey)C({disableAutoComparative:!1});else{const L=v.find(w=>w.value!==d.targetMetricKey);C({comparativeMetricKey:L==null?void 0:L.value,disableAutoComparative:!1})}};return e.jsxs(s.AccordionItem,{value:"bullet-config",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-6 border-t border-border/50 py-4",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"ORIENTATION"}),e.jsxs(s.Select,{value:j,onValueChange:T=>S(T),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"horizontal",className:"text-xs",children:"Horizontal"}),e.jsx(s.SelectItem,{value:"vertical",className:"text-xs",children:"Vertical"})]})]})]}),c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TARGET METRIC"}),e.jsxs(s.Select,{value:d.targetMetricKey||"__none",onValueChange:T=>C({targetMetricKey:T==="__none"?void 0:T}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"__none",className:"text-xs",children:"None"}),v.map(T=>e.jsx(s.SelectItem,{value:T.value,className:"text-xs",children:T.label},T.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),c?e.jsxs(s.Select,{value:d.comparativeMetricKey||"__none",onValueChange:T=>C({comparativeMetricKey:T==="__none"?void 0:T,disableAutoComparative:T==="__none"}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsx(s.SelectContent,{children:M.map(T=>e.jsx(s.SelectItem,{value:T.value,className:"text-xs",children:T.label},T.value))})]}):e.jsxs("div",{className:"space-y-2 rounded-md border border-border/50 p-3 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between font-medium",children:[e.jsx("span",{children:"Show comparative"}),e.jsx(s.SmallSwitch,{checked:k,onCheckedChange:T=>b(T)})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparative values are auto-detected from the third metric in your results."})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TARGET VALUE (FALLBACK)"}),e.jsx(ce,{type:"number",className:"h-8 text-xs",value:f,onCommit:O,placeholder:"Optional numeric fallback"})]})]}),e.jsxs("section",{className:"space-y-4 rounded-md border border-border/60 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"QUALITATIVE RANGES"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(s.Info,{className:"h-3.5 w-3.5"})})}),e.jsx(s.TooltipContent,{side:"top",children:"Use columns or static values for Poor / Average / Good."})]})})]}),e.jsx("div",{className:"flex items-center gap-2 text-xs font-medium",children:e.jsx(s.SmallSwitch,{checked:l,onCheckedChange:N})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:x,disabled:!l,onChange:T=>p(T.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),l&&e.jsx("div",{className:"space-y-3",children:us.map(T=>{var L,w,R,K,_;return e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/40 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[T," LABEL"]}),e.jsx(ce,{placeholder:`Display label (${T})`,value:((L=d.rangeLabels)==null?void 0:L[T])||"",onCommit:G=>E(T,G),className:"h-8 text-xs"})]}),c?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[T," COLUMN"]}),e.jsxs(s.Select,{value:((w=d.rangeKeys)==null?void 0:w[T])||"__none",onValueChange:G=>{G==="__none"?A(T,""):A(T,G)},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select column"})}),e.jsx(s.SelectContent,{children:y.map(G=>e.jsx(s.SelectItem,{value:G.value,className:"text-xs",children:G.label},G.value))})]})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[T," COLUMN KEY"]}),e.jsx(ce,{placeholder:"Column key",value:((R=d.rangeKeys)==null?void 0:R[T])||"",onCommit:G=>A(T,G),className:"h-8 text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[T," VALUE"]}),e.jsx(ce,{type:"number",placeholder:x?"0.80":"Static value",value:((K=d.ranges)==null?void 0:K[T])===void 0?"":String((_=d.ranges)==null?void 0:_[T]),onCommit:G=>B(T,G),className:"h-8 text-xs"})]})]},T)})})]})]})]})}const xs=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Fn=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Fe({value:t,onChange:n,label:a}){const[r,o]=D.useState(!1),[d,i]=D.useState(!1),c=()=>{const l=xs.find(u=>u.value===t);return l?l.color:t.startsWith("#")?t:xs[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:o,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:c()},"aria-label":`Change color for ${a}`})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:Fn.map(l=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",c()===l?"border-gray-900":"border-transparent"),style:{backgroundColor:l},onClick:()=>{n(l),o(!1)},children:e.jsx("span",{className:"sr-only",children:l})},l))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{i(!0),o(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),d&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>i(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Vs,{color:c(),onColorChange:l=>{n(l),i(!1)},onClose:()=>i(!1)})})]})]})}const Bn=Object.keys(s.HEATMAP_PRESET_PALETTES);function Us(){const t=s.useEditorStore(g=>g.card),n=s.useEditorStore(g=>{var k;return(k=g.card)==null?void 0:k.preferences}),{setCardPreferences:a}=s.useEditorActions(),r=(t==null?void 0:t.type)==="heatmap",o=(n==null?void 0:n.heatmapConfig)||{},d=o.colorPalette??"green",i=o.legendPosition??"bottom",c=D.useMemo(()=>o.colorRange&&o.colorRange[0]&&o.colorRange[1]?[o.colorRange[0],o.colorRange[1]]:[...s.DEFAULT_HEATMAP_CUSTOM_RANGE],[o.colorRange]),l=g=>{const k={...o,...g};k.colorPalette!=="custom"?delete k.colorRange:(!k.colorRange||!k.colorRange[0]||!k.colorRange[1])&&(k.colorRange=[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]),a({...n||{},heatmapConfig:k})},u=g=>{l({colorPalette:g,colorRange:g==="custom"?o.colorRange??[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},x=(g,k)=>{const m=[...c];m[g]=k,l({colorPalette:"custom",colorRange:m})},h=g=>{l({legendPosition:g})};return r?e.jsxs(s.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(s.RadioGroup,{value:d,onValueChange:g=>u(g??"blue"),className:"space-y-3",children:[Bn.map(g=>{const k=s.HEATMAP_PRESET_PALETTES[g];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`heatmap-${g}`,value:g}),e.jsxs(s.Label,{htmlFor:`heatmap-${g}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:k.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${k.start}, ${k.end})`}})]})]},g)}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(s.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),d==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(Fe,{value:c[0],onChange:g=>x(0,g),label:"Start color"}),e.jsx(Fe,{value:c[1],onChange:g=>x(1,g),label:"End color"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Color scale position"}),e.jsxs(s.Select,{value:i,onValueChange:g=>h(g??"bottom"),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["top","bottom","left","right"].map(g=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:g[0].toUpperCase()+g.slice(1)},g))})]})]})]})]}):null}function hs(t){if(!t)return;const n={...t};if(n.xMetricKey||delete n.xMetricKey,n.yMetricKey||delete n.yMetricKey,n.radiusMetricKey||delete n.radiusMetricKey,n.labelKey||delete n.labelKey,n.groupKey||delete n.groupKey,n.enableGrouping===void 0&&delete n.enableGrouping,n.radiusScale||delete n.radiusScale,n.fixedRadius===void 0&&delete n.fixedRadius,n.minRadius===void 0&&delete n.minRadius,n.maxRadius===void 0&&delete n.maxRadius,Object.keys(n).length!==0)return n}function _s(){var E,N,p,j,S,M,y,b,I,F,T,L;const t=s.useEditorStore(w=>w.card.preferences),n=s.useEditorStore(w=>w.card),a=s.useEditorStore(w=>w.card.type),r=s.useEditorStore(w=>w.isDevMode),{setCardPreferences:o,updateCardInFrame:d}=s.useEditorActions(),i=a==="bubble",c=a==="scatter",l=D.useMemo(()=>(t==null?void 0:t.bubbleScatterConfig)||{},[t==null?void 0:t.bubbleScatterConfig]),x=s.hasValidCardConfig(n==null?void 0:n.config)&&!r,h=D.useMemo(()=>{var w,R;return((R=(w=n==null?void 0:n.config)==null?void 0:w.metricColumns)==null?void 0:R.map(K=>{const _=K.label||K.name||K.alias||"";return{value:_,label:_}}))||[]},[(E=n==null?void 0:n.config)==null?void 0:E.metricColumns]),g=D.useMemo(()=>{var w,R;return((R=(w=n==null?void 0:n.config)==null?void 0:w.groupByColumns)==null?void 0:R.map(K=>{const _=K.label||K.name||K.alias||"";return{value:_,label:_}}))||[]},[(N=n==null?void 0:n.config)==null?void 0:N.groupByColumns]),k=D.useMemo(()=>l.enableGrouping!==void 0?l.enableGrouping:!r&&g.length>=2,[l.enableGrouping,r,g.length]),[m,f]=D.useState(k);D.useEffect(()=>{f(k)},[k]);const v=w=>{const R={...t||{},bubbleScatterConfig:w};o(R),n&&d({...n,preferences:R})},C=w=>{o(w),n&&d({...n,preferences:w})};D.useEffect(()=>{if(!t||h.length===0)return;const w={};let R=!1;if(!l.xMetricKey&&h[0]&&(w.xMetricKey=h[0].value,R=!0),!l.yMetricKey&&h[1]&&(w.yMetricKey=h[1].value,R=!0),i&&!l.radiusMetricKey&&h[2]&&(w.radiusMetricKey=h[2].value,R=!0),!l.labelKey&&g[0]&&(w.labelKey=g[0].value,R=!0),k&&!l.groupKey&&g[1]&&(w.groupKey=g[1].value,w.enableGrouping=!0,R=!0),R){const K=hs({...l,...w});v(K)}},[h,g,l,t,o,i,k]);const A=w=>{const R=hs({...l,...w});v(R)},B=w=>{f(w),A({enableGrouping:w,groupKey:w?l.groupKey:void 0})};if(!i&&!c)return null;const O=i?s.Circle:s.ChartScatter;return e.jsxs(s.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(s.AccordionTrigger,{className:"py-2 text-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{className:"h-4 w-4"}),e.jsxs("span",{children:[i?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-1 pb-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-muted-foreground",children:["Dimensions",e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(s.Info,{className:"h-3 w-3"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{children:"Label identifies each point. Group creates separate series in the legend."})})]})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Label Column"}),x?e.jsxs(s.Select,{value:l.labelKey||"",onValueChange:w=>A({labelKey:w}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select label column"})}),e.jsx(s.SelectContent,{children:g.map(w=>e.jsx(s.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx(ce,{className:"h-8 text-xs",placeholder:"Column name for labels",value:l.labelKey||"",onCommit:w=>A({labelKey:w})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Group points into series"}),e.jsx(s.SmallSwitch,{checked:m,onCheckedChange:B})]}),m&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Group By"}),x?e.jsxs(s.Select,{value:l.groupKey||"",onValueChange:w=>A({groupKey:w}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select group column"})}),e.jsx(s.SelectContent,{children:g.map(w=>e.jsx(s.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx(ce,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:l.groupKey||"",onCommit:w=>A({groupKey:w})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Metrics"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"X Axis"}),x?e.jsxs(s.Select,{value:l.xMetricKey||"",onValueChange:w=>A({xMetricKey:w}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select X metric"})}),e.jsx(s.SelectContent,{children:h.map(w=>e.jsx(s.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx(ce,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:l.xMetricKey||"",onCommit:w=>A({xMetricKey:w})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Axis"}),x?e.jsxs(s.Select,{value:l.yMetricKey||"",onValueChange:w=>A({yMetricKey:w}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(s.SelectContent,{children:h.map(w=>e.jsx(s.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx(ce,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:l.yMetricKey||"",onCommit:w=>A({yMetricKey:w})})]}),i&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Radius"}),x?e.jsxs(s.Select,{value:l.radiusMetricKey||"",onValueChange:w=>A({radiusMetricKey:w}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(s.SelectContent,{children:h.map(w=>e.jsx(s.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx(ce,{className:"h-8 text-xs",placeholder:"Column name for radius",value:l.radiusMetricKey||"",onCommit:w=>A({radiusMetricKey:w})})]})]}),i&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Radius Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Scale Mode"}),e.jsxs(s.Select,{value:l.radiusScale||"sqrt",onValueChange:w=>A({radiusScale:w}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"sqrt",children:"Square Root (area-proportional)"}),e.jsx(s.SelectItem,{value:"linear",children:"Linear"}),e.jsx(s.SelectItem,{value:"fixed",children:"Fixed Size"})]})]})]}),l.radiusScale!=="fixed"&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Min Radius"}),e.jsx(ce,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((p=l.minRadius)==null?void 0:p.toString())||"",onCommit:w=>A({minRadius:w?Number(w):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Max Radius"}),e.jsx(ce,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((j=l.maxRadius)==null?void 0:j.toString())||"",onCommit:w=>A({maxRadius:w?Number(w):void 0})})]})]}),l.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(s.Label,{className:"text-xs",children:["Fixed Radius: ",l.fixedRadius||10]}),e.jsx(s.Slider,{value:[l.fixedRadius||10],onValueChange:([w])=>A({fixedRadius:w}),min:3,max:30,step:1,className:"py-2"})]})]}),c&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Point Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(s.Label,{className:"text-xs",children:["Point Size: ",l.fixedRadius||5]}),e.jsx(s.Slider,{value:[l.fixedRadius||5],onValueChange:([w])=>A({fixedRadius:w}),min:2,max:15,step:1,className:"py-2"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Axis Titles"}),e.jsx(s.SmallSwitch,{checked:((M=(S=t==null?void 0:t.xAxisConfig)==null?void 0:S.name)==null?void 0:M.enabled)??!1,onCheckedChange:w=>{var _,G,q,V;const R=l.xMetricKey||"X Axis",K=l.yMetricKey||"Y Axis";C({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{enabled:w,text:((G=(_=t==null?void 0:t.xAxisConfig)==null?void 0:_.name)==null?void 0:G.text)||R}},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{enabled:w,text:((V=(q=t==null?void 0:t.yAxisConfig)==null?void 0:q.name)==null?void 0:V.text)||K}}})}})]}),((b=(y=t==null?void 0:t.xAxisConfig)==null?void 0:y.name)==null?void 0:b.enabled)&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"X Title"}),e.jsx(ce,{className:"h-8 text-xs",placeholder:l.xMetricKey||"X Axis",value:((F=(I=t==null?void 0:t.xAxisConfig)==null?void 0:I.name)==null?void 0:F.text)||"",onCommit:w=>{var R;C({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{...(R=t==null?void 0:t.xAxisConfig)==null?void 0:R.name,enabled:!0,text:w||l.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Title"}),e.jsx(ce,{className:"h-8 text-xs",placeholder:l.yMetricKey||"Y Axis",value:((L=(T=t==null?void 0:t.yAxisConfig)==null?void 0:T.name)==null?void 0:L.text)||"",onCommit:w=>{var R;C({...t??{},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{...(R=t==null?void 0:t.yAxisConfig)==null?void 0:R.name,enabled:!0,text:w||l.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const On=[{value:"percentOfTotal",label:"% of Total",description:"Each stage shows percentage of the sum of all values"},{value:"percentOfFirst",label:"% of Stage 1",description:"First stage = 100%, others relative to first stage"}];function Hs(){const t=s.useEditorStore(l=>l.card),n=s.useEditorStore(l=>{var u;return(u=l.card)==null?void 0:u.preferences}),{setCardPreferences:a}=s.useEditorActions(),r=(t==null?void 0:t.type)==="funnel",o=(n==null?void 0:n.funnelConfig)||{},d=o.percentMode??"percentOfTotal",i=l=>{const u={...o,...l};a({...n||{},funnelConfig:u})},c=l=>{i({percentMode:l})};return r?e.jsxs(s.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Filter,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Funnel Settings"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"PERCENTAGE MODE"}),e.jsx(s.RadioGroup,{value:d,onValueChange:l=>c(l),className:"space-y-2",children:On.map(l=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`funnel-${l.value}`,value:l.value,className:"mt-0.5"}),e.jsxs(s.Label,{htmlFor:`funnel-${l.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:l.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:l.description})]})]},l.value))})]})})]}):null}function Rn(){const t=s.useEditorStore(n=>n.card);return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[(t==null?void 0:t.type)==="funnel"&&e.jsx(Hs,{}),(t==null?void 0:t.type)==="heatmap"&&e.jsx(Us,{}),(t==null?void 0:t.type)==="bullet"&&e.jsx(qs,{}),((t==null?void 0:t.type)==="bubble"||(t==null?void 0:t.type)==="scatter")&&e.jsx(_s,{}),e.jsx(zs,{}),e.jsx($s,{}),e.jsx(Ks,{}),e.jsx(Gs,{})]})]})}const Pn=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:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),Vn=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:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),zn=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:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function $n(){const t=s.useEditorStore(a=>a.card.type);function n(a){const r=["kpi","table","text","map","custom"],o=d=>r.includes(a)?d:e.jsxs(e.Fragment,{children:[d,e.jsx(Rn,{})]});switch(a){case"stackedBar":case"stackedLine":return o(e.jsx(wn,{}));case"tornado":case"pyramid":return o(e.jsx(Oe,{docContent:Pn,cardType:a}));case"kpi":return e.jsx(bn,{});case"line":case"bar":return o(e.jsx(un,{cardType:a}));case"range":return o(e.jsx(Oe,{docContent:Vn,cardType:a}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return o(e.jsx(Oe,{cardType:a}));case"bubble":case"scatter":return o(e.jsx(mn,{cardType:a}));case"table":return e.jsx(kn,{cardType:a});case"text":return e.jsx(Oe,{docContent:zn,cardType:a,suffix:"Visual"});case"map":return e.jsx(Cn,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Fs,{})});default:return o(e.jsx(pn,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Kn(){const t=D.useRef(null),n=D.useRef(null),a=s.useEditorStore(o=>o.isShowingVisual),r=s.useEditorStore(o=>o.showAIDialog);return D.useEffect(()=>{var o,d,i,c;r?((o=t.current)==null||o.resize(0),(d=n.current)==null||d.resize(0)):((i=t.current)==null||i.resize(25),(c=n.current)==null||c.resize(25))},[r]),e.jsxs(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(zt,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:a&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx($n,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(os,{})})]}):e.jsx(os,{})})]})}function Gn(t){var oe;s.useAIInteractionStore($=>$.currentAIContext);const[n,a]=D.useState(""),[r,o]=D.useState(null),{authToken:d,tokenProps:i}=s.useSemaphorContext(),c=s.useEditorStore($=>{var se;return(se=$==null?void 0:$.card)==null?void 0:se.sql}),l=s.useEditorStore($=>$.isDevMode),u=s.useEditorStore($=>{var se;return(se=$==null?void 0:$.card)==null?void 0:se.python}),{setCardPython:x,setCardSql:h,setRunSql:g,switchCardType:k,setQueryConfig:m}=s.useEditorActions(),f=s.useEditorStore($=>$.currentAssitantScope)||[],v=s.useEditorStore($=>$.userInputForAI),C=s.useEditorStore($=>$.triggerAIRun),A=s.useEditorStore($=>$.card),B=s.useEditorStore($=>$.selectedDatabaseName),O=s.useEditorStore($=>$.selectedTableName),E=s.useEditorStore($=>$.selectedConnectionId),N=s.useEditorStore($=>$.selectedSchemaName),p=s.useDashboardStore($=>$.dashboard.aiScopeTables),{errorMessage:j,refetch:S,data:M}=s.useDashboardCardQuery(A),{setTriggerAIRun:y,setCurrentAssitantScope:b,setCardConfig:I}=s.useEditorActions(),{selectedDatamodelName:F,connectionType:T,selectedDatamodelId:L}=s.useEditorAside(),w=(oe=s.useDashboardQuery().data)==null?void 0:oe.assistantProfileId,{messages:R,setMessages:K,regenerate:_,error:G,sendMessage:q,status:V,addToolResult:z,stop:H,clearError:P}=s.useChat({transport:new s.DefaultChatTransport({api:`${i.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${d==null?void 0:d.accessToken}`}),body:()=>{const $=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:w,isDevMode:l,aiContext:$.currentAIContext,reasoningEffort:$.reasoningEffort,showReasoning:$.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:$,body:se})=>({body:{...se,messages:s.cleanupIncompleteMessages($)}})}),onError:$=>{var se;if($.name==="AbortError"||(se=$.message)!=null&&se.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",$)},onToolCall:W,onFinish({isAbort:$,isDisconnect:se,isError:de}){a(""),console.log($?"[Editor Assistant] Stream aborted by user":se?"[Editor Assistant] Stream disconnected (network error)":de?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});D.useEffect(()=>{C&&v&&(q({role:"user",parts:[{type:"text",text:v}]}),y(!1))},[C,v,q,y]);async function W({toolCall:$}){var se,de,ue,we,me,je,xe,be,ke,fe,Te,Ee,Ae,Ie,ve,ye;if(["createChartFromSql","createForecast"].includes($.toolName)){const Q=((se=$.input)==null?void 0:se.sql)??((de=$.args)==null?void 0:de.sql),ae=((ue=$.input)==null?void 0:ue.python)??((we=$.args)==null?void 0:we.python),re=((me=$.input)==null?void 0:me.chartType)??((je=$.args)==null?void 0:je.chartType);k(re),h(Q),x(ae),g(!0),z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if($.toolName==="getUserSql"){if(!c){z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",message:"No SQL found"}});return}z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",sql:c,python:u||""}})}else if($.toolName==="generateQueryConfig"){a("Generating query config...");const Q=((xe=$.input)==null?void 0:xe.chartType)??((be=$.args)==null?void 0:be.chartType),ae=((ke=$.input)==null?void 0:ke.queryConfig)??((fe=$.args)==null?void 0:fe.queryConfig);((Te=$.input)==null?void 0:Te.cardConfig)??((Ee=$.args)==null||Ee.cardConfig),k(Q),I(ae),h(void 0),x(void 0);const re=await S();if((Ae=re==null?void 0:re.data)!=null&&Ae.error){z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",queryConfig:ae,message:(Ie=re==null?void 0:re.data)==null?void 0:Ie.error.message}});return}if((ve=re==null?void 0:re.data)!=null&&ve.records){z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:ae,message:"The data has been visualized"}});return}z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:ae,message:"The data has been visualized",records:(ye=re==null?void 0:re.data)==null?void 0:ye.records}})}else a("Analyzing...")}function Y($){const se=s.removeFromScopeArray(f,$);ee(se)}function ee($){const se=s.sanitizeAIScope($);b(se),K(de=>[...de,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(se)}`}]}])}function J(){const $={databaseName:B||"",schemaName:N||"",tableName:O||"",datamodelId:L||"",datamodelName:s.resolveDatamodelName(F),connectionId:E||"",connectionType:T||""},se=s.dedup([...f,$]);ee(se)}function ne(){const $={databaseName:B||"",schemaName:N||"",tableName:O||"",datamodelName:s.resolveDatamodelName(F),connectionId:E||"",connectionType:T||"",datamodelId:L||""};if(!s.isInAiScopeArray([...p||[],...f],$)||f.length===0){const de=s.dedup([...p||[],...f,$]).filter(ue=>ue.connectionId===$.connectionId);ee(de)}}const le=!["ready","error"].includes(V),Z=s.getErrorMessage(G);return{messages:R,setMessages:K,sendMessage:q,regenerate:_,isLoading:le,handleSetAIScope:ne,handleAddCurrentTableToScope:J,removeFromCurrentSelections:Y,currentAssitantScope:f,setCurrentAssitantScope:b,stop:H,status:V,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:Z,clearError:P}}const qn=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function ps({isFullscreen:t,onFullscreenChange:n,fullscreenContainer:a}){const r=D.useRef(null),[o,d]=D.useState(!1),[i,c]=D.useState(s.isDevEnv),[l,u]=D.useState(!1),[x,h]=D.useState(!1),[g,k]=D.useState(!1),m=t??g,f=s.useCurrentAIContext(),{setCurrentAIContext:v}=s.useAIActions(),{clearQueue:C}=s.useQueueActions(),{clearFileAttachments:A}=s.useFileActions(),B=s.useFileAttachments("editor"),O=s.useDashboardStore(Q=>Q.dashboard.aiContext),E=s.useEditorStore(Q=>Q.card.dataSource),N=s.useEditorStore(Q=>Q.actions.setCardSql),p=s.useEditorStore(Q=>Q.actions.setRunSql),j=s.useEditorStore(Q=>Q.showAIDialog),S=s.useDashboardStore(Q=>Q.handleOpenAssistantProfile),{setShowAIDialog:M,setCardPython:y}=s.useEditorActions(),{setDataSource:b}=s.useEditorActions(),{assistantProfile:I}=s.useAssistantProfile(),{messages:F,setMessages:T,sendMessage:L,isLoading:w,stop:R,status:K,llmUsage:_,errorMessage:G,clearError:q}=Gn(),[V,z]=D.useState(""),H=Q=>{z(Q.target.value)},P=Q=>{Q.preventDefault();const ae=V.trim();if(!ae&&B.length===0)return;const re=[];ae&&re.push({type:"text",text:ae}),B.forEach(Ne=>{Ne.data&&re.push({type:"file",mediaType:Ne.type,filename:Ne.name,url:`data:${Ne.type};base64,${Ne.data}`})}),L({role:"user",parts:re}),z(""),A("editor"),se({force:!0})},{visibleMessages:W,hasMoreMessages:Y,totalMessageCount:ee,loadMoreMessages:J,resetMessageWindow:ne}=s.useMessageWindow(F,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:le,isAtBottom:Z,hasNewMessages:oe,newMessageCount:$,scrollToBottom:se,handleScroll:de,resetNewMessageCount:ue}=s.useAutoScroll(W,{threshold:50,behavior:"smooth",isStreaming:w});D.useEffect(()=>{var Q;j&&((Q=r.current)==null||Q.focus(),v({selectedEntities:(E==null?void 0:E.selectedEntities)||[]}))},[j,E,v]),s.useAutoSubmitQueue({assistantType:"editor",status:K,isLoading:w,sendMessage:L});const{hasActiveTools:we}=s.useActiveToolStatus(F),me=D.useCallback(Q=>{n==null||n(Q),t===void 0&&k(Q)},[t,n]);D.useEffect(()=>{if(!m)return;function Q(ae){ae.key==="Escape"&&me(!1)}return window.addEventListener("keydown",Q),()=>{window.removeEventListener("keydown",Q)}},[m,me]);const je=D.useCallback(Q=>{L({role:"user",parts:[{type:"text",text:Q}]}),se({force:!0})},[L,se]),xe=D.useCallback(async()=>{const Q=JSON.stringify(F??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Q),s.ue.success("Conversation copied")}catch(ae){console.error("Failed to copy conversation",ae),s.ue.error("Unable to copy conversation")}},[F]),be=D.useCallback(()=>{me(!m)},[m,me]);function ke(Q,ae){ae==="sql"?(N(Q),p(!0)):ae==="python"&&(y(Q),p(!0))}function fe(){f.selectedEntities.length===0&&v({selectedEntities:(O==null?void 0:O.selectedEntities)||[]})}function Te(Q){fe();const ae={role:"user",parts:[{type:"text",text:Q.title+" "+Q.subtitle}]};L(ae)}function Ee(Q){fe(),L({role:"user",parts:[{type:"text",text:Q}]})}function Ae(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:d,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:c,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:u,children:"System Message"})]})]})}function Ie(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const ve=(V==null?void 0:V.length)===0&&(F==null?void 0:F.filter(Q=>Q.role==="user").length)===0,ye=e.jsxs("div",{"data-role":"editor-assistant",className:s.cn("flex h-full w-full flex-col justify-between px-6 py-4",m&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Ie(),S&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:S,children:(I==null?void 0:I.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Ae(),i&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:xe,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:m?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:be,children:m?e.jsx(s.Minimize2,{className:"size-4"}):e.jsx(s.Maximize2,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{T([]),C("editor"),q(),ne()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{M(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:le,className:"mt-2 flex w-full grow basis-0",onScroll:de,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[Y&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:J,className:"text-xs",children:["Load ",Math.min(5,ee-W.length)," ","more messages (",ee-W.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:W,showTools:i,handleRun:ke,showSystemMessage:l,onQuickReply:je,disableQuickReplies:w}),!we&&e.jsx(s.AssistantStatus,{status:K,errorMessage:G})]})}),j&&!Z&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{se({force:!0}),ue()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),oe&&$>0&&e.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:$>9?"9+":$})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[ve&&!I&&e.jsx(s.Placeholders,{onClick:Te,placeholders:qn}),e.jsx("div",{children:ve&&I&&e.jsx(s.SeedQuestions,{seedQuestions:I.seedQuestions||[],handleSeedQuestionClick:Ee})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:z,stop:R,input:V,handleInputChange:H,handleSubmit:Q=>{fe(),P(Q),se({force:!0})},isLoading:w,status:K,assistantType:"editor",onFocus:()=>{}})]}),_&&o&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",_.inputTokens," prompt tokens, ",_.outputTokens," ","completion tokens, ",_.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(E==null?void 0:E.selectedEntities)||[],open:x,onOpenChange:h,dataSource:E||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return m&&a?nt.createPortal(e.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:e.jsx("div",{className:"flex h-full w-full",children:ye})}),a):ye}const Un="chart-selector-standard-first";function _n(){const[t,n]=Ve(Un,!0);return{standardFirst:t,updatePreference:n}}const fs=({pluginVisual:t,index:n,onSelect:a})=>{const r=s.useDynamicIcon(t.icon||""),o=t.name.charAt(0).toUpperCase(),d=s.getAutoDetectedChartIcon(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:a,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):d||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:o}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${n}`)},gs=["default","standardPlugin","customPlugin"];function Hn({selectedChart:t,onChartChange:n}){var E;const[a,r]=D.useState(!1),{data:o}=s.useCustomVisualsQuery();_n();const i=((E=s.useEditorStore(N=>N.card).customCardPreferences)==null?void 0:E.url)||"";at.useRemoteChartStore(i);const{setCardType:c,setCardPreferences:l,setIsDevMode:u}=s.useEditorStore(N=>N.actions),{setCardCustomCfg:x,setCustomCardPreferences:h,setQueryConfig:g}=s.useEditorActions(),[k,m]=Ve("chart-section-active",null),f=D.useMemo(()=>k?[k,...gs.filter(N=>N!==k)]:gs,[k]);function v(N){x(null),l({}),c(N),["custom","map"].includes(N)&&(u(!0),g(void 0)),n(N),r(!1)}function C(N){x(null),l({}),c("custom"),h({type:"component",visualType:"single",url:N.url,componentName:N.name,icon:N.icon,pluginChartType:N.chartType}),g(void 0),n("custom"),r(!1)}const A=D.useMemo(()=>{let N=s.chartTypes;return N=s.chartTypes.filter(j=>j.id!=="tableBuilder"),N.some(j=>j.id==="bullet")?N:[...N,{id:"bullet",icon:s.BulletChartIcon,label:"Bullet Chart"}]},[]),B=()=>{var p;if(t==="custom"){const j=s.useEditorStore.getState().card;return((p=j==null?void 0:j.customCardPreferences)==null?void 0:p.componentName)||"Custom Visual"}const N=A.find(j=>j.id===t);return(N==null?void 0:N.label)||"Select chart type"},O=()=>{var p,j;if(t==="custom"){const S=s.useEditorStore.getState().card,M=(p=S==null?void 0:S.customCardPreferences)==null?void 0:p.icon,y=(j=S==null?void 0:S.customCardPreferences)==null?void 0:j.componentName;if(M&&y)return e.jsx(Jn,{icon:M,componentName:y});if(y){const b=s.getAutoDetectedChartIcon(y);if(b)return b}return e.jsx(De,{className:"h-4 w-4"})}const N=A.find(S=>S.id===t);if(N){const S=N.icon;return e.jsx(S,{className:"h-4 w-4"})}return e.jsx(De,{className:"h-4 w-4"})};return e.jsx("div",{className:"",children:e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[O(),e.jsx("span",{children:B()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),f.map(N=>{if(N==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:k==="default",onCheckedChange:p=>m(p?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:A.map(p=>{const j=p.icon;return e.jsx(s.CommandItem,{value:`${p.label} ${p.id} chart graph visualization`,onSelect:()=>v(p.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(j,{className:"h-4 w-4"}),e.jsx("span",{children:p.label})]})},p.id)})},"default");if(N==="standardPlugin"){const p=o.filter(j=>j.pluginType==="standard");return p.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:k==="standardPlugin",onCheckedChange:j=>m(j?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:p.filter(j=>j.componentType==="chart").map((j,S)=>e.jsx(fs,{pluginVisual:j,index:S,onSelect:()=>C(j)},`${j.url}-${j.name}-${S}`))},"standardPlugin"):null}if(N==="customPlugin"){const p=o.filter(j=>j.pluginType==="custom");return p.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:k==="customPlugin",onCheckedChange:j=>m(j?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:p.map((j,S)=>e.jsx(fs,{pluginVisual:j,index:S,onSelect:()=>C(j)},`${j.url}-${j.name}-${S}`))},"customPlugin"):null}return null})]})]})})]})})}const Jn=({icon:t,componentName:n})=>{const a=s.useDynamicIcon(),r=s.getAutoDetectedChartIcon(n);return a?e.jsx(a,{className:"h-4 w-4"}):r||e.jsx(De,{className:"h-4 w-4"})},Qn=[{id:"table",icon:s.Table2,label:"Table"},{id:"bar",icon:s.ChartColumnIncreasing,label:"Bar Chart"},{id:"line",icon:s.ChartLine,label:"Line Chart"},{id:"stackedBar",icon:s.ChartColumnStacked,label:"Stacked Bar",requiresPivot:!1},{id:"pie",icon:s.ChartPie,label:"Pie Chart"},{id:"doughnut",icon:s.Donut,label:"Donut Chart"},{id:"kpi",icon:s.TiSortNumerically,label:"KPI"},{id:"treemap",icon:s.TbChartTreemap,label:"Treemap"},{id:"bullet",icon:s.BulletChartIcon,label:"Bullet Chart"},{id:"funnel",icon:s.TbChartFunnel,label:"Funnel Chart"},{id:"tornado",icon:s.Tornado,label:"Tornado Chart"},{id:"heatmap",icon:s.Grid3x3,label:"Heatmap"},{id:"range",icon:s.ChartNoAxesGantt,label:"Range Chart"}];function Yn({selectedChart:t,onChartChange:n,isDropdownExpanded:a,onToggleDropdown:r}){var c;const o=s.useEditorStore(l=>l.card),d=((c=o==null?void 0:o.config)==null?void 0:c.pivotByColumns)&&o.config.pivotByColumns.length>0,i=Qn.filter(l=>!(l.requiresPivot&&!d));return e.jsxs("div",{className:"grid grid-cols-7 gap-2",children:[i.map(l=>{const u=l.icon,x=t===l.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>n(l.id),className:s.cn("h-8 w-8 p-0",x&&"bg-accent text-accent-foreground"),children:[e.jsx(u,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:l.label})]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:"border-foreground/20 bg-foreground text-background",children:[e.jsx("p",{children:l.label}),e.jsx(s.TooltipArrow,{className:"fill-foreground"})]})]},l.id)}),r&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0","aria-label":a?"Hide all charts":"Show all charts",children:a?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})})}),e.jsxs(s.TooltipContent,{side:"bottom",className:"border-foreground/20 bg-foreground text-background",children:[e.jsx("p",{children:a?"Hide dropdown":"Show all charts"}),e.jsx(s.TooltipArrow,{className:"fill-foreground"})]})]})]})}let Wn=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce((n,a)=>(a&=63,a<36?n+=a.toString(36):a<62?n+=(a-26).toString(36).toUpperCase():a>62?n+="-":n+="_",n),"");const Pe=[{id:"sum",label:"Sum",symbol:"+",description:"Add two metrics together",template:()=>"({field_0} + {field_1})",requiresTwoInputs:!0},{id:"difference",label:"Difference",symbol:"−",description:"Subtract one metric from another",template:()=>"({field_0} - {field_1})",requiresTwoInputs:!0},{id:"product",label:"Product (Multiplication)",symbol:"×",description:"Multiply two metrics",template:()=>"({field_0} * {field_1})",requiresTwoInputs:!0},{id:"ratio",label:"Ratio",symbol:"÷",description:"Divide one metric by another",template:()=>"({field_0} / NULLIF({field_1}, 0))",requiresTwoInputs:!0},{id:"change",label:"Change",symbol:"Δ",description:"Calculate percentage change from A to B",template:()=>"(({field_1} - {field_0}) / NULLIF({field_0}, 0))",requiresTwoInputs:!0},{id:"percentage",label:"Percentage",symbol:"%",description:"Calculate (A / B) × 100",template:()=>"(({field_0} / NULLIF({field_1}, 0)) * 100)",requiresTwoInputs:!0},{id:"scale",label:"Scale (Multiply by Factor)",symbol:"×n",description:"Multiply a metric by a constant factor",template:()=>"({field_0} * {constant})",requiresTwoInputs:!1},{id:"custom",label:"Custom Expression",symbol:"{}",description:"Drag fields to create custom expression with tokens",requiresTwoInputs:!1,allowsCustomExpression:!0}];function Xn(t,n,a,r,o,d,i,c,l){const u=Pe.find(f=>f.id===n);if(!u)throw new Error(`Unknown operation: ${n}`);let x,h=[],g;if(n==="custom"){if(!(c!=null&&c.trim()))throw new Error("Custom expression is required");x=c.trim()}else if(n==="scale"){if(!a)throw new Error("Metric A is required for scale operation");if(l===void 0||l===0)throw new Error("Constant factor is required for scale operation");x=u.template().replace("{constant}",String(l)),h=[a],g=l}else{if(!a||!r)throw new Error("Metrics A and B are required for standard operations");x=u.template(),h=[a,r]}const k={operation:n,inputFields:h,...g!==void 0&&{constant:g}};return{id:i||`calc_${Wn(10)}`,name:t.toLowerCase().replace(/\s+/g,"_"),label:t,alias:t.toLowerCase().replace(/\s+/g,"_"),qualifiedFieldName:t.toLowerCase().replace(/\s+/g,"_"),dataType:"number",role:"metric",aggregate:"SUM",expression:x,calculatedFormula:k,entityId:d,entityName:s.CALCULATED_FIELD_ENTITY_MARKER,entityType:"table",description:`Calculated field: ${t}`}}function js(t){var r,o;const n=Pe.find(d=>d.id===t.operation);if(!n)return"Unknown operation";if(t.operation==="custom")return"Custom expression";if(t.operation==="scale"){const d=((r=t.inputFields[0])==null?void 0:r.label)||((o=t.inputFields[0])==null?void 0:o.name)||"A",i=t.constant??1;return`${d} × ${i}`}return t.inputFields.map(d=>d.label||d.name).join(` ${n.symbol} `)}const We=({dataType:t})=>s.getFieldIconComponent(t);function Zn({aliasTemplate:t,onAliasTemplateChange:n}){var l;const[a,r]=D.useState(t),[o,d]=D.useState(!1),i=(l=s.useEditorStore(u=>{var x;return(x=u.card.config)==null?void 0:x.pivotByColumns}))==null?void 0:l[0],c=i?`e.g. Min Sales in {{${i.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.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(s.Input,{placeholder:c,value:o?a:t,onChange:u=>{r(u.target.value),d(!0)},onFocus:()=>d(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&o&&a!==t?(n(a),d(!1)):u.key==="Escape"&&(r(t),d(!1))},"aria-label":"Edit alias template"}),o&&a!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{n(a),d(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),d(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function ea({valueAliases:t,onValueAliasesChange:n}){const[a,r]=D.useState(null),[o,d]=D.useState(""),[i,c]=D.useState(""),l=()=>{n({...t,"":""})},u=h=>{const g={...t};delete g[h],n(g)},x=h=>{const g={...t};delete g[h],g[o]=i,n(g),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,g],k)=>e.jsx("div",{className:"flex items-center gap-2",children:a===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input,{placeholder:"Value key",value:o,onChange:m=>d(m.target.value),className:"h-8 w-24 text-xs",onPointerDown:m=>m.stopPropagation(),onKeyDown:m=>{m.key==="Enter"?x(h):m.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input,{placeholder:"Alias label",value:i,onChange:m=>c(m.target.value),className:"h-8 w-24 text-xs",onPointerDown:m=>m.stopPropagation(),onKeyDown:m=>{m.key==="Enter"?x(h):m.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>x(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),d(h),c(g)},"aria-label":"Edit value alias key"}),e.jsx(s.Input,{placeholder:"Alias label",value:g,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),d(h),c(g)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+k)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:l,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function sa({column:t}){const n=s.useEditorStore(l=>l.card.type),a=s.useEditorStore(l=>{var u,x;return(x=(u=l.card)==null?void 0:u.config)==null?void 0:x.metricColumns}),r=(a==null?void 0:a.map(l=>l.label))||[],o=r==null?void 0:r.find(l=>l===t.label||l===t.name),d=o?r.indexOf(o):-1;function i(){return e.jsx("div",{className:"pr-1",children:o&&e.jsx(Rs,{idx:d,col:o,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function c(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Ps,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&i(),["pie","doughnut"].includes(n)&&c()]})}function ta({field:t,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:o}=s.useSemaphorContext(),d=s.useEditorStore(u=>u.card),i=d==null?void 0:d.dataSource,c=["attribute-values",t.entityName,t.name,n,a],l=s.useQuery({queryKey:c,queryFn:async()=>{if(!(i!=null&&i.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},x={connection_id:i.connectionId,cardConfig:u,cardDataSource:i,cache_config:s.getCacheConfig({card:d})};console.log("requestBody",x);const h=await s.postRequestRegular(`${o.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",x);if(h!=null&&h.error)return console.error("Error fetching attribute values:",h.error),[];const g=t.name;return((h==null?void 0:h.records)||[]).map(m=>{const f=m[g]||m[t.alias||g]||m[t.label];return{id:f||"",value:f||"",label:String(f||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(i!=null&&i.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:l.data||[],isLoading:l.isLoading,isFetching:l.isFetching,isError:l.isError,error:l.error,refetch:l.refetch}}function Js({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:o,onSave:d}){var B,O;const i=!!o,[c,l]=D.useState(i?"values":"fields"),[u,x]=D.useState(""),[h,g]=D.useState({id:(o==null?void 0:o.id)||s.v4(),field:(o==null?void 0:o.field)||null,selectedValues:o?Array.isArray(o.value)?o.value:[o.value]:[]}),k=a.filter(E=>{var p;return i?!1:!((p=r==null?void 0:r.conditions)==null?void 0:p.some(j=>j.field.id===E.id))&&E.label.toLowerCase().includes(u.toLowerCase())}),m=E=>{g({...h,field:E}),l("values")},f=()=>{if(h.field&&h.selectedValues.length>0){const E={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let N;if(i){const p=((r==null?void 0:r.conditions)||[]).map(j=>j.id===o.id?E:j);N={...r,conditions:p}}else{const p=(r==null?void 0:r.conditions)||[];N={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...p,E],groups:[]}}d(N),n(!1)}},v=()=>{if(!i||!o)return;const E=((r==null?void 0:r.conditions)||[]).filter(N=>N.id!==o.id);if(E.length>0){const N={...r,conditions:E};d(N)}else d(void 0);n(!1)},C=E=>{g({...h,selectedValues:E})},A=()=>{i&&o?(g({id:o.id,field:o.field,selectedValues:Array.isArray(o.value)?o.value:[o.value]}),l("values")):(g({id:s.v4(),field:null,selectedValues:[]}),l("fields")),x("")};return D.useEffect(()=>{t&&A()},[t,i,o]),e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:i?`Edit Filter: ${(B=h.field)==null?void 0:B.label}`:c==="fields"?"Select Field to Filter":`Select Values for ${(O=h.field)==null?void 0:O.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!i&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&c==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(E=>e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted rounded-md text-xs",children:[e.jsxs("span",{className:"font-medium",children:[E.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(E.value)?`${E.value.length} values`:String(E.value)})]},E.id))})]}),c==="fields"&&!i?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search fields...",value:u,onChange:E=>x(E.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:k.map(E=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>m(E),children:[e.jsx(We,{dataType:s.getDataType(E.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:E.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[E.entityName,".",E.name]})]})]},E.id))}),k.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),k.length===0&&!u&&a.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(na,{field:h.field,selectedValues:h.selectedValues,onValuesChange:C,onBack:i?void 0:()=>l("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:i?e.jsx(s.Button,{variant:"destructive",onClick:v,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:A,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:f,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function na({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[o,d]=D.useState(""),{values:i,isLoading:c,isFetching:l}=ta({field:t,searchQuery:o,limit:500}),u=o?i.filter(g=>String(g.value).toLowerCase().includes(o.toLowerCase())):i,x=g=>{const k=n.includes(g);a(k?n.filter(m=>m!==g):[...n,g])},h=()=>{n.length===u.length&&u.length>0?a([]):a(u.map(g=>g.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search values...",value:o,onChange:g=>d(g.target.value),className:"pl-10"})]}),c||l?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(s.Checkbox,{checked:n.length===u.length&&u.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",u.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:u.map(g=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>x(g.value),children:[e.jsx(s.Checkbox,{checked:n.includes(g.value),onCheckedChange:()=>x(g.value)}),e.jsx(Qe,{className:"text-sm",children:g.label})]},g.id))})]})]})}function Qs({open:t,onOpenChange:n,availableMetrics:a,existingField:r,onSave:o,cardId:d}){const[i,c]=D.useState(""),[l,u]=D.useState("ratio"),[x,h]=D.useState(null),[g,k]=D.useState(null),[m,f]=D.useState(1),[v,C]=D.useState(""),[A,B]=D.useState({format:"number",decimalPlaces:2}),[O,E]=D.useState({}),N=Pe.find(b=>b.id===l),p=a.find(b=>b.id===x),j=a.find(b=>b.id===g);D.useEffect(()=>{if(r&&t)if(c(r.label),r.calculatedFormula)if(u(r.calculatedFormula.operation),r.calculatedFormula.operation==="custom")C(r.expression||"");else if(r.calculatedFormula.operation==="scale"){const b=r.calculatedFormula.inputFields;if(b.length>=1){const I=a.find(F=>F.qualifiedFieldName===b[0].qualifiedFieldName);h((I==null?void 0:I.id)||null)}r.calculatedFormula.constant!==void 0&&f(r.calculatedFormula.constant)}else{const b=r.calculatedFormula.inputFields;if(b.length>=2){const I=a.find(T=>T.qualifiedFieldName===b[0].qualifiedFieldName),F=a.find(T=>T.qualifiedFieldName===b[1].qualifiedFieldName);h((I==null?void 0:I.id)||null),k((F==null?void 0:F.id)||null)}}else u("custom"),C(r.expression||"")},[r,t,a]);const S=()=>{const b={};return i.trim()||(b.name="Name is required"),l==="custom"?v.trim()||(b.customExpression="Custom expression is required"):l==="scale"?(x||(b.inputA="Please select a metric for input A"),(isNaN(m)||m===0)&&(b.constantFactor="Please enter a valid non-zero number"),r&&x===r.id&&(b.circular="Cannot reference the field being edited")):(x||(b.inputA="Please select a metric for input A"),g||(b.inputB="Please select a metric for input B"),x===g&&(b.inputs="Inputs A and B must be different metrics"),r&&(x===r.id||g===r.id)&&(b.circular="Cannot reference the field being edited")),E(b),Object.keys(b).length===0},M=()=>{if(!S())return;const b=Xn(i,l,p||null,j||null,A,d,r==null?void 0:r.id,l==="custom"?v:void 0,l==="scale"?m:void 0);o(b),y()},y=()=>{c(""),u("ratio"),h(null),k(null),f(1),C(""),E({}),n(!1)};return e.jsxs(s.Dialog,{modal:!1,open:t,onOpenChange:n,children:[t&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-w-md max-h-[90vh] overflow-y-auto",onInteractOutside:b=>{b.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsxs(s.DialogTitle,{children:[r?"Edit":"Create"," Calculated Metric"]}),e.jsx(s.DialogDescription,{children:"Combine existing metrics to create a new calculated field"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"name",children:"Name"}),e.jsx(s.Input$1,{id:"name",value:i,onChange:b=>c(b.target.value),placeholder:"e.g., Profit Margin",className:O.name?"border-red-500":""}),O.name&&e.jsx("p",{className:"text-xs text-red-500",children:O.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"operation",children:"Outcome is"}),e.jsxs(s.Select,{value:l,onValueChange:b=>{u(b),b==="custom"?(h(null),k(null)):l==="custom"&&C("")},children:[e.jsx(s.SelectTrigger,{id:"operation",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"CALCULATED"}),Pe.map(b=>e.jsx(s.SelectItem,{value:b.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm",children:b.symbol}),e.jsx("span",{children:b.label})]})},b.id))]})})]}),N&&e.jsx("p",{className:"text-xs text-muted-foreground",children:N.description})]}),l==="custom"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"customExpression",children:"SQL Expression"}),e.jsx(s.Textarea,{id:"customExpression",value:v,onChange:b=>C(b.target.value),placeholder:"e.g., CASE WHEN revenue > 1000 THEN revenue - cost ELSE 0 END",className:s.cn("font-mono text-sm",O.customExpression&&"border-red-500"),rows:4}),O.customExpression&&e.jsx("p",{className:"text-xs text-red-500",children:O.customExpression}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Write a SQL expression using column names from your data source"})]}):e.jsxs("div",{className:"rounded-md bg-muted p-3 font-mono text-sm",children:["= ",x&&p?p.label:"A"," ",N==null?void 0:N.symbol," ",g&&j?j.label:"B"]}),l!=="custom"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"inputA",children:"Where"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded bg-muted font-mono text-sm font-medium",children:"A"}),e.jsxs(s.Select,{value:x||"",onValueChange:h,children:[e.jsx(s.SelectTrigger,{id:"inputA",className:O.inputA?"border-red-500":"",children:e.jsx(s.SelectValue,{placeholder:"+ Choose metric"})}),e.jsx(s.SelectContent,{children:a.filter(b=>!s.isCalculatedMetric(b)||b.id!==(r==null?void 0:r.id)).map(b=>e.jsxs(s.SelectItem,{value:b.id,children:[b.label||b.name,b.aggregate&&` (${b.aggregate})`]},b.id))})]})]}),O.inputA&&e.jsx("p",{className:"text-xs text-red-500",children:O.inputA})]}),l!=="custom"&&l!=="scale"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded bg-muted font-mono text-sm font-medium",children:"B"}),e.jsxs(s.Select,{value:g||"",onValueChange:k,children:[e.jsx(s.SelectTrigger,{id:"inputB",className:O.inputB?"border-red-500":"",children:e.jsx(s.SelectValue,{placeholder:"+ Choose metric"})}),e.jsx(s.SelectContent,{children:a.filter(b=>!s.isCalculatedMetric(b)||b.id!==(r==null?void 0:r.id)).map(b=>e.jsxs(s.SelectItem,{value:b.id,children:[b.label||b.name,b.aggregate&&` (${b.aggregate})`]},b.id))})]})]}),O.inputB&&e.jsx("p",{className:"text-xs text-red-500",children:O.inputB})]}),l==="scale"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"constantFactor",children:"Multiplication Factor"}),e.jsx(s.Input$1,{id:"constantFactor",type:"number",step:"any",value:m,onChange:b=>f(parseFloat(b.target.value)||0),placeholder:"e.g., 0.15",className:O.constantFactor?"border-red-500":""}),O.constantFactor&&e.jsx("p",{className:"text-xs text-red-500",children:O.constantFactor}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Enter the constant value to multiply the metric by (e.g., 0.15 for 15%)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"format",children:"Format"}),e.jsxs(s.Select,{value:A.format,onValueChange:b=>B({...A,format:b}),children:[e.jsx(s.SelectTrigger,{id:"format",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsxs(s.SelectItem,{value:"number",children:["Decimal (",A.decimalPlaces,")"]}),e.jsx(s.SelectItem,{value:"currency",children:"Currency"}),e.jsx(s.SelectItem,{value:"percent",children:"Percentage"})]})]})]}),(O.inputs||O.circular)&&e.jsxs(s.Alert,{variant:"destructive",children:[e.jsx(s.CircleAlert,{className:"h-4 w-4"}),e.jsx(s.AlertDescription,{children:O.inputs||O.circular})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:y,children:"Cancel"}),e.jsxs(s.Button,{onClick:M,children:[r?"Update":"Create"," Metric"]})]})]})]})}function aa({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:o,hasPivotColumns:d=!1,cardType:i}){var Ze,es,ss,ts,ns;const{attributes:c,listeners:l,setNodeRef:u,transform:x,transition:h,isDragging:g}=s.useSortable({id:t.id}),k=s.useEditorStore(U=>U.card),{updateLabel:m,handleAggregationChange:f,handleDateFormatChange:v,handleGranularityChange:C,handleAliasTemplateChange:A,handleValueAliasesChange:B,removeField:O,handleKpiComparisonTypeChange:E,handleKpiShowTrendlineChange:N,handleKpiTrendlineWindowChange:p,handleKpiTrendlineGranularityChange:j,handleKpiTargetValueChange:S}=s.useFieldManagement(k),[M,y]=D.useState(!1),[b,I]=D.useState(!1),[F,T]=D.useState(!1),[L,w]=D.useState(null),[R,K]=D.useState(t.dateFormat||"YYYY-MM-DD"),[_,G]=D.useState(t.customFormat||""),[q,V]=D.useState(!!t.customFormat),[z,H]=D.useState(t.granularity||"day"),[P,W]=D.useState(t.aliasTemplate||""),[Y,ee]=D.useState(t.valueAliases||{}),[J,ne]=D.useState((Ze=t.parameters)==null?void 0:Ze.filters),le=U=>{U==="custom"?V(!0):(V(!1),K(U),n==="groupBy"&&v(a,U,""))},Z=U=>{G(U),n==="groupBy"&&v(a,"custom",U)},oe=U=>{var ie;H(U);const X=(ie=s.getDateFormatOptionsForGranularity(U)[0])==null?void 0:ie.value;X&&!q&&(K(X),n==="groupBy"&&v(a,X,"")),n==="groupBy"&&C(a,U)},$=U=>{W(U),n==="metrics"&&A(a,U)},se=U=>{ee(U),n==="metrics"&&B(a,U)},de=U=>{m(n,a,U)},ue=U=>{var te;if(ne(U),n==="metrics"){const X={...t,parameters:{...t.parameters,filters:U}},ie=[...((te=k.config)==null?void 0:te.metricColumns)||[]];ie[a]=X,s.useEditorStore.getState().actions.updateCardConfig(k.id,{metricColumns:ie})}I(!1)},we=()=>{O(n,a)},me={transform:s.CSS.Transform.toString(x),transition:h},je=s.getDataType(t.dataType),xe=je==="date",be=i==="kpi",ke=s.getDateFormatOptionsForGranularity(z),fe=n!=="pivotBy",Te=xe&&n==="groupBy"&&(!be||((es=k.config)==null?void 0:es.comparisonType)==="start_vs_end"),Ee=!be&&xe&&n==="groupBy",Ae=i&&s.COMPARISON_SUPPORTED_CHART_TYPES.includes(i)&&xe&&n==="groupBy",Ie=i==="kpi"&&xe&&n==="groupBy",ve=i&&i!=="pivotTable"&&n==="metrics"&&((ss=k.config)==null?void 0:ss.comparisonType)==="target",ye=n==="metrics",Q=()=>{const U=t,te=n==="metrics"&&s.isCalculatedMetric(U);return e.jsxs("div",{className:"space-y-1",children:[!te&&e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:X=>{X.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),te&&U.calculatedFormula&&e.jsxs("div",{title:js(U.calculatedFormula),onPointerDown:X=>{X.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap rounded bg-muted/50 px-1.5 py-0.5 font-mono text-xs text-primary",children:["= ",js(U.calculatedFormula)]})]})},ae=()=>fe?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(pe,{value:t.label??"",onSave:de,placeholder:"Display label...",type:"text"})]}):null,re=()=>Te?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:z,onValueChange:oe,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(U=>e.jsx(s.SelectItem,{className:"text-xs",value:U,children:s.toTitleCase(U)},U))})]})]}):null,Ne=()=>Ee?e.jsxs(e.Fragment,{children:[re(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(s.Select,{value:q?"custom":R,onValueChange:le,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:ke.map(U=>e.jsx(s.SelectItem,{className:"text-xs",value:U.value,children:U.label},U.value))})]}),q&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:_,onChange:U=>{U.stopPropagation(),Z(U.target.value)},onClick:U=>U.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,Ws=()=>{var X,ie,Ce,Le,ge;const U=Ae,te=Ie;return!U&&!te?null:e.jsxs(e.Fragment,{children:[U&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((X=k.config)==null?void 0:X.comparisonType)||"none",onValueChange:E,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"start_vs_end",children:"Start vs End"})]})]})]}),te&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((ie=k.config)==null?void 0:ie.showTrendline)||!1,onCheckedChange:N})]})}),((Ce=k.config)==null?void 0:Ce.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input,{type:"number",min:"1",max:"365",value:((Le=k.config)==null?void 0:Le.trendlineWindow)||30,onChange:Be=>{const tt=parseInt(Be.target.value)||30;p(tt)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(s.Select,{value:((ge=k.config)==null?void 0:ge.trendlineGranularity)||"day",onValueChange:j,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]})]})},Xs=()=>{var U,te;return ve?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(pe,{value:((U=k.config)==null?void 0:U.targetValue)!==void 0&&((te=k.config)==null?void 0:te.targetValue)!==null?String(k.config.targetValue):"",onSave:X=>{!isNaN(Number(X))&&X!==null?S(Number(X)):S(0)},placeholder:"Enter target value...",type:"text"})]}):null},Zs=()=>{if(!ye)return null;const U=t,te=s.isCalculatedMetric(U);return e.jsxs(e.Fragment,{children:[te&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Formula"}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>T(!0),children:[e.jsx(s.Pencil,{className:"mr-2 h-3 w-3"}),"Edit Formula"]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:X=>{f(a,X)},disabled:te,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(J==null?void 0:J.conditions)&&J.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:J.conditions.map(X=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{w(X),I(!0)},children:[e.jsxs("span",{className:"font-medium",children:[X.field.label,":"]}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(X.value)?X.value.length===1?String(X.value[0]):X.value.length<=2?X.value.join(", "):`${X.value.slice(0,2).join(", ")} +${X.value.length-2}`:String(X.value)})}),Array.isArray(X.value)&&X.value.length>1&&e.jsx(s.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",X.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:X.value.map((ie,Ce)=>e.jsx("div",{children:String(ie)},Ce))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:ie=>{var Le;ie.stopPropagation();const Ce=J.conditions.filter(ge=>ge.id!==X.id);if(Ce.length>0){const ge={...J,conditions:Ce};ue(ge)}else if(ne(void 0),n==="metrics"){const ge={...t,parameters:{...t.parameters,filters:void 0}},Be=[...((Le=k.config)==null?void 0:Le.metricColumns)||[]];Be[a]=ge,s.useEditorStore.getState().actions.updateCardConfig(k.id,{metricColumns:Be})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},X.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{w(null),I(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(sa,{column:t}),d&&e.jsxs(e.Fragment,{children:[e.jsx(Zn,{aliasTemplate:P,onAliasTemplateChange:$}),e.jsx(ea,{valueAliases:Y,onValueAliasesChange:se})]})]})},{columns:et=[]}=s.useColumns(),st=(J==null?void 0:J.conditions)&&J.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:me,...c,...l,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${g?"z-50 scale-95 opacity-50":"border-slate-200"} ${n==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(We,{dataType:je}),e.jsx(Qe,{className:s.cn("w-[140px] flex-1 text-sm",st&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((ts=J==null?void 0:J.conditions)==null?void 0:ts.length)&&!M&&e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:J.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:J.conditions.map(U=>e.jsxs("div",{children:[U.field.label,":"," ",Array.isArray(U.value)?`${U.value.length} values`:String(U.value)]},U.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:U=>{U.stopPropagation(),y(!M)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${M?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:U=>{U.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const te=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",te),o(te)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:U=>{U.stopPropagation(),we()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),M&&e.jsxs("div",{className:"space-y-3",children:[Q(),ae(),i==="kpi"&&re(),Ne(),Ws(),Xs(),Zs()]})]}),b&&e.jsx(Js,{open:b,onOpenChange:U=>{I(U),U||w(null)},availableFields:et,existingFilters:J,editingCondition:L,onSave:U=>{var te;if(U)ue(U);else if(ne(void 0),n==="metrics"){const X={...t,parameters:{...t.parameters,filters:void 0}},ie=[...((te=k.config)==null?void 0:te.metricColumns)||[]];ie[a]=X,s.useEditorStore.getState().actions.updateCardConfig(k.id,{metricColumns:ie})}w(null)}}),F&&n==="metrics"&&e.jsx(Qs,{open:F,onOpenChange:T,availableMetrics:((ns=k.config)==null?void 0:ns.metricColumns)||[],existingField:t,onSave:U=>{var X;const te=[...((X=k.config)==null?void 0:X.metricColumns)||[]];te[a]=U,s.useEditorStore.getState().actions.updateCardConfig(k.id,{metricColumns:te})},cardId:k.id})]})}function ra({concept:t}){const n=()=>{switch(t){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:"Pivot 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:"Metric 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(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:n()})]})})}function Re({zone:t,fields:n,label:a,placeholder:r,shouldShow:o,hasPivotColumns:d=!1,activeField:i=null}){const{isOver:c,setNodeRef:l}=s.useDroppable({id:t}),{updateSortByColumn:u}=s.useEditorActions(),x=s.useEditorStore(v=>v.card),h=s.useEditorStore(v=>v.card.type),g=n.length>0,k=D.useMemo(()=>!i||!c?!0:s.validateFieldForChartType(i,t,h).isValid,[i,c,t,h]),m=(v,C)=>{var B;!((B=x.config)!=null&&B.sortByColumns)||x.config.sortByColumns.findIndex(O=>O.id===v)===-1||u(x.id,v,{direction:C})};if(t==="sortBy"&&o===!1)return null;const f=t!=="sortBy"&&h!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:a}),f&&e.jsx(ra,{concept:t})]}),e.jsx("div",{ref:l,className:s.cn("rounded-lg border-2 border-dotted p-0.5 transition-all",{"border-green-500 bg-green-50 dark:bg-green-950":c&&k,"border-red-500 bg-red-50 dark:bg-red-950":c&&!k,"border-muted-foreground/30 bg-muted/40":!c&&g,"min-h-[60px] border-muted-foreground/20 bg-background":!c&&!g}),children:n.length===0?e.jsx("div",{className:"flex min-h-[60px] items-center justify-center text-sm text-muted-foreground/60",children:r}):e.jsx(s.SortableContext,{items:n.map(v=>v.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((v,C)=>{const B=v.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(aa,{field:v,zone:t,index:C,sortDirection:B,onSortDirectionChange:O=>m(v.id,O),hasPivotColumns:d,cardType:h})})},v.id)})})})})]})}const bs={difference:{label:"Difference",description:"Shows the exact difference between two values.",formula:"Primary - Secondary",example:"Sales increased by $5,000 compared to last year."},change:{label:"Change",description:"Shows the percentage increase or decrease between two values.",formula:"(Primary - Secondary) / Secondary × 100%",example:"Year-over-year sales change of 25%."},change_difference:{label:"Change (difference)",description:"Shows both the percentage change and the exact difference between two values.",formula:`% Change: (Primary - Secondary) / Secondary × 100%
200
- Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function la(){var g,k,m,f,v,C,A,B,O,E,N;const t=s.useEditorStore(p=>p.card),{setCardPreferences:n}=s.useEditorActions(),a=((g=t.config)==null?void 0:g.metricColumns)||[],r=((k=t.config)==null?void 0:k.groupByColumns)||[],o=a.length===2&&r.length===0,d=a.length>=1&&r.length>0;if(!(t.type==="kpi"&&(o||d)))return null;const c=((f=(m=t.preferences)==null?void 0:m.kpiVisualOptions)==null?void 0:f.metricComparison)||{},l=p=>{var S;const j={...t.preferences,kpiVisualOptions:{...(S=t.preferences)==null?void 0:S.kpiVisualOptions,metricComparison:{...c,...p}}};n(j)},u=d||c.enabled,x=((v=t.config)==null?void 0:v.comparisonType)||"none",h=x==="previous_period"||x==="same_period_last_year"||x==="start_vs_end";return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pt,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[o&&a.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:c.enabled||!1,onCheckedChange:p=>l({enabled:p,...p&&!c.calculationType?{calculationType:"difference"}:{}})})]}),u&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const p=c.calculationType||"difference",j=bs[p];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:j==null?void 0:j.label}),e.jsx("p",{children:j==null?void 0:j.description}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-[10px]",children:j==null?void 0:j.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",j==null?void 0:j.example]})]})})()})]})]}),e.jsxs(s.Select,{value:c.calculationType||"difference",onValueChange:p=>l({calculationType:p}),children:[e.jsx(s.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Object.entries(bs).map(([p,j])=>e.jsx(s.SelectItem,{value:p,className:"text-xs",children:j.label},p))})]})]}),e.jsx(Ye,{formatOptions:c.formatOptions||{},onFormatOptionsChange:p=>l({formatOptions:p}),showTitle:!0,title:"COMPARISON FORMAT"}),(h||o)&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),o&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:c.position||"right",onValueChange:p=>l({position:p}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:c.showArrow!==!1,onCheckedChange:p=>l({showArrow:p})}),e.jsx(s.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-color",checked:c.showColor!==!1,onCheckedChange:p=>l({showColor:p})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),c.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Fe,{value:((C=c.colorConfig)==null?void 0:C.increase)||"green",onChange:p=>l({colorConfig:{...c.colorConfig,increase:p}}),label:"Primary > Secondary"}),e.jsx(Fe,{value:((A=c.colorConfig)==null?void 0:A.decrease)||"red",onChange:p=>l({colorConfig:{...c.colorConfig,decrease:p}}),label:"Primary < Secondary"}),e.jsx(Fe,{value:((B=c.colorConfig)==null?void 0:B.noChange)||"neutral",onChange:p=>l({colorConfig:{...c.colorConfig,noChange:p}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"conditional-label",checked:c.conditionalLabel||!1,onCheckedChange:p=>l({conditionalLabel:p})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),c.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input$1,{id:"label-increase",type:"text",value:((O=c.conditionalLabels)==null?void 0:O.increase)??"Increase",onChange:p=>l({conditionalLabels:{...c.conditionalLabels,increase:p.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(s.Input$1,{id:"label-decrease",type:"text",value:((E=c.conditionalLabels)==null?void 0:E.decrease)??"Decrease",onChange:p=>l({conditionalLabels:{...c.conditionalLabels,decrease:p.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(s.Input$1,{id:"label-no-change",type:"text",value:((N=c.conditionalLabels)==null?void 0:N.noChange)??"No change",onChange:p=>l({conditionalLabels:{...c.conditionalLabels,noChange:p.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Previous Label"}),e.jsx(s.Input$1,{id:"label-name",type:"text",value:c.labelName??"",onChange:p=>l({labelName:p.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function oa(){var o,d;const t=s.useEditorStore(i=>i.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((d=(o=t.preferences)==null?void 0:o.kpiVisualOptions)==null?void 0:d.formatOptions)||{},r=i=>{var l;const c={...t.preferences,kpiVisualOptions:{...(l=t.preferences)==null?void 0:l.kpiVisualOptions,formatOptions:i}};n(c)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Hash,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(Ye,{formatOptions:a,onFormatOptionsChange:r,showTitle:!1})})]})}function ia(){var d;const t=s.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.type}),n=s.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.preferences}),{setCardPreferences:a}=s.useEditorActions();if(t!=="treemap")return null;const r=((d=n==null?void 0:n.chartOptions)==null?void 0:d.treemapColorMode)??"branch",o=i=>{const c={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,treemapColorMode:i}};a(c)};return e.jsxs(s.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(s.RadioGroup,{value:r,onValueChange:i=>o(i??"branch"),className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:"treemap-color-branch",value:"branch"}),e.jsxs(s.Label,{htmlFor:"treemap-color-branch",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Shade by value (default)"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Keeps parent hue and adjusts lightness based on the node's share within the branch."})]})]}),e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:"treemap-color-category",value:"category"}),e.jsxs(s.Label,{htmlFor:"treemap-color-category",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Single color per category"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Applies the top-level color to all descendants without lightening/darkening."})]})]})]})})]})}function ca({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r,activeField:o}){const[d,i]=D.useState(!1),c=s.useEditorStore(B=>{var O;return((O=B.card.customCardPreferences)==null?void 0:O.url)&&B.card.type==="custom"}),l=s.useEditorStore(B=>B.card),u=s.useEditorStore(B=>B.actions.updateCardConfig),x=l==null?void 0:l.type,h=t.length>0||a.length>0,g=x!=="kpi"||a.length<=2,k=x!=="kpi",m=x!=="kpi"&&h,f=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(x),v=k&&!f,C=()=>x==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},A=()=>x==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Columns",placeholder:"Drop fields to measure"};return e.jsxs(e.Fragment,{children:[e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.List,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[g&&e.jsx(Re,{zone:"groupBy",fields:t,label:C().label,placeholder:C().placeholder,activeField:o}),v&&e.jsx(Re,{zone:"pivotBy",fields:n,label:"Pivot Columns",placeholder:"Drop fields to pivot data",activeField:o}),e.jsx(Re,{zone:"metrics",fields:a,label:A().label,placeholder:A().placeholder,hasPivotColumns:n.length>0,activeField:o}),a.length>=1&&e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:()=>i(!0),className:"mt-2 w-full justify-start text-xs text-muted-foreground hover:text-foreground",children:[e.jsx(s.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),m&&e.jsx(Re,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics",activeField:o})]})]}),!c&&e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings2,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(oa,{}),e.jsx(la,{}),e.jsx(zs,{}),e.jsx(ia,{}),e.jsx(Us,{}),x==="bullet"&&e.jsx(qs,{}),x==="funnel"&&e.jsx(Hs,{}),(x==="bubble"||x==="scatter")&&e.jsx(_s,{}),e.jsx($s,{}),e.jsx(Ks,{}),e.jsx(Gs,{})]})})]}),c&&e.jsxs(s.AccordionItem,{value:"plugin",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ns,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsx(Fs,{})})]})]}),e.jsx(Qs,{open:d,onOpenChange:i,availableMetrics:a,onSave:B=>{u(l.id,{metricColumns:[...a,B]})},cardId:l.id})]})}function da({onEditJoins:t}){const n=s.useEditorStore(c=>c.card),{autoJoinMetadata:a}=s.useDashboardCardQuery(n);if(!(a!=null&&a.autoResolved))return null;const{resolvedJoinPlan:r}=a,o=(r==null?void 0:r.joins)||[];if(o.length===0)return null;const d=c=>!c||c.length===0?"No conditions":c.map(l=>{var g,k,m,f;const u=`${(g=l.source)==null?void 0:g.entityName}.${(k=l.source)==null?void 0:k.name}`,x=`${(m=l.target)==null?void 0:m.entityName}.${(f=l.target)==null?void 0:f.name}`,h=l.operator||"=";return`${u} ${h} ${x}`}).join(" AND "),i=c=>!c.joinKeyGroups||c.joinKeyGroups.length===0?"No conditions defined":c.joinKeyGroups.length===1?d(c.joinKeyGroups[0].keys):c.joinKeyGroups.map((l,u)=>({id:u,operator:l.operator,condition:d(l.keys)}));return e.jsx(s.Card,{className:"border-blue-500/30 bg-blue-50/30 dark:bg-blue-950/20",children:e.jsxs("div",{className:"flex items-center justify-between p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dt,{className:"size-4 text-blue-600 dark:text-blue-400"}),e.jsx("h3",{className:"text-sm font-medium text-blue-900 dark:text-blue-100",children:"Auto-Resolved Joins"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"secondary",className:"cursor-help bg-blue-100 text-xs text-blue-700 dark:bg-blue-900 dark:text-blue-300",children:o.length})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:o.map((c,l)=>{const u=i(c),x=Array.isArray(u);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children:c.source.name}),e.jsx(s.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:c.target.name})]}),e.jsx(s.Badge,{variant:"outline",className:"border-green-500/40 bg-green-50/30 text-xs text-green-700 dark:bg-green-950/30 dark:text-green-300",children:c.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:x?u.map(h=>e.jsxs("div",{className:"rounded bg-muted/30 px-2 py-1",children:[e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:h.condition}),h.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",h.operator,")"]})]},h.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:u})})})]},c.id||l)})})})]})})]}),t&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:t,className:"h-7 gap-1 p-2 text-xs text-blue-700 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-100",children:e.jsx(s.SquarePen,{className:"size-3.5"})})]})})}const vs={getItem(t){if(typeof window>"u")return null;try{return localStorage.getItem(t)}catch(n){return console.warn(`Failed to read from localStorage (${t}):`,n),null}},setItem(t,n){if(!(typeof window>"u"))try{localStorage.setItem(t,n)}catch(a){console.warn(`Failed to write to localStorage (${t}):`,a)}}};function ua({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:o,sortByFields:d,activeField:i}){var p,j;const[c,l]=D.useState(()=>vs.getItem("chart-selector-expanded")==="true"),[u,x]=D.useState(!1),h=s.useEditorStore(S=>S.card),g=s.useEditorStore(S=>S.actions.updateCardConfig),k=a.length>0||r.length>0||o.length>0,{data:m,autoJoinMetadata:f}=s.useDashboardCardQuery(h),v=((p=h==null?void 0:h.config)==null?void 0:p.joinPlan)||(f!=null&&f.autoResolved?f.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),C=((j=h==null?void 0:h.dataSource)==null?void 0:j.selectedEntities)||[],A=S=>{g(h.id,{...h==null?void 0:h.config,joinPlan:S}),x(!1)},B=()=>{g(h.id,{...h==null?void 0:h.config,joinPlan:void 0}),x(!1)},O=()=>{x(!1)},E=()=>{x(!0)};D.useEffect(()=>{vs.setItem("chart-selector-expanded",String(c))},[c]);const N=()=>{l(S=>!S)};return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col border-x border-border",children:[e.jsxs("div",{className:s.cn("px-6 pt-4",{"space-y-4":c}),children:[e.jsx("div",{className:s.cn("overflow-hidden transition-all duration-300 ease-in-out",c?"max-h-[200px] opacity-100":"max-h-0 opacity-0"),children:c&&e.jsx(Hn,{selectedChart:t,onChartChange:n})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:"flex items-center justify-center",children:e.jsx(Yn,{selectedChart:t,onChartChange:n,isDropdownExpanded:c,onToggleDropdown:N})})]}),e.jsx("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:e.jsx("div",{className:s.cn("invisible flex gap-2",{visible:k||m}),children:e.jsx(_e.EditorClearButton,{})})}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx(da,{onEditJoins:E}),e.jsx(ca,{groupByFields:a,pivotByFields:r,metricsFields:o,sortByFields:d,activeField:i})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]}),e.jsx(Ts,{open:u,onOpenChange:x,joinPlan:v,availableDataSources:C,onSave:A,onCancel:O,onRemove:B,children:e.jsx("div",{})})]})}function ma({initialFilters:t,availableFields:n}={}){const[a,r]=D.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(E=>E.card.dataSource);const{columns:o,isLoading:d}=s.useColumns(),c=n||o||[],l={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=E=>{const N=p=>{if(p.id===E){const j=c[0]||l,S=s.getDataType(j.dataType)==="date";return{...p,conditions:[...p.conditions,{id:`condition-${Date.now()}`,field:j,operator:S?"between":"=",value:S?[]:""}]}}return{...p,groups:p.groups.map(N)}};r(N(a))},x=E=>{const N=p=>{if(p.id===E){const j=c[0]||l,S=s.getDataType(j.dataType)==="date";return{...p,groups:[...p.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:j,operator:S?"between":"=",value:S?[]:""}],groups:[]}]}}return{...p,groups:p.groups.map(N)}};r(N(a))},h=(E,N)=>{const p=j=>j.id===E?{...j,conditions:j.conditions.filter(S=>S.id!==N)}:{...j,groups:j.groups.map(p)};r(p(a))},g=(E,N)=>{const p=j=>j.id===E?{...j,groups:j.groups.filter(S=>S.id!==N)}:{...j,groups:j.groups.map(p)};r(p(a))},k=(E,N,p,j)=>{if(p==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const S=M=>M.id===E?{...M,conditions:M.conditions.map(y=>y.id===N?{...y,[p]:j}:y)}:{...M,groups:M.groups.map(S)};r(S(a))},m=(E,N,p)=>{const j=S=>S.id===E?{...S,conditions:S.conditions.map(M=>M.id===N?{...M,...p}:M)}:{...S,groups:S.groups.map(j)};r(j(a))},f=(E,N)=>{const p=j=>j.id===E?{...j,logicalOperator:N}:{...j,groups:j.groups.map(p)};r(p(a))},v=(E,N)=>{const p=j=>j.id===E?{...j,negate:N}:{...j,groups:j.groups.map(p)};r(p(a))},C=(E,N,p)=>{const j=S=>S.id===E?{...S,conditions:s.arrayMove(S.conditions,N,p)}:{...S,groups:S.groups.map(j)};r(j(a))},A=(E,N,p)=>{const j=S=>S.id===E?{...S,groups:s.arrayMove(S.groups,N,p)}:{...S,groups:S.groups.map(j)};r(j(a))},B=E=>{if(!E||E.conditions.length===0&&E.groups.length===0)return"-- No filters defined";const N=j=>{let S="";typeof j.field=="object"?S=j.field.entityName?`${j.field.entityName}.${j.field.name}`:j.field.name:S=String(j.field);const M=j.operator;let y=j.value;if(j.field.dataType==="string"&&!["in","not in"].includes(j.operator))typeof y=="string"?y=`'${y}'`:Array.isArray(y)&&(y=`'${y.join(", ")}'`);else if(j.field.dataType==="date"||j.field.dataType==="datetime"||j.field.dataType==="timestamp")if(j.operator==="between"&&Array.isArray(y)&&y.length===2){const b=y[0]?`'${y[0]}'`:"NULL",I=y[1]?`'${y[1]}'`:"NULL";return`${S} BETWEEN ${b} AND ${I}`}else if((j.operator==="in"||j.operator==="not in")&&Array.isArray(y)){const b=y.map(I=>I?`'${I}'`:"NULL").join(", ");return`${S} ${M} (${b})`}else typeof y=="string"||y instanceof Date?y=`'${y}'`:Array.isArray(y)&&y.length>0&&(y=`'${y[0]}'`);else if(["in","not in"].includes(j.operator)){let b=[];Array.isArray(y)?b=y.map(I=>typeof I=="string"?`'${I}'`:String(I)):typeof y=="string"?b=y.split(",").map(I=>{const F=I.trim();return j.field.dataType==="string"?`'${F}'`:F}):typeof y=="number"&&(b=[String(y)]),y=`(${b.join(", ")})`}switch(M){case"contains":return typeof y=="string"?`${S} LIKE '%${y.replace(/'/g,"")}'`:`${S} LIKE '%${String(y)}'`;case"startsWith":return typeof y=="string"?`${S} LIKE '${y.replace(/'/g,"")}%'`:`${S} LIKE '${String(y)}%'`;case"endsWith":return typeof y=="string"?`${S} LIKE '%${y.replace(/'/g,"")}'`:`${S} LIKE '%${String(y)}'`;case"isNull":return`${S} IS NULL`;case"isNotNull":return`${S} IS NOT NULL`;default:return`${S} ${M} ${y}`}},p=j=>{const S=j.conditions.map(N),M=j.groups.map(F=>p(F)),y=[...S,...M].filter(Boolean);if(y.length===0)return"";const b=y.join(` ${j.logicalOperator} `),I=y.length>1?`(${b})`:b;return j.negate?`NOT ${I}`:I};return p(E)},O=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:c,isLoading:d,addCondition:u,addGroup:x,removeCondition:h,removeGroup:g,updateCondition:k,updateConditionFields:m,updateGroupOperator:f,updateGroupNegate:v,reorderConditions:C,reorderGroups:A,generateSQLPreview:B,hasAnyFilters:O}}function xa({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const ha=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function pa({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:o="w-64"}){const[d,i]=D.useState(!1),c=D.useMemo(()=>{const l={};return a.forEach(u=>{const x=ha(u);l[x]||(l[x]={}),l[x][u.entityId]||(l[x][u.entityId]=[]),l[x][u.entityId].push(u)}),l},[a]);return e.jsxs(s.Popover,{modal:!0,open:d,onOpenChange:i,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":d,className:s.cn("justify-between",!t&&"text-muted-foreground",o),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(xa,{children:[t.entityName,".",t.name]})}):r,e.jsx(dt,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(c).map(([l,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),l]}),children:Object.entries(u).map(([x,h])=>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:[s.getEntityIcon(h[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:h[0].entityName})]}),h.map((g,k)=>e.jsxs(s.CommandItem,{value:g.id,onSelect:()=>{n(g),i(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===g.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:g.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:g.description&&e.jsx("span",{children:g.description})})]})]},g.id+k))]},`${l}-${x}`))},l))})]})})]})}function Xe(t){var f;const n=s.useEditorStore(v=>v.card),{authToken:a,tokenProps:r}=s.useSemaphorContext(),o=s.useEditorStore(v=>v.card.config),d=o==null?void 0:o.joinPlan,i={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},l={...i,role:"sortby",direction:"asc"},u={joinPlan:d,groupByColumns:[i],metricColumns:[c],sortByColumns:[l]},x=((f=n.dataSource)==null?void 0:f.connectionId)||n.connectionId,{data:h,isPending:g,error:k}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(a==null?void 0:a.accessToken)||"",{connection_id:x,cardConfig:u,cardDataSource:n.dataSource})}catch(v){console.log(t),console.error("error",v)}},enabled:!!x,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(v=>({label:v.value||"BLANK",value:v.value||"BLANK",count:(v==null?void 0:v.count)||0})),isPending:g,error:k}}function fa({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:o}){const[d,i]=qe.useState(!1),{filterValues:c}=Xe(t),l=x=>{a(n.filter(h=>h!==x))},u=x=>{n.includes(x)?a(n.filter(h=>h!==x)):a([...n,x])};return e.jsx("div",{className:s.cn("w-full",o),children:e.jsxs(s.Popover,{open:d,onOpenChange:i,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":d,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:n.length>0?n.map(x=>{const h=c.find(g=>g.value===x);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.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:g=>{g.key==="Enter"&&l(x)},onMouseDown:g=>{g.preventDefault(),g.stopPropagation()},onClick:g=>{g.stopPropagation(),l(x)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},x)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:c.map((x,h)=>e.jsxs(s.CommandItem,{onSelect:()=>u(x.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.includes(x.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:x.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x.count})]})]},x.value+h))})]})]})})]})})}function ga({field:t,value:n,onChange:a,placeholder:r="Select value...",className:o}){const{filterValues:d,isPending:i,error:c}=Xe(t);return i?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):c?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:n,onValueChange:a,children:[e.jsx(s.SelectTrigger,{className:o||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:d.map((l,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:l.value,children:l.label},l.value+u))})]})}function ja({value:t,operator:n,onChange:a,className:r}){var l;const{tokenProps:o}=s.useSemaphorContext(),d=(l=o==null?void 0:o.params)==null?void 0:l.timezone,i=D.useMemo(()=>{if(t){if(n==="between"||n==="not between"){if(Array.isArray(t)&&t.length===2){const u=t[0]?new Date(t[0]):void 0,x=t[1]?new Date(t[1]):void 0;if(u&&x)return{from:u,to:x}}}else if(n==="="||n==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(n===">"||n===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(n==="<"||n==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((n==="in"||n==="not in")&&Array.isArray(t)&&t.length>0){const u=new Date(t[0]),x=t.length>1?new Date(t[t.length-1]):u;if(!isNaN(u.getTime()))return{from:u,to:x}}}},[t,n]),c=u=>{if(!u){a(void 0);return}if(u.from&&u.to)a([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const x=new Date(u.from);x.setHours(23,59,59,999),a([u.from.toISOString(),x.toISOString()])}else if(u.to){const x=new Date(u.to);x.setHours(0,0,0,0),a([x.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:i,onChange:c,timezone:d,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const ba=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],va=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],ya=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Na=["=","!=","isNull","isNotNull"],Ca=["between","isNull","isNotNull"],Sa={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null","not between":"Not Between"};function ys(t){return Sa[t]||s.titleCase(t)}function wa(t){switch(t){case"string":return va;case"number":return ya;case"boolean":return Na;case"date":return Ca;default:return ba}}function Ys({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:o,onRemoveCondition:d,onUpdateGroupOperator:i,availableFields:c,updateConditionFields:l}){const{attributes:u,listeners:x,setNodeRef:h,transform:g,transition:k,isDragging:m}=s.useSortable({id:t.id}),{isPending:f,error:v}=Xe(t.field),C={transform:s.CSS.Transform.toString(g),transition:k};return e.jsxs("div",{ref:h,style:C,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${m?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...x,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(s.Select,{value:r,onValueChange:A=>i(a,A),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx(pa,{value:t.field,onValueChange:A=>{const B=A,O=s.getDataType(B.dataType)==="date";l(a,t.id,{field:B,value:"",operator:O?"between":"="})},availableFields:c,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:A=>{A==="in"||A==="not in"?l(a,t.id,{operator:A,value:[]}):A==="isNull"||A==="isNotNull"?l(a,t.id,{operator:A,value:null}):l(a,t.id,{operator:A,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?ys(t.operator):""})}),e.jsx(s.SelectContent,{children:wa(s.getDataType(t.field.dataType)).map(A=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:A,children:ys(A)},A))})]}),t.operator==="isNull"||t.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?f?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):v?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(fa,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(A=>typeof A=="string")?t.value:[],onChange:A=>l(a,t.id,{value:A}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input,{value:typeof t.value=="string"?t.value:"",onChange:A=>l(a,t.id,{value:A.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(ga,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:A=>l(a,t.id,{value:A}),placeholder:"Select value...",className:"flex-1"}):s.getDataType(t.field.dataType)==="boolean"?e.jsxs(s.Select,{value:typeof t.value=="boolean"?String(t.value):"",onValueChange:A=>l(a,t.id,{value:A==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):s.getDataType(t.field.dataType)==="date"?e.jsx(ja,{value:t.value,operator:t.operator,onChange:A=>l(a,t.id,{value:A}),className:"flex-1"}):e.jsx(s.Input,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:A=>o(a,t.id,"value",A.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>d(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function ka({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:d,onUpdateCondition:i,onUpdateField:c,onRemoveCondition:l,onReorderConditions:u,onReorderGroups:x,onAddCondition:h,onAddGroup:g,availableFields:k,renderFilterGroup:m,updateConditionFields:f}){const{attributes:v,listeners:C,setNodeRef:A,transform:B,transition:O,isDragging:E}=s.useSortable({id:t.id}),N={transform:s.CSS.Transform.toString(B),transition:O},p=S=>{const{active:M,over:y}=S;if(y&&M.id!==y.id){const b=t.conditions.findIndex(F=>F.id===M.id),I=t.conditions.findIndex(F=>F.id===y.id);b!==-1&&I!==-1&&u(t.id,b,I)}},j=S=>{const{active:M,over:y}=S;if(y&&M.id!==y.id&&a){const b=t.groups.findIndex(F=>F.id===M.id),I=t.groups.findIndex(F=>F.id===y.id);b!==-1&&I!==-1&&x(a,b,I)}};return e.jsxs("div",{ref:A,style:N,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${E?"z-50 opacity-50":""}`,children:[n>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",{...v,...C,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>o(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:S=>r(t.id,S),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>a&&d(a,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:p,children:e.jsx(s.SortableContext,{items:t.conditions.map(S=>S.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((S,M)=>e.jsx(Ys,{condition:S,index:M,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:i,onUpdateField:c,onRemoveCondition:l,onUpdateGroupOperator:r,availableFields:k,updateConditionFields:f},S.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:j,children:e.jsx(s.SortableContext,{items:t.groups.map(S=>S.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(S=>m(S,n+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>g(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Ta({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:o}){const{currentFilters:d,availableFields:i,isLoading:c,addCondition:l,addGroup:u,removeCondition:x,removeGroup:h,updateCondition:g,updateConditionFields:k,updateGroupOperator:m,updateGroupNegate:f,reorderConditions:v,reorderGroups:C,generateSQLPreview:A,hasAnyFilters:B,setCurrentFilters:O}=ma({initialFilters:t,availableFields:n}),E=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[N,p]=D.useState(!1),j=(y,b,I)=>{const F=T=>T.id===y?{...T,conditions:T.conditions.map(L=>L.id===b?{...L,field:I,dataType:I.dataType}:L)}:{...T,groups:T.groups.map(F)};O(F(d))},S=(y,b=0,I)=>b===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:F=>{const{active:T,over:L}=F;if(L&&T.id!==L.id){const w=y.conditions.findIndex(K=>K.id===T.id),R=y.conditions.findIndex(K=>K.id===L.id);w!==-1&&R!==-1&&v(y.id,w,R)}},children:e.jsx(s.SortableContext,{items:y.conditions.map(F=>F.id),strategy:s.verticalListSortingStrategy,children:y.conditions.map((F,T)=>e.jsx(Ys,{condition:F,index:T,groupId:y.id,groupLogicalOperator:y.logicalOperator,onUpdateCondition:g,onUpdateField:j,onRemoveCondition:x,onUpdateGroupOperator:m,availableFields:i,updateConditionFields:k},F.id))})}),e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:F=>{const{active:T,over:L}=F;if(L&&T.id!==L.id){const w=y.groups.findIndex(K=>K.id===T.id),R=y.groups.findIndex(K=>K.id===L.id);w!==-1&&R!==-1&&C(y.id,w,R)}},children:e.jsx(s.SortableContext,{items:y.groups.map(F=>F.id),strategy:s.verticalListSortingStrategy,children:y.groups.map(F=>S(F,b+1,y.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>l(y.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),N&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(y.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},y.id):e.jsx(ka,{group:y,depth:b,parentGroupId:I,onUpdateGroupOperator:m,onUpdateGroupNegate:f,onRemoveGroup:h,onUpdateCondition:g,onUpdateField:j,onRemoveCondition:x,onReorderConditions:v,onReorderGroups:C,onAddCondition:l,onAddGroup:u,availableFields:i,renderFilterGroup:S,updateConditionFields:k},y.id),M=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[c?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..."})]}):S(d),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(s.SmallSwitch,{id:"advanced-mode",checked:N,onCheckedChange:y=>p(y)}),e.jsx(s.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)"})]})}),B&&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:A(d)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:o,children:"Cancel"}),M>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(B?d:null),children:"Apply Filters"})]})]})}function Ea({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:o,isOpen:d,onOpenChange:i}){const c=u=>{a(t,u),i(!1)},l=()=>{r(t),i(!1)};return e.jsxs(s.Dialog,{modal:!1,open:d,onOpenChange:i,children:[d&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Ta,{filters:n,availableFields:o,onSave:c,onCancel:()=>i(!1),onClearAll:l})]})]})}function Aa({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var v,C;const[o,d]=D.useState(null),i=s.useEditorStore(A=>A.card),c=s.useEditorStore(A=>A.actions.updateCardConfig),l=(v=i==null?void 0:i.config)==null?void 0:v.joinPlan,u=(C=i==null?void 0:i.dataSource)==null?void 0:C.semanticDomainId,{data:x}=s.useJoinabilityMap(u),h=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")],g=D.useCallback(A=>A.startsWith("card-")?null:A.startsWith("source-")||n.find(B=>B.id===A)?"source":a("groupBy").find(B=>B.id===A)?"groupBy":a("metrics").find(B=>B.id===A)?"metrics":a("pivotBy").find(B=>B.id===A)?"pivotBy":a("sortBy").find(B=>B.id===A)?"sortBy":null,[n,a]),k=D.useCallback(A=>{d(A.active.id)},[]),m=D.useCallback(A=>{var S;const{active:B,over:O}=A;if(!O||!t){d(null);return}const E=B.id,N=O.id,p=g(E),j=g(N)||N;if(j==="sortBy"){if(p==="source"){const M=n.find(b=>b.id===E);if(!M){d(null);return}if(!(a("groupBy").some(b=>b.name===M.name&&b.qualifiedEntityName===M.qualifiedEntityName)||a("metrics").some(b=>b.name===M.name&&b.qualifiedEntityName===M.qualifiedEntityName))){d(null);return}}else if(p==="pivotBy"){d(null);return}else if(p!=="groupBy"&&p!=="metrics"&&p!=="sortBy"){d(null);return}}if(p==="source"&&j==="sortBy"){const M=[...n].find(F=>F.id===E);if(!M){d(null);return}const y=a("sortBy");if(s.fieldAlreadyExists(M,y)){d(null);return}const b=s.validateFieldForChartType(M,"sortBy",i.type);if(!b.isValid){s.ue.error("Invalid Field Type",{description:b.reason,position:"top-center",duration:3e3}),d(null);return}const I=s.getNewField(M,"sortBy",y);d(null),r("sortBy",[...y,I]);return}if(p==="source"&&j!=="source"&&j!=="sortBy"){const M=[...n].find(L=>L.id===E);if(!M){d(null);return}const y=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(y.length>0){const L=y[0].qualifiedEntityName;if(!L){d(null);return}if(L!==M.qualifiedEntityName&&M.qualifiedEntityName)if(u&&(x!=null&&x.joinabilityMap)){if(s.calculateFieldState(M,{joinabilityMap:x.joinabilityMap,selectedFields:y,baseEntityName:(S=l==null?void 0:l.baseEntity)==null?void 0:S.name}).state==="unreachable"){s.showJoinRequiredNotification(),d(null);return}}else{if(!l){s.showJoinRequiredNotification(),d(null);return}if(!s.areEntitiesJoined(L,M.qualifiedEntityName,l)){s.showJoinRequiredNotification(),d(null);return}}}const b=a(j);if(s.fieldAlreadyExists(M,b)){d(null);return}const I=s.validateFieldForChartType(M,j,i.type);if(!I.isValid){s.ue.error("Invalid Field Type",{description:I.reason,position:"top-center",duration:3e3}),d(null);return}const F=s.getNewField(M,j,b),T=[...b,F];d(null),r(j,T),j==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(i.type,i.config,c,t,T);return}if(p&&j&&p!=="source"&&j!=="source"&&p!==j){const M=a(p),y=a(j),b=M.find(w=>w.id===E);if(!b){d(null);return}const I=s.validateFieldForChartType(b,j,i.type);if(!I.isValid){s.ue.error("Invalid Field Type",{description:I.reason,position:"top-center",duration:3e3}),d(null);return}const F=s.getNewField(b,j,y);if(d(null),j==="sortBy"){s.fieldAlreadyExists(b,y)||r(j,[...y,F]);return}const T=M.filter(w=>w.id!==E),L=[...y,F];r(p,T),r(j,L),j==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(i.type,i.config,c,t,L);return}if(p&&j&&p===j&&p!=="source"){const M=a(p),y=M.findIndex(I=>I.id===E),b=M.findIndex(I=>I.id===N);if(y!==b){const I=s.arrayMove(M,y,b);r(p,I)}}d(null)},[t,n,a,r,g,l,u,x,i.type,c,i.config]),f=o?h.find(A=>A.id===o):null;return{activeId:o,activeField:f,handleDragStart:k,handleDragEnd:m}}function Ia({activeView:t,onViewChange:n,splitViewEnabled:a}){const r=s.useEditorStore(l=>l.card),{config:o}=D.useContext(s.SemaphorContext).tokenProps,d=(o==null?void 0:o.showInfoTab)!==!1,{errorMessage:i}=s.useDashboardCardQuery(r),c=()=>a?!1:!["table","pivotTable","aggregateTable"].includes(r.type);return e.jsx(s.Tabs,{value:t,onValueChange:l=>n(l),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),c()&&e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),r.type!=="kpi"&&d&&e.jsx(s.TabsTrigger,{value:"info",className:s.cn("rounded-md transition data-[state=active]:bg-muted",i&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:i?"Error":"Info"})]})})}const Da=[{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 Ma(){var l,u;const t=s.useEditorStore(x=>x.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=D.useState(!1),[o,d]=D.useState(""),i=x=>{if(x==="custom"){r(!0);return}r(!1),n(t.id,parseInt(x))},c=x=>{const h=x.target.value;d(h),h&&!isNaN(parseInt(h))&&n(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(s.Input$1,{type:"number",value:o,onChange:c,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(l=t.config)==null?void 0:l.rowLimit)==null?void 0:u.toString())||"100",onValueChange:i,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:Da.map(x=>e.jsx(s.SelectItem,{value:x.value,children:x.label},x.value))})]})})}function La({card:t,queryData:n,isLoading:a,isFetching:r,pagination:o,onPaginationChange:d,onSortChange:i,sortState:c,splitViewEnabled:l}){const u=D.useMemo(()=>(n==null?void 0:n.records)||[],[n==null?void 0:n.records]);return!l||["table","pivotTable","aggregateTable"].includes(t.type)?e.jsx(Ue,{}):e.jsxs(s.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(s.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:e.jsx(Ue,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:(n==null?void 0:n.records)&&e.jsx(s.TableVisual,{card:t,data:u,paginationMetadata:o,onPaginationChange:d,isLoading:a||r,onSortChange:i,sortState:c})})})]})}const Fa="semaphor-split-view-enabled";function Ba(){return Ve(Fa,!0)}function Oa({isOpen:t,onClose:n}){const a=rt.useClickOutside(n,{enabled:t}),r=s.useEditorStore(x=>{var h;return((h=x.card.customCardPreferences)==null?void 0:h.url)||""}),o=s.useEditorStore(x=>x.card),d=s.useEditorStore(x=>{var h;return((h=x.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),i=s.useEditorStore(x=>{var h;return((h=x.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:c}=s.useDashboardCardQuery(o),{getCard:l}=s.useCustomVisual(r),u=D.useMemo(()=>!r||r.trim()===""?null:l("Chart Settings"),[l,r]);return e.jsx("div",{ref:a,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:n,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(D.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(c==null?void 0:c.records)||[],chartType:d,settings:i})})})]})})}function Ra({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onFiltersClick:o,activeCard:d,columns:i,columnsLoading:c,columnsError:l}){var J,ne,le;const u=s.useEditorStore(Z=>Z.card),x=s.useDashboardStore(Z=>Z.filterValues),h=s.useDashboardStore(Z=>Z.selectedSheetId),g=s.useDashboardStore(Z=>Z.inlineFilterValuesMap[(d==null?void 0:d.id)||""]),{updateCardConfig:k,setCard:m,updateCardInFrame:f,setShowAIDialog:v}=s.useEditorActions(),C=s.useEditorStore(Z=>Z.showAIDialog),A=s.useDashboardStore(Z=>Z.isVisualEditing),[B,O]=D.useState(!1),[E,N]=D.useState(!1),[p,j]=D.useState(null),{config:S}=D.useContext(s.SemaphorContext).tokenProps,M=(S==null?void 0:S.showInfoTab)!==!1,[y,b]=Ba(),I=s.useEditorStore(Z=>{var oe;return((oe=Z.card.customCardPreferences)==null?void 0:oe.url)&&Z.card.type==="custom"}),{data:F,errorMessage:T,isLoading:L,isFetching:w,errorSql:R,pagination:K,refetch:_,comparisonMetadata:G}=s.useDashboardCardQuery(d),q=D.useMemo(()=>(F==null?void 0:F.records)||[],[F==null?void 0:F.records]),[V,z]=D.useState(!1);D.useEffect(()=>{w||z(!1)},[w]);const H=()=>{const Z=!y;Z&&t==="table"&&n("chart"),b(Z)},P=(Z,oe)=>{const $={...d,paginationConfig:{page:Z+1,pageSize:oe}};m($),f($)};function W(){return e.jsxs("div",{className:"relative border-b border-border bg-background p-4",children:[e.jsx("button",{onClick:r,className:"absolute right-4 top-4 rounded-md p-1 hover:bg-muted","aria-label":"Close Debug Panel",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsxs("div",{className:"space-y-4 pr-8",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(u.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(x||{},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(d.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",i.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:c?"Loading...":l?"Error loading columns":JSON.stringify(i.slice(0,5),null,2)})]})]})]})}const Y=Z=>{if(!u.config)return;const oe=s.sortStateToSortByColumns(Z,u.config.metricColumns,u.config.groupByColumns);k(u.id,{...u.config,sortByColumns:oe})},ee=D.useMemo(()=>{var Z;return s.sortByColumnsToSortState((Z=u.config)==null?void 0:Z.sortByColumns)},[(J=u.config)==null?void 0:J.sortByColumns]);return e.jsxs("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":C&&A}),children:[a&&W(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&C&&e.jsx(Ms,{variant:"outline"}),e.jsx(Ia,{activeView:t,onViewChange:n,splitViewEnabled:y}),e.jsx(s.FilterInfo,{cardId:d.id,cardFilters:(ne=d.config)==null?void 0:ne.filters,cardFilterCount:s.getFilterCount(((le=d.config)==null?void 0:le.filters)||null),onFiltersClick:o,inlineFilters:d.inlineFilters,inlineFilterValues:g,sheetId:h||""}),G&&e.jsx(s.ComparisonMetadataBadge,{metadata:G,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Ma,{})}),C&&e.jsx(_e.EditorClearButton,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:L||w,onClick:()=>{z(!0),_()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":V})})}),t==="chart"&&e.jsx(s.IconButton,{tooltip:y?"Hide Results Table":"Show Results Table",onClick:H,children:y?e.jsx(ht,{className:"size-4"}):e.jsx(Et,{className:"size-4"})}),t==="chart"&&e.jsx(e.Fragment,{children:e.jsx(Ls,{})}),!C&&e.jsx(s.IconButton,{onClick:()=>v(!C),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),r&&s.isDevEnv]})]}),!B&&I&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>O(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(s.Settings2,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex min-h-0 grow flex-col",children:[t==="chart"&&e.jsx("div",{className:s.cn("flex grow flex-col pb-6",{"pb-0":y&&!["table","pivotTable","aggregateTable"].includes(d.type)}),children:e.jsx(La,{card:d,queryData:F,isLoading:L,isFetching:w,pagination:K,onPaginationChange:P,onSortChange:Y,sortState:ee,splitViewEnabled:y})}),t==="table"&&(F==null?void 0:F.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:d,data:q,paginationMetadata:K,onPaginationChange:P,isLoading:L||w,onSortChange:Y,sortState:ee})}),t==="info"&&M&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col pb-6",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col rounded-md bg-background px-6",children:T?e.jsx(Je,{error:T,errorSql:R,onSendFeedback:()=>{const Z=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:u.config,dataSource:d.dataSource,dashboardFilters:x,errorMessage:T,errorSql:R,generatedSql:F==null?void 0:F.sql});j(Z),N(!0)},onOpenInEditor:()=>{v(!0),setTimeout(()=>{const Z=s.useEditorStore.getState().actions;Z.setIsDevMode(!0),Z.setCardSql(R||""),setTimeout(()=>{Z.setRunSql(!0)},100)},100)}}):e.jsx(As,{sql:F==null?void 0:F.sql,error:T,errorSql:R})})})]}),e.jsx(Oa,{isOpen:B,onClose:()=>O(!1)}),p&&e.jsx(s.FeedbackDialog,{open:E,onOpenChange:N,feedbackData:p})]})]})}function Pa({activeField:t}){const[n,a]=D.useState(!0);return D.useEffect(()=>{t&&a(!0)},[t]),t?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 ${n?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(We,{dataType:t.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:t.label||t.name})]}):null}const Va=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const n=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},a=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",n,!0),window.addEventListener("unhandledrejection",a,!0),()=>{console.error=t,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function za({column:t,isSelected:n,onSelect:a,availableFields:r,width:o,onWidthChange:d}){var K,_,G;const i=s.useEditorStore(q=>q.card),{updateCardConfig:c,removeGroupByColumn:l,removeMetricColumn:u,updateFilters:x}=s.useEditorActions(),[h,g]=D.useState(!1),[k,m]=D.useState(!1),f=D.useRef(null),v=D.useCallback(q=>{q.preventDefault(),q.stopPropagation(),m(!0),f.current={startX:q.clientX,startWidth:o||150};const V=H=>{if(!f.current)return;const P=H.clientX-f.current.startX,W=Math.max(80,f.current.startWidth+P);d==null||d(t.id,W)},z=()=>{m(!1),f.current=null,document.removeEventListener("mousemove",V),document.removeEventListener("mouseup",z)};document.addEventListener("mousemove",V),document.addEventListener("mouseup",z)},[o,t.id,d]),C=(K=i==null?void 0:i.config)==null?void 0:K.filters,A=(_=C==null?void 0:C.conditions)==null?void 0:_.some(q=>q.field.name===t.name&&q.field.qualifiedEntityName===t.qualifiedEntityName),B=q=>{q?x(i.id,q):c(i.id,{filters:void 0})},{attributes:O,listeners:E,setNodeRef:N,transform:p,transition:j,isDragging:S}=s.useSortable({id:t.id}),M={transform:s.CSS.Transform.toString(p),transition:j},y=s.getDataType(t.dataType),b=$a(y),I=()=>{var z;const q=((z=i==null?void 0:i.config)==null?void 0:z.sortByColumns)||[],V=q.findIndex(H=>H.name===t.name);if(V!==-1){const H=[...q];H[V]={...H[V],direction:"asc"},c(i.id,{sortByColumns:H})}else c(i.id,{sortByColumns:[...q,{...t,id:`sort-${t.id}`,role:"sortby",direction:"asc"}]})},F=()=>{var z;const q=((z=i==null?void 0:i.config)==null?void 0:z.sortByColumns)||[],V=q.findIndex(H=>H.name===t.name);if(V!==-1){const H=[...q];H[V]={...H[V],direction:"desc"},c(i.id,{sortByColumns:H})}else c(i.id,{sortByColumns:[...q,{...t,id:`sort-${t.id}`,role:"sortby",direction:"desc"}]})},T=()=>{var z;const q=((z=i==null?void 0:i.config)==null?void 0:z.groupByColumns)||[];if(!q.some(H=>H.name===t.name)){const H={...t,id:`groupby-${t.id}-${Date.now()}`,role:"groupby"};c(i.id,{groupByColumns:[...q,H]})}},L=q=>{var H;const V=((H=i==null?void 0:i.config)==null?void 0:H.metricColumns)||[];if(!V.some(P=>P.name===t.name&&P.aggregate===q)){const P={...t,id:`metric-${t.id}-${q}-${Date.now()}`,label:`${q} of ${t.label||t.name}`,role:"metric",aggregate:q};c(i.id,{metricColumns:[...V,P]})}},w=()=>{t.role==="groupby"?l(i.id,t.id):t.role==="metric"&&u(i.id,t.id)},R={...M,width:o?`${o}px`:void 0,minWidth:o?`${o}px`:"120px"};return e.jsxs("th",{ref:N,style:R,className:s.cn("group relative border-r border-border bg-background px-1 py-0",S&&"opacity-50",n&&"bg-primary/10",k&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...O,...E,className:"cursor-grab p-1 text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100 active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-3 w-3"})}),e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs("button",{onClick:a,className:s.cn("flex flex-1 items-center justify-between gap-1 rounded px-2 py-2 text-left text-sm font-medium transition-colors hover:bg-muted/50",n&&"bg-primary/10"),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(b,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:t.label||t.name}),t.role==="metric"&&t.aggregate&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",t.aggregate,")"]}),A&&e.jsx(s.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(s.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(s.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(s.DropdownMenuItem,{onClick:()=>g(!0),children:[e.jsx(s.Filter,{className:s.cn("mr-2 h-4 w-4",A&&"text-primary")}),A?"Edit Filter":"Filter"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:I,children:[e.jsx(it,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(s.DropdownMenuItem,{onClick:F,children:[e.jsx(ot,{className:"mr-2 h-4 w-4"}),"Sort Z → A"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuSub,{children:[e.jsxs(s.DropdownMenuSubTrigger,{children:[e.jsx(s.Calculator,{className:"mr-2 h-4 w-4"}),"Summarize"]}),e.jsxs(s.DropdownMenuSubContent,{children:[e.jsx(s.DropdownMenuItem,{onClick:()=>L("SUM"),children:"Sum"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("AVG"),children:"Average"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("COUNT"),children:"Count"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("DISTINCT"),children:"Count Distinct"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("MIN"),children:"Min"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("MAX"),children:"Max"})]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:T,children:[e.jsx(He,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(s.DropdownMenuItem,{disabled:!0,children:[e.jsx(Ss,{className:"mr-2 h-4 w-4"}),"Pivot by this column"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{disabled:!0,children:[e.jsx(s.EyeOff,{className:"mr-2 h-4 w-4"}),"Hide column"]}),e.jsxs(s.DropdownMenuItem,{onClick:w,className:"text-destructive focus:text-destructive",children:[e.jsx(s.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:v,className:s.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",k&&"bg-primary")}),e.jsx(Js,{open:h,onOpenChange:g,availableFields:r.length>0?r:[t],existingFilters:C,editingCondition:A?(G=C==null?void 0:C.conditions)==null?void 0:G.find(q=>q.field.name===t.name&&q.field.qualifiedEntityName===t.qualifiedEntityName):void 0,onSave:B})]})}function $a(t){switch(t){case"number":return s.Hash;case"date":return s.Calendar;case"string":default:return s.Type}}function Ka({selectedColumn:t,onColumnSelect:n,isLoading:a=!1,sourceFields:r=[]}){var j,S,M,y;const o=s.useEditorStore(b=>b.card),{updateCardConfig:d}=s.useEditorActions(),[i,c]=D.useState(null),[l,u]=D.useState({}),[x,h]=D.useState(!1),g=D.useMemo(()=>{var F,T;const b=((F=o==null?void 0:o.config)==null?void 0:F.groupByColumns)||[],I=((T=o==null?void 0:o.config)==null?void 0:T.metricColumns)||[];return[...b,...I]},[(j=o==null?void 0:o.config)==null?void 0:j.groupByColumns,(S=o==null?void 0:o.config)==null?void 0:S.metricColumns]),k=D.useMemo(()=>{const b=new Set(g.map(I=>`${I.qualifiedEntityName}.${I.name}`));return r.filter(I=>!b.has(`${I.qualifiedEntityName}.${I.name}`))},[r,g]),{data:m,isLoading:f}=s.useDashboardCardQuery(o),v=(m==null?void 0:m.records)||[],C=D.useCallback((b,I)=>{u(F=>({...F,[b]:I}))},[]),A=D.useCallback(b=>{var L,w;const I=s.getDataType(b.dataType),F=((L=o==null?void 0:o.config)==null?void 0:L.groupByColumns)||[],T=((w=o==null?void 0:o.config)==null?void 0:w.metricColumns)||[];if(I==="number"){const R={...b,id:`metric-${b.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};d(o.id,{metricColumns:[...T,R]})}else{const R={...b,id:`groupby-${b.id}-${Date.now()}`,role:"groupby"};d(o.id,{groupByColumns:[...F,R]})}h(!1)},[(M=o==null?void 0:o.config)==null?void 0:M.groupByColumns,(y=o==null?void 0:o.config)==null?void 0:y.metricColumns,o.id,d]),B=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),O=b=>{c(b.active.id)},E=b=>{const{active:I,over:F}=b;if(c(null),!F||I.id===F.id)return;const T=g.findIndex(w=>w.id===I.id),L=g.findIndex(w=>w.id===F.id);if(T!==-1&&L!==-1){const w=s.arrayMove(g,T,L),R=w.filter(_=>_.role==="groupby"),K=w.filter(_=>_.role==="metric");d(o.id,{groupByColumns:R,metricColumns:K})}},N=i?g.find(b=>b.id===i):null,p=b=>{let I="";for(;b>=0;)I=String.fromCharCode(b%26+65)+I,b=Math.floor(b/26)-1;return I};return a?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):g.length===0?e.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-4 p-8 text-center",children:e.jsxs("div",{className:"rounded-lg border-2 border-dashed border-muted-foreground/25 p-12",children:[e.jsx("h3",{className:"text-lg font-medium text-muted-foreground",children:"No columns selected"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground/75",children:"Select columns from the panel on the right to build your table"})]})}):e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(s.DndContext,{sensors:B,collisionDetection:s.closestCenter,onDragStart:O,onDragEnd:E,children:[e.jsxs("table",{className:"w-full border-collapse",children:[e.jsxs("thead",{children:[e.jsxs("tr",{className:"border-b border-border bg-muted/30",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-1 text-center text-xs font-medium text-muted-foreground"}),e.jsx(s.SortableContext,{items:g.map(b=>b.id),strategy:s.horizontalListSortingStrategy,children:g.map((b,I)=>e.jsx("th",{style:{width:l[b.id]?`${l[b.id]}px`:void 0,minWidth:l[b.id]?`${l[b.id]}px`:"120px"},className:"border-r border-border bg-muted/30 px-2 py-1 text-center text-xs font-medium text-muted-foreground",children:p(I)},`letter-${b.id}`))}),e.jsx("th",{className:"w-10 border-r border-border bg-muted/30 px-2 py-1"})]}),e.jsxs("tr",{className:"border-b-2 border-border bg-background",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-2 text-center text-xs font-medium text-muted-foreground",children:"#"}),e.jsx(s.SortableContext,{items:g.map(b=>b.id),strategy:s.horizontalListSortingStrategy,children:g.map(b=>e.jsx(za,{column:b,isSelected:(t==null?void 0:t.id)===b.id,onSelect:()=>n(b),availableFields:r,width:l[b.id],onWidthChange:C},b.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(s.Popover,{open:x,onOpenChange:h,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Add column",children:e.jsx(s.Plus,{className:"h-4 w-4"})})}),e.jsx(s.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search columns..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No columns available."}),e.jsx(s.CommandGroup,{heading:"Available Columns",children:k.map(b=>{const I=s.getDataType(b.dataType),F=I==="number"?s.Hash:I==="date"?s.Calendar:s.Type;return e.jsxs(s.CommandItem,{value:b.label||b.name,onSelect:()=>A(b),children:[e.jsx(F,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm",children:b.label||b.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:b.entityName})]})]},b.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:f?e.jsx("tr",{children:e.jsx("td",{colSpan:g.length+2,className:"h-32 text-center",children:e.jsx(s.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):v.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:g.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):v.slice(0,100).map((b,I)=>e.jsxs("tr",{className:s.cn("border-b border-border transition-colors hover:bg-muted/50",I%2===0?"bg-background":"bg-muted/20"),children:[e.jsx("td",{className:"sticky left-0 z-10 w-12 border-r border-border bg-muted/50 px-2 py-2 text-center text-xs font-medium text-muted-foreground",children:I+1}),g.map(F=>{const T=b[F.name]??b[F.label??""];return e.jsx("td",{style:{width:l[F.id]?`${l[F.id]}px`:void 0,minWidth:l[F.id]?`${l[F.id]}px`:"120px"},className:s.cn("border-r border-border px-3 py-2 text-sm",(t==null?void 0:t.id)===F.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:Ga(T,F)})},`${I}-${F.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},I))})]}),e.jsx(s.DragOverlay,{children:N&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:N.label||N.name})})]})}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border bg-muted/30 px-4 py-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Showing ",Math.min(v.length,100)," of ",v.length," rows"]}),e.jsxs("span",{children:[g.length," columns"]})]})]})}function Ga(t,n){if(t==null)return"—";if(typeof t=="number")return n.role==="metric"?new Intl.NumberFormat("en-US",{minimumFractionDigits:0,maximumFractionDigits:2}).format(t):t.toString();if(t instanceof Date||typeof t=="string"&&!isNaN(Date.parse(t))){const a=new Date(t);if(!isNaN(a.getTime()))return a.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(t)}function qa({entityGroups:t,isLoading:n=!1}){var B,O;const a=s.useEditorStore(E=>E.card),{updateCardConfig:r,removeGroupByColumn:o,removeMetricColumn:d}=s.useEditorActions(),[i,c]=D.useState(!0),[l,u]=D.useState(""),[x,h]=D.useState(new Set),g=((B=a==null?void 0:a.config)==null?void 0:B.groupByColumns)||[],k=((O=a==null?void 0:a.config)==null?void 0:O.metricColumns)||[],m=E=>{const N=new Set(x);N.has(E)?N.delete(E):N.add(E),h(N)},f=E=>g.some(N=>N.name===E.name&&N.qualifiedEntityName===E.qualifiedEntityName)||k.some(N=>N.name===E.name&&N.qualifiedEntityName===E.qualifiedEntityName),v=(E,N)=>{if(N)if(s.getDataType(E.dataType)==="number"){const j={...E,id:`metric-${E.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(a.id,{metricColumns:[...k,j]})}else{const j={...E,id:`groupby-${E.id}-${Date.now()}`,role:"groupby"};r(a.id,{groupByColumns:[...g,j]})}else{const p=g.findIndex(S=>S.name===E.name&&S.qualifiedEntityName===E.qualifiedEntityName),j=k.findIndex(S=>S.name===E.name&&S.qualifiedEntityName===E.qualifiedEntityName);p!==-1&&o(a.id,g[p].id),j!==-1&&d(a.id,k[j].id)}},C=E=>{if(!l)return E;const N=l.toLowerCase();return E.filter(p=>p.name.toLowerCase().includes(N)||p.label&&p.label.toLowerCase().includes(N))},A=E=>{switch(s.getDataType(E)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.Type}};return i?e.jsxs("div",{className:"flex h-full w-72 flex-col border-l border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Columns"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>c(!1),title:"Close panel",children:e.jsx(wt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search columns...",value:l,onChange:E=>u(E.target.value),className:"h-8 pl-8 text-sm"})]})}),(g.length>0||k.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[g.length>0&&e.jsxs(s.Collapsible,{defaultOpen:!0,children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(He,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsx("span",{children:"Groupings"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:g.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:g.map(E=>{const N=A(E.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(s.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(N,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:E.label||E.name}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>o(a.id,E.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},E.id)})})})]}),k.length>0&&e.jsxs(s.Collapsible,{defaultOpen:!0,children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(s.Calculator,{className:"h-3.5 w-3.5 text-green-500"}),e.jsx("span",{children:"Metrics"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:k.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:k.map(E=>{const N=A(E.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(s.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(N,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:E.label||E.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:E.aggregate}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>d(a.id,E.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},E.id)})})})]})]}),e.jsx(s.ScrollArea,{className:"flex-1",children:e.jsx("div",{className:"p-2",children:n?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent"})}):t.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No columns available"}):t.map(E=>{const N=C(E.columns);if(N.length===0)return null;const p=x.has(E.entityId)||l.length>0;return e.jsxs(s.Collapsible,{open:p,onOpenChange:()=>m(E.entityId),children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:s.cn("h-3.5 w-3.5 transition-transform duration-200",p&&"rotate-90")}),e.jsx(s.Table2,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate text-left",children:E.label||E.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:N.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:N.map(j=>{const S=A(j.dataType),M=f(j);return e.jsxs("label",{className:s.cn("flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-sm transition-colors hover:bg-muted/50",M&&"bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:M,onCheckedChange:y=>v(j,y),className:"h-3.5 w-3.5"}),e.jsx(S,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:j.label||j.name})]},j.id)})})})]},E.entityId)})})})]}):e.jsx("div",{className:"flex h-full items-start border-l border-border bg-muted/30 p-2",children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(!0),title:"Open panel",children:e.jsx(kt,{className:"h-4 w-4"})})})}const Ua=[{name:"SUM",description:"Sum of values",syntax:"SUM([column])"},{name:"AVG",description:"Average of values",syntax:"AVG([column])"},{name:"COUNT",description:"Count of rows",syntax:"COUNT([column])"},{name:"COUNTD",description:"Count distinct values",syntax:"COUNTD([column])"},{name:"MIN",description:"Minimum value",syntax:"MIN([column])"},{name:"MAX",description:"Maximum value",syntax:"MAX([column])"},{name:"IF",description:"Conditional logic",syntax:"IF(condition, then, else)"},{name:"CASE",description:"Multiple conditions",syntax:"CASE WHEN ... THEN ... END"},{name:"CONCAT",description:"Concatenate text",syntax:"CONCAT([col1], [col2])"},{name:"ROUND",description:"Round number",syntax:"ROUND([column], decimals)"},{name:"FLOOR",description:"Round down",syntax:"FLOOR([column])"},{name:"CEIL",description:"Round up",syntax:"CEIL([column])"},{name:"ABS",description:"Absolute value",syntax:"ABS([column])"},{name:"DATEPART",description:"Extract date part",syntax:"DATEPART(year, [date])"},{name:"DATEDIFF",description:"Difference between dates",syntax:"DATEDIFF(day, [date1], [date2])"}];function _a({value:t,onChange:n,onSubmit:a,onCancel:r,selectedColumn:o,availableColumns:d}){const[i,c]=D.useState(!1),[l,u]=D.useState("column"),x=D.useRef(null);D.useEffect(()=>{const m=f=>{f.key==="Escape"&&t?r():f.key==="Enter"&&t&&!i&&a(t)};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[t,r,a,i]);const h=m=>{const f=`[${m.label||m.name}]`,v=x.current;if(v){const C=v.selectionStart||0,A=v.selectionEnd||0,B=t.slice(0,C)+f+t.slice(A);n(B),setTimeout(()=>{v.setSelectionRange(C+f.length,C+f.length),v.focus()},0)}else n(t+f);c(!1)},g=m=>{const f=x.current;if(f){const v=f.selectionStart||0,C=f.selectionEnd||0,A=t.slice(0,v)+m.syntax+t.slice(C);n(A),setTimeout(()=>{f.setSelectionRange(v+m.name.length+1,v+m.syntax.length-1),f.focus()},0)}else n(t+m.syntax);c(!1)},k=m=>{switch(s.getDataType(m)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.Type}};return e.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-1.5",children:[e.jsx("div",{className:"flex min-w-[100px] items-center justify-center rounded border border-border bg-background px-2 py-1 text-xs font-medium text-muted-foreground",children:o?e.jsx("span",{className:"truncate",children:o.label||o.name}):e.jsx("span",{children:"—"})}),e.jsxs(s.Popover,{open:i&&l==="function",onOpenChange:m=>{c(m),m&&u("function")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Insert function",children:e.jsx(Tt,{className:"h-4 w-4"})})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search functions..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No functions found."}),e.jsx(s.CommandGroup,{heading:"Functions",children:Ua.map(m=>e.jsx(s.CommandItem,{value:m.name,onSelect:()=>g(m),children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm font-medium",children:m.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:m.syntax})]})},m.name))})]})]})})]}),e.jsxs(s.Popover,{open:i&&l==="column",onOpenChange:m=>{c(m),m&&u("column")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",className:"h-7 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground",title:"Insert column reference",children:[e.jsx("span",{children:"Columns"}),e.jsx(s.ChevronDown,{className:"h-3 w-3"})]})}),e.jsx(s.PopoverContent,{className:"w-[250px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search columns..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No columns found."}),e.jsx(s.CommandGroup,{heading:"Available Columns",children:d.map(m=>{const f=k(m.dataType);return e.jsxs(s.CommandItem,{value:m.label||m.name,onSelect:()=>h(m),children:[e.jsx(f,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:m.label||m.name})]},m.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(s.Input$1,{ref:x,value:t,onChange:m=>n(m.target.value),placeholder:"Enter a formula or select a column...",className:"h-7 border-border bg-background font-mono text-sm"})}),t&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-destructive hover:bg-destructive/10 hover:text-destructive",onClick:r,title:"Cancel (Esc)",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-green-600 hover:bg-green-600/10 hover:text-green-600",onClick:()=>a(t),title:"Apply (Enter)",children:e.jsx(s.Check,{className:"h-4 w-4"})})]})]})}function Ha({className:t}){var g,k,m,f;const n=s.useEditorStore(v=>v.card),[a,r]=D.useState(null),[o,d]=D.useState(""),{columns:i=[],columnGroups:c=[],isLoading:l}=s.useColumns();(g=n==null?void 0:n.config)!=null&&g.groupByColumns,(k=n==null?void 0:n.config)!=null&&k.metricColumns,(m=n==null?void 0:n.config)!=null&&m.groupByColumns,(f=n==null?void 0:n.config)!=null&&f.pivotByColumns;const u=v=>{r(v),d(v?`[${v.label||v.name}]`:"")},x=v=>{console.log("Formula submitted:",v),d(""),r(null)},h=()=>{d(""),r(null)};return e.jsxs("div",{className:s.cn("flex h-full w-full flex-col",t),children:[e.jsx(_a,{value:o,onChange:d,onSubmit:x,onCancel:h,selectedColumn:a,availableColumns:i}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(Ka,{selectedColumn:a,onColumnSelect:u,isLoading:l,sourceFields:i})}),e.jsx(qa,{entityGroups:c,isLoading:l})]})]})}function Ja(){var K,_;const[t,n]=D.useState("chart"),[a,r]=D.useState(!1),[o,d]=D.useState(!1),[i,c]=D.useState(!0),l=s.useEditorStore(G=>G.showAIDialog),u=s.useDashboardStore(G=>G.isVisualEditing),{setCardType:x}=s.useEditorActions(),h=s.useEditorStore(G=>G.card.type);D.useEffect(()=>Va(),[]);const g=G=>{x(G)},k=s.useEditorStore(G=>G.frame),m=s.useEditorStore(G=>G.card);s.useEditorStore(G=>G.activeTabCardId),s.useEditorStore(G=>G.actions.getAvailableFields);const{addCard:f,removeCard:v,updateCard:C,setActiveCard:A,updateFilters:B}=s.useEditorActions(),{columns:O=[],isLoading:E,error:N}=s.useColumns(),p=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),j=m,{getFieldsForContainer:S,setFieldsForContainer:M}=s.useFieldManagement(j),{activeField:y,handleDragStart:b,handleDragEnd:I}=Aa({activeCardId:k.activeCardId,sourceFields:O,getFieldsForContainer:S,setFieldsForContainer:M}),F=(G,q)=>{q&&B(G,q)},T=G=>{var q;C(G,{config:{...(q=k.cards.find(V=>V.id===G))==null?void 0:q.config,filters:void 0}})},L=O,w=G=>{if(!G)return 0;let q=G.conditions.length;return G.groups.forEach(V=>{q+=w(V)}),q},R=w(((K=j==null?void 0:j.config)==null?void 0:K.filters)||null);return e.jsxs(s.DndContext,{sensors:p,collisionDetection:s.closestCenter,onDragStart:b,onDragEnd:I,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Es,{isVisible:i,onToggleVisibility:()=>c(!i)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:h==="tableBuilder"?e.jsx(Ha,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!l&&e.jsx(ua,{selectedChart:h,onChartChange:g,groupByFields:S("groupBy"),pivotByFields:S("pivotBy"),metricsFields:S("metrics"),sortByFields:S("sortBy"),activeField:y}),e.jsx(Ra,{selectedChart:h,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onFiltersClick:()=>d(!0),filterCount:R,activeCard:j,dataSourceState:m.dataSource||s.EMPTY_DATA_SOURCE,columns:O,columnsLoading:E,columnsError:N,getFieldsForContainer:S,cards:k.cards,activeCardId:k.activeCardId,addCard:f,setActiveCard:A})]})}),!i&&u&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>c(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),j&&e.jsx(Ea,{cardId:j.id,filters:((_=j.config)==null?void 0:_.filters)||null,onFiltersChange:F,onClearFilters:T,availableFields:L,isOpen:o,onOpenChange:d}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Pa,{activeField:y||null})})]})}function Qa({authToken:t,onSave:n,onClose:a}){const r=D.useRef(null),o=s.useEditorStore(N=>N.showAIDialog),d=s.useEditorStore(N=>N.isDevMode),i=s.useAssistantLayoutStore(N=>N.setFullscreen),c=s.useAssistantLayoutStore(N=>N.setPanelOpen),l=s.useAssistantLayoutStore(N=>N.setContainer),u=s.useAssistantPanel("editor"),x=s.useFullscreenAssistant(),h=s.useAssistantContainer("editor"),g=x==="editor",k=D.useCallback(N=>{l("editor",N)},[l]),{setAuthToken:m}=s.useDashboardActions(),{setShowAIDialog:f,setOnSave:v,setOnClose:C}=s.useEditorActions(),{setActiveAssistantType:A}=s.useAIActions();D.useEffect(()=>{n&&v(n),a&&C(a)},[n,v,a,C]),D.useEffect(()=>{t&&t.accessToken&&m(t)},[t,m]),D.useEffect(()=>{var N,p;o?((N=r.current)==null||N.resize(40),c("editor",!0),A("editor")):((p=r.current)==null||p.resize(0),c("editor",!1),x==="editor"&&i(null),A(null))},[o,c,A,i,x]);function B(N){N<1?(f(!1),c("editor",!1),x==="editor"&&i(null),A(null)):(o||(f(!0),A("editor")),u.isOpen||c("editor",!0))}function O(){return e.jsxs(e.Fragment,{children:[e.jsx(Es,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow border-l",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:s.cn("grow transition-opacity",g&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Kn,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:B,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(ps,{isFullscreen:g,onFullscreenChange:N=>i(N?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:k,className:s.cn("absolute inset-0",!g&&"pointer-events-none")})]})]})}function E(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:s.cn("flex grow transition-opacity",g&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Ja,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:B,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(ps,{isFullscreen:g,onFullscreenChange:N=>i(N?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:k,className:s.cn("absolute inset-0",!g&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:d?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:O()}):E()})}function Ya(){s.useDashboardStore(i=>i.selectedCardId);const t=s.useDashboardStore(i=>i.selectedSheetId),{setIsVisualEditing:n}=s.useDashboardStore(i=>i.actions),a=s.useDashboardStore(i=>i.isVisualEditing),r=s.useDashboardStore(i=>i.actions.updateFrame);function o(i){t&&(r(t,i),n(!1))}function d(){n(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!a}),children:e.jsx(Qa,{onSave:o,onClose:d})})}exports.default=Ya;
198
+ `;B(V)}function G(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.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(Pt,{})}),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(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.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(Vt,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function q(){var V,z,H,P,W,Y;return e.jsx("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-4",children:[e.jsxs(s.Button,{title:"Shift + Enter",disabled:y||b,onClick:()=>{R()},className:"h-8 shrink-0",size:"sm",children:[y||b?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(s.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(Ot,{errorSql:L,sql:M==null?void 0:M.sql,error:K,onDebugWithAssistant:_}),e.jsx(_e.EditorClearButton,{}),e.jsxs(s.Toggle,{pressed:a,onPressedChange:ee=>r(ee),className:"h-8",size:"sm",variant:"outline",children:[e.jsx(Rt,{className:"mr-2 size-4 text-foreground/70"}),"Python"]}),!d&&e.jsxs("button",{disabled:d,onClick:()=>{O(!0)},className:"flex h-8 w-full cursor-text items-center justify-start rounded-md bg-muted/50 px-3 text-left text-sm text-muted-foreground",children:[e.jsx(s.Sparkles,{className:"mr-3 size-4 text-foreground/70"}),"Type your question..."]}),e.jsxs("div",{className:"flex flex-1 items-center justify-end gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((z=(V=l.preferences)==null?void 0:V.tablePrefs)==null?void 0:z.enableDevModePagination)??!1,onCheckedChange:ee=>{var J;v({...l.preferences,tablePrefs:{...(J=l.preferences)==null?void 0:J.tablePrefs,enableDevModePagination:ee}})}}),e.jsx(s.Label,{htmlFor:"pagination",className:"cursor-pointer text-sm",children:"Paginate"}),((P=(H=l.preferences)==null?void 0:H.tablePrefs)==null?void 0:P.enableDevModePagination)&&e.jsxs(s.Select,{value:String(((Y=(W=l.preferences)==null?void 0:W.tablePrefs)==null?void 0:Y.pageSize)||50),onValueChange:ee=>{var le,Z,oe;const J=Number(ee),ne={...l,preferences:{...l.preferences,tablePrefs:{...(le=l.preferences)==null?void 0:le.tablePrefs,pageSize:J}},paginationConfig:{page:1,pageSize:J}};E(ne),N(ne),l.sql&&((oe=(Z=l.preferences)==null?void 0:Z.tablePrefs)!=null&&oe.enableDevModePagination)&&j(!0)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"10",children:"10"}),e.jsx(s.SelectItem,{value:"25",children:"25"}),e.jsx(s.SelectItem,{value:"50",children:"50"}),e.jsx(s.SelectItem,{value:"100",children:"100"}),e.jsx(s.SelectItem,{value:"500",children:"500"}),e.jsx(s.SelectItem,{value:"1000",children:"1000"})]})]})]}),o&&o.length>0&&e.jsxs(s.HoverCard,{openDelay:200,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",className:"h-8 gap-2 px-2",children:[e.jsx(s.Filter,{className:"size-4"}),e.jsx(s.Badge,{className:"h-5 min-w-5 bg-purple-100 px-1.5 text-purple-700 hover:bg-purple-100 dark:bg-purple-950 dark:text-purple-300",children:o.length})]})}),e.jsx(s.HoverCardContent,{className:"mr-4 max-h-[400px] w-[500px] overflow-auto p-0",children:e.jsxs("div",{className:"p-3",children:[e.jsx("div",{className:"mb-2 text-sm font-semibold",children:"Active Dashboard Filters"}),e.jsx(s.CodeHighlighter,{code:JSON.stringify(o,null,2),language:"json"})]})})]})]})]})})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsx("div",{className:"relative flex grow overflow-y-scroll",children:G()}),q()]})}const $t=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:s.Grid3x3}];function Kt({className:t}){const n=s.useEditorStore(o=>o.card),{setCardType:a,setCard:r,updateCardInFrame:l}=s.useEditorActions(),d=["table","aggregateTable","pivotTable"].includes(n.type),i=s.hasValidCardConfig(n.config);if(!d||!i)return null;const c=o=>{var x;const u=o;if(u==="aggregateTable"&&((x=n.config)!=null&&x.pivotByColumns)&&n.config.pivotByColumns.length>0){const h={...n,type:u,config:{...n.config,pivotByColumns:[]}};r(h),l(h)}else{a(u);const h={...n,type:u};l(h)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:n.type,onValueChange:c,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:$t.map(o=>{const u=o.icon,x=n.type===o.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:o.value,id:`table-type-${o.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${o.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all",x?"bg-muted text-foreground shadow-sm":"text-muted-foreground hover:bg-muted/50"),children:[e.jsx(u,{className:"h-3.5 w-3.5"}),o.label]})]},o.value)})})})}function Gt({type:t,isLinked:n,className:a}){const r=s.useDashboardStore(p=>p.selectedFrameId),l=s.useManagementStore(p=>p.selectedVisual),d=s.useEditorStore(p=>p.frame);let i;if(t)i=t;else if(n!==void 0)i=n?"linked":"library";else if(!!!(d!=null&&d.visualId||l!=null&&l.id)&&r)i="local";else if(l&&!r)i="library";else if(d!=null&&d.visualId&&r)i="linked";else if(l!=null&&l.id&&r)i="library";else return null;if(i==="local")return null;const c={linked:"border-purple-200/70 bg-gradient-to-r from-purple-50/50 to-purple-100/30 text-purple-900 shadow-sm hover:from-purple-100/60 hover:to-purple-100/50 hover:shadow-md dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100 dark:hover:from-purple-950/60 dark:hover:to-purple-900/50",library:"border-blue-200/70 bg-gradient-to-r from-blue-50/50 to-blue-100/30 text-blue-900 shadow-sm hover:from-blue-100/60 hover:to-blue-100/50 hover:shadow-md dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30 dark:text-blue-100 dark:hover:from-blue-950/60 dark:hover:to-blue-900/50"},o={linked:"Linked to library: Changes made here update the library visual and all linked instances.",library:"Library visual: Share and reuse this visual across multiple dashboards."},u={linked:"border-purple-200 bg-purple-50 text-purple-900 dark:border-purple-800 dark:bg-purple-950 dark:text-purple-100",library:"border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-800 dark:bg-blue-950 dark:text-blue-100"},x={linked:"fill-purple-50 dark:fill-purple-950",library:"fill-blue-50 dark:fill-blue-950"},h={linked:e.jsx(bt,{className:"h-3.5 w-3.5"}),library:e.jsx(jt,{className:"h-3.5 w-3.5"})};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:s.cn("cursor-help select-none transition-all",c[i],a),children:h[i]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:s.cn("max-w-xs",u[i]),children:[e.jsx(s.TooltipArrow,{className:x[i]}),e.jsx("p",{children:o[i]})]})]})})}function Ds({className:t,...n}){var G,q,V;const a=s.useEditorStore(z=>z.card),r=((G=a.customCardPreferences)==null?void 0:G.showCardHeader)??!0,l=((V=(q=a.preferences)==null?void 0:q.displayOptions)==null?void 0:V.showInlineFilterBar)??!0,d=s.useEditorStore(z=>z.frame),i=s.useDashboardStore(z=>z.dashboard.filters),c=s.useDashboardStore(z=>z.selectedSheetId),[o,u]=D.useState(!1),{currentUser:x}=s.useCurrentUserInfo(),{tokenProps:h}=D.useContext(s.SemaphorContext),p=s.useEditorStore(z=>z.actions.setRunSql),{updateFilter:w}=s.useDashboardActions(),m=i==null?void 0:i.find(z=>z.id===d.filterId),{data:g,isLoading:v,isFetching:C,errorMessage:A,errorSql:B,pagination:O}=s.useDashboardCardQuery(a),E=D.useMemo(()=>(g==null?void 0:g.records)||[],[g==null?void 0:g.records]),{setCard:N,updateCardInFrame:f,setIsDevMode:j,setCardSql:S}=s.useEditorActions(),{data:M}=s.useTopoJson(a),y=D.useMemo(()=>{var z;return a.type!=="pivotTable"||!((z=g==null?void 0:g.records)!=null&&z.length)?null:{records:g.records,columnSubtotalMeta:g.columnSubtotalMeta,subtotalColumns:g.subtotalColumns||[],pivotSchema:g.pivotSchema||[],groupByColumns:g.groupByColumns}},[a.type,g==null?void 0:g.records,g==null?void 0:g.columnSubtotalMeta,g==null?void 0:g.subtotalColumns,g==null?void 0:g.pivotSchema,g==null?void 0:g.groupByColumns]),b=s.usePivotTableConfig(a,y),I=z=>{j(!0),S(z||B||a.sql||a.python||""),setTimeout(()=>{p(!0)},100)},F=()=>{u(!0)},T=D.useMemo(()=>{const z=typeof window<"u"?window.location.href:"",H=typeof navigator<"u"?navigator.userAgent:"",P=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:s.FeedbackCategory.QUERY_GENERATION,user:x,tokenContext:h,systemState:{cardConfig:a.config,dataSource:a.dataSource,dashboardFilters:i,errorMessage:A||void 0,errorSql:B||a.sql||a.python,generatedSql:B||a.sql},metadata:{url:z,userAgent:H,timestamp:new Date().toISOString(),viewport:P}}},[x,h,a,i,A,B]),L=(z,H)=>{var W,Y;const P={...a,paginationConfig:{page:z+1,pageSize:H}};N(P),f(P),a.sql&&((Y=(W=a.preferences)==null?void 0:W.tablePrefs)!=null&&Y.enableDevModePagination)&&p(!0)},k=z=>{var W,Y,ee,J;const H=s.sortStateToSortByColumns(z,(W=a.config)==null?void 0:W.metricColumns,(Y=a.config)==null?void 0:Y.groupByColumns),P={...a,config:{...a.config||{},sortByColumns:H}};N(P),f(P),a.sql&&((J=(ee=a.preferences)==null?void 0:ee.tablePrefs)!=null&&J.enableDevModePagination)&&p(!0)},R=D.useMemo(()=>!a.id||!(g!=null&&g.records)?null:s.createChartConfig({card:a,data:g==null?void 0:g.records,cardType:a.type,queryConfig:a.queryConfig,customCfg:a.customCfg,preferences:a.preferences,topoJson:M}),[a.id,g==null?void 0:g.records,a.type,a.customCfg,a.preferences,M]);function K(z){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(s.EditorCustomVisual,{card:z})})}function _(){if(g!=null&&g.records&&(g==null?void 0:g.records.length)===0&&!v&&!C)return A?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(Je,{error:A,errorSql:B||a.sql||a.python,onOpenInEditor:I,onSendFeedback:F,showFeedbackButton:!0,errorTitle:"Unable to Create Visual"})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((v||C)&&(!(g!=null&&g.records)||g.records.length===0))return a.type==="table"?e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableSkeleton,{})}):e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!a.id)return null;if(a.type==="custom")return K(a);if(!["table","pivotTable","aggregateTable","custom"].includes(a.type)&&R)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:v||C?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:R})});if(a.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:a,data:E,paginationMetadata:O,onPaginationChange:L,onSortChange:k,isLoading:v||C})});if(a.type==="pivotTable"&&b)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.PivotTableTanstack,{card:a,data:b.data,options:b.options,onAggregationChange:z=>{const H=s.handleAggregationChange(z,a.config),P={...a,config:H};N(P),f(P)},onAggregationLabelChange:z=>{const H=s.handleAggregationLabelChange(z,a.config),P={...a,config:H};N(P),f(P)}})});if(a.type==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:a,data:(g==null?void 0:g.records)||[],groupByColumns:g==null?void 0:g.groupByColumns,pivotSchema:g==null?void 0:g.pivotSchema,paginationMetadata:O,onPaginationChange:L,onAggregationChange:z=>{const H=s.handleAggregationChange(z,a.config),P={...a,config:H};N(P),f(P)},isLoading:v||C})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[(v||C)&&(g==null?void 0:g.records)&&g.records.length>0&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),r&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:a.title,onSave:z=>N({...a,title:z}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(Gt,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(Kt,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:a.description||"",onSave:z=>N({...a,description:z}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),m&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:m.title||m.column,onSave:z=>w({...m,title:z}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:m})]})]}),l&&a.inlineFilters&&a.inlineFilters.length>0&&e.jsx("div",{className:"px-6 pb-3",children:e.jsx(s.InlineFilterBar,{card:a,sheetId:c||""})}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:_()}),e.jsx(s.FeedbackDialog,{open:o,onOpenChange:u,feedbackData:T,showDebugInfo:!0})]})}const Ke=({language:t,value:n,onChange:a,readonly:r})=>e.jsx(s.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:t,value:n,onChange:a}),qt=()=>e.jsxs(s.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.DialogTitle,{children:"Customize Card"})}),e.jsxs(s.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."})]})]}),Ut=({customCode:t,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:l})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Ke,{language:"json",value:a,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Ke,{readonly:!0,language:"json",value:n,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Ke,{language:"javascript",value:t,onChange:l})})]}),_t=({error:t,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:l})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!n,onClick:a,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:l,variant:"outline",children:"Close"})]});function Ht(){const[t,n]=D.useState(!1),[a,r]=D.useState(""),[l,d]=D.useState(""),[i,c]=D.useState(""),[o,u]=D.useState(""),x=s.useEditorStore(E=>E.card),h=s.useEditorStore(E=>E.card.customCfg),p=h?JSON.stringify(h,null,2):"",{data:w}=s.useDashboardCardQuery(x),{data:m}=s.useTopoJson(x),{setCardCustomCfg:g,setCustomVisualCode:v}=s.useEditorActions(),C=E=>{var N,f;return JSON.stringify({...E,data:{...E.data,datasets:(f=(N=E.data)==null?void 0:N.datasets)==null?void 0:f.map(j=>({...j,data:[]}))}},null,2)},A=()=>{var N,f;if(!((N=w==null?void 0:w.records)!=null&&N.length))return;const E=s.createChartConfig({card:x,data:w.records,cardType:x.type,queryConfig:x.queryConfig,preferences:x.preferences,topoJson:m});if(E){r(C(E)),c(((f=x.preferences)==null?void 0:f.customVisualCode)||"");const j=s.merge(E,h);d(C(j))}},B=()=>{try{if(i&&v(i),l){const E=JSON.parse(l),N=s.getObjectDiff(JSON.parse(a),E);g(N),u("")}}catch{u("Invalid JSON configuration")}},O=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:n,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:A,className:O?"":"text-green-600 hover:text-green-700",children:e.jsx(s.Settings,{className:"h-4 w-4"})})}),e.jsxs(s.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(qt,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Ds,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Ut,{customCode:i,cardCustomCfgString:p,mergedConfig:l,onConfigChange:E=>d(E??""),onCodeChange:E=>c(E??"")})]}),e.jsx(_t,{error:o,hasCardCustomConfig:!!h,onReset:()=>{d(a),g(null)},onApply:B,onClose:()=>n(!1)})]})]})}function Jt({onChartTypeChange:t}){const{setCardCustomCfg:n,setCardPreferences:a,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:d,isLoading:i,isError:c}=s.useCustomVisualsQuery(),o=D.useCallback((u,x)=>{n(null),a({}),r(u),x&&l({type:"component",visualType:"single",url:x.url,componentName:x.name,icon:x.icon}),t==null||t()},[n,a,r,l,t]);return i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-muted-foreground",children:"Loading custom visuals..."})]}):c?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-destructive",children:"Failed to load custom visuals"})]}):!d||d.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"mb-2",children:e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Custom Charts"})}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:d.map((u,x)=>e.jsx(Qt,{text:u.name,onClick:()=>o("custom",u),icon:u.icon},`${u.url}-${u.name}-${x}`))})]})}const Qt=({text:t,icon:n,onClick:a})=>{const r=s.useDynamicIcon();return e.jsxs("button",{onClick:a,className:"flex flex-col items-center gap-2 rounded-lg border border-border bg-background p-3 transition-all hover:border-primary/50 hover:bg-muted/50 hover:shadow-sm",children:[r?e.jsx(r,{className:"h-6 w-6"}):e.jsx(De,{className:"h-6 w-6 text-muted-foreground"}),e.jsx("span",{title:t,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:t})]})};function Yt({onChartTypeChange:t,iconClassName:n,searchQuery:a=""}){const{setCardType:r,setCardPreferences:l,setIsDevMode:d}=s.useEditorStore(p=>p.actions),{setCardCustomCfg:i,setCustomCardPreferences:c,setQueryConfig:o}=s.useEditorActions();function u(p,w){i(null),l({}),r(p),["custom","text","map"].includes(p)&&(d(!0),o(void 0)),t==null||t()}const h=[{type:"table",name:"Table",icon:s.Table2},{type:"bar",name:"Bar Chart",icon:s.ChartColumnIncreasing},{type:"line",name:"Line Chart",icon:s.ChartLine},{type:"stackedBar",name:"Stacked Bar",icon:s.ChartColumnStacked},{type:"stackedLine",name:"Stacked Line",icon:s.MdStackedLineChart},{type:"scatter",name:"Scatter",icon:s.ChartScatter},{type:"bubble",name:"Bubble",icon:s.TbChartBubble},{type:"pie",name:"Pie Chart",icon:s.ChartPie},{type:"doughnut",name:"Doughnut",icon:s.Donut},{type:"funnel",name:"Funnel",icon:s.TbChartFunnel},{type:"radar",name:"Radar",icon:s.Radar},{type:"polarArea",name:"Polar Area",icon:s.PiChartPolar},{type:"tornado",name:"Tornado",icon:s.Tornado},{type:"range",name:"Range",icon:s.ChartNoAxesGantt},{type:"bullet",name:"Bullet Chart",icon:s.BulletChartIcon},{type:"treemap",name:"Treemap",icon:s.TbChartTreemap},{type:"kpi",name:"KPI",icon:s.TiSortNumerically},{type:"text",name:"Text",icon:s.BookType},{type:"map",name:"Map",icon:s.Map},{type:"custom",name:"Custom",icon:De}].filter(p=>p.name.toLowerCase().includes(a.toLowerCase()));return e.jsx("div",{className:"grid grid-cols-3 gap-2",children:h.map(p=>{const w=p.icon;return e.jsxs("button",{onClick:()=>u(p.type),className:"flex flex-col items-center gap-2 rounded-lg border border-border bg-background p-3 transition-all hover:border-primary/50 hover:bg-muted/50 hover:shadow-sm",children:[e.jsx(w,{className:s.cn("h-6 w-6",n),strokeWidth:p.icon===s.MdStackedLineChart?0:void 0}),e.jsx("span",{className:"text-xs font-medium text-foreground",children:p.name})]},p.type)})})}function Wt({chartType:t,className:n,customIcon:a,componentName:r}){const l=s.useDynamicIcon();switch(t){case"bar":return e.jsx(s.ChartColumnIncreasing,{className:n});case"line":return e.jsx(s.ChartLine,{className:n});case"pie":return e.jsx(s.ChartPie,{className:n});case"radar":return e.jsx(s.Radar,{className:n});case"scatter":return e.jsx(s.ChartScatter,{className:n});case"bubble":return e.jsx(s.TbChartBubble,{className:n});case"doughnut":return e.jsx(s.Donut,{className:n});case"stackedBar":return e.jsx(s.ChartColumnStacked,{className:n});case"stackedLine":return e.jsx(s.MdStackedLineChart,{className:n});case"polarArea":return e.jsx(s.PiChartPolar,{className:n});case"treemap":return e.jsx(s.TbChartTreemap,{className:n});case"bullet":return e.jsx(s.BulletChartIcon,{className:n});case"funnel":return e.jsx(s.TbChartFunnel,{className:n});case"tornado":case"pyramid":return e.jsx(s.Tornado,{className:n});case"range":return e.jsx(s.ChartNoAxesGantt,{className:n});case"kpi":return e.jsx(s.TiSortNumerically,{className:n});case"text":return e.jsx(s.Type,{className:n});case"map":return e.jsx(s.Map,{className:n});case"custom":return a&&l?e.jsx(l,{className:n}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(De,{className:n});default:return e.jsx(s.Table2,{className:n})}}function Ms({variant:t="ghost"}){var c,o;const[n,a]=D.useState(!1),[r,l]=D.useState(""),d=s.useEditorStore(u=>u.card),i=d.type;return e.jsxs(s.Popover,{open:n,onOpenChange:u=>{a(u),u||l("")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(Wt,{className:"size-4",chartType:i,customIcon:(c=d.customCardPreferences)==null?void 0:c.icon,componentName:(o=d.customCardPreferences)==null?void 0:o.componentName})})}),e.jsxs(s.PopoverContent,{onOpenAutoFocus:u=>u.preventDefault(),className:"z-[70] w-[360px] p-3",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-sm border border-border bg-background px-3 py-2",children:[e.jsx(s.Search,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search charts...",value:r,onChange:u=>l(u.target.value),className:"h-auto border-0 p-0 text-sm focus-visible:ring-0 focus-visible:ring-offset-0"})]}),e.jsxs("div",{className:"max-h-[400px] overflow-y-auto",children:[e.jsx(Yt,{onChartTypeChange:()=>a(!1),searchQuery:r}),e.jsx(Jt,{onChartTypeChange:()=>a(!1)})]})]})]})}function Xt({error:t,className:n="",textClassName:a="",copyButtonClassName:r=""}){const[l,d]=D.useState(!1),i=D.useRef(null),c=D.useRef(!1);function o(){t&&!c.current&&navigator.clipboard.writeText(t)}function u(p){(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),o())}function x(){const p=window.getSelection();if(p&&p.toString().trim()!==""){const w=p.toString();navigator.clipboard.writeText(w),d(!0),c.current=!0,setTimeout(()=>{d(!1),c.current=!1},1e3)}else c.current=!1}function h(){d(!1),c.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 ${n}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,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:i,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${a}`,onClick:o,onKeyDown:u,onMouseUp:x,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&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 Zt(){const t=s.useEditorStore(o=>{var u,x;return(x=(u=o.card.preferences)==null?void 0:u.chartOptions)==null?void 0:x.indexAxis}),n=s.useEditorStore(o=>o.card.type),{setChartOrientation:a,setCardPreferences:r}=s.useEditorStore(o=>o.actions),l=o=>{if(a(o),n!=="bullet")return;const u=o==="y"?"horizontal":"vertical",x=s.useEditorStore.getState().card.preferences,h={...x||{},bulletConfig:{...(x==null?void 0:x.bulletConfig)||{},orientation:u}};r(h)};function d(){const o=t??"x",u=()=>{l(o==="x"?"y":"x")};return e.jsx(s.IconButton,{onClick:u,tooltip:"Chart Orientation",children:o==="x"?e.jsx($e,{className:"size-4"}):e.jsx(ze,{className:"size-4"})})}function i(){const o=()=>{l(t==="y"||t===void 0?"x":"y")};return e.jsx(s.IconButton,{onClick:o,tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx($e,{className:"size-4"}):e.jsx(ze,{className:"size-4"})})}function c(){const o=t??"y",u=()=>{l(o==="y"?"x":"y")};return e.jsx(s.IconButton,{onClick:u,tooltip:"Chart Orientation",children:o==="y"?e.jsx(ze,{className:"size-4"}):e.jsx($e,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?i():n==="bullet"?c():d()})}function en({className:t}){var w,m,g,v,C,A,B,O,E,N;const n=s.useEditorStore(f=>f.card),{setCardPreferences:a,updateCardInFrame:r,setCard:l}=s.useEditorActions(),[d,i]=D.useState(!1),c=((m=(w=n.preferences)==null?void 0:w.displayOptions)==null?void 0:m.showFilterInfo)??!0,o=((v=(g=n.preferences)==null?void 0:g.displayOptions)==null?void 0:v.showCardToolbar)??!0,u=((A=(C=n.preferences)==null?void 0:C.displayOptions)==null?void 0:A.showChrome)??!0,x=((O=(B=n.preferences)==null?void 0:B.displayOptions)==null?void 0:O.allowScroll)??!0,h=((N=(E=n.preferences)==null?void 0:E.displayOptions)==null?void 0:N.showInlineFilterBar)??!0,p=(f,j)=>{var y;const S={...n.preferences,displayOptions:{...(y=n.preferences)==null?void 0:y.displayOptions,[f]:j}};a(S);const M={...n,preferences:S};l(M),r(M)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:d,onOpenChange:i,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(ks,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"Display Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Changes apply to dashboard view only"})}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:f=>{p("showFilterInfo",f)},onSelect:f=>f.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Filter Info"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Badge"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:f=>{p("showCardToolbar",f)},onSelect:f=>f.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Toolbar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Hover actions"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:f=>{p("showChrome",f)},onSelect:f=>f.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Chrome"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Frame & padding"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:f=>{p("allowScroll",f)},onSelect:f=>f.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Allow Scroll"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card content scroll"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:h,onCheckedChange:f=>{p("showInlineFilterBar",f)},onSelect:f=>f.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Inline Filter Bar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card filters"})]})]})]})})}function sn(){const[t,n]=D.useState(!1),a=s.useEditorStore(h=>h.card),r=s.useEditorStore(h=>h.selectedConnectionId),{setCard:l}=s.useEditorActions(),d=s.useDashboardStore(h=>h.actions.removeCardInlineFilterValue),i=(a==null?void 0:a.inlineFilters)||[];function c(h){const p=h.qualifiedFieldName||h.name;if(i.find(A=>A.column===p))return;const m=h.qualifiedFieldName?h.qualifiedFieldName.split(".").slice(0,-1).join("."):h.qualifiedEntityName||h.entityName,g=s.fmt(h.name),v=h.qualifiedFieldName||g,C={id:s.v4(),column:p,title:h.label||h.name,dataType:h.dataType,table:h.entityName||"",database:"",connectionId:r||"",operation:"in",sql:s.getDefaultFilterSql(h.dataType,m,v),width:250};l({...a,inlineFilters:[...i,C]})}function o(h){const p=i.filter(w=>w.id!==h);l({...a,inlineFilters:p}),d(a.id,h)}function u(h,p){const w=i.map(m=>m.id===h?{...m,...p}:m);l({...a,inlineFilters:w})}return["bar","line","pie","doughnut","table","stackedBar","stackedLine","horizontalBar","radar","polarArea","scatter","bubble","funnel","aggregateTable","custom"].includes(a==null?void 0:a.type)?e.jsx("div",{className:"flex items-center gap-1",children:e.jsxs(s.Popover,{open:t,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.IconButton,{tooltip:"Add Inline Filter",className:s.cn("relative",{"text-primary":i.length>0}),children:[e.jsx(yt,{className:"h-4 w-4"}),i.length>0&&e.jsx("span",{className:"absolute -right-1 -top-1 flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] font-medium text-primary-foreground",children:i.length})]})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80 p-0",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"border-b px-4 py-3",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Inline Filters"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"On-card filters for fast, focused exploration."})]}),e.jsx("div",{className:"flex max-h-[300px] flex-col overflow-hidden",children:e.jsx(s.DndContext,{collisionDetection:s.closestCenter,children:e.jsx(s.SortableContext,{items:[],strategy:s.verticalListSortingStrategy,children:e.jsx(s.FieldsList,{context:"inline-filter",onFieldSelect:c,inlineFilters:i})})})}),i.length>0&&e.jsxs("div",{className:"border-t px-4 py-3",children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Active Filters"}),e.jsx("div",{className:"space-y-1",children:i.map(h=>e.jsx(tn,{filter:h,onUpdate:p=>u(h.id,p),onRemove:()=>o(h.id)},h.id))})]})]})})]})}):null}function tn({filter:t,onUpdate:n,onRemove:a}){return e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-muted px-2 py-1.5 text-sm",children:[e.jsx("span",{className:"truncate",title:t.column,children:t.title}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(s.CustomFilterPopover,{filter:t,variant:"inline",onAccept:r=>n(r),trigger:e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0",title:"Configure filter",children:e.jsx(s.Settings2,{className:"h-3 w-3"})})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0 hover:bg-destructive/10 hover:text-destructive",onClick:a,children:e.jsx(s.X,{className:"h-3 w-3"})})]})]})}function Ls(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var i,c;return(c=(i=d.card)==null?void 0:i.preferences)==null?void 0:c.chartOptions}),a=s.getChartGridStyle(n),{setChartGrid:r}=s.useEditorActions();function l(){const d=["xy","none","x","y"],c=(d.indexOf(a)+1)%d.length;r(d[c])}return e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(Zt,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsx(e.Fragment,{}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:l,children:[(a==="xy"||!a)&&e.jsx(s.Grid3x3,{className:"size-4"}),a==="x"&&e.jsx(Ss,{className:"size-4"}),a==="y"&&e.jsx(He,{className:"size-4"}),a==="none"&&e.jsx(At,{className:"size-4"})]}),e.jsx(sn,{}),e.jsx(en,{})]})}function nn(){const t=s.useEditorStore(m=>m.frame),n=s.useEditorStore(m=>m.card),{setFrame:a,setActiveTabCardId:r,setCard:l,updateCardInFrame:d}=s.useEditorActions(),i=(m,g)=>{m.dataTransfer.setData("tabIndex",g.toString())},c=m=>{m.preventDefault()},o=(m,g)=>{const v=m.dataTransfer.getData("tabIndex");if(v===g.toString())return;const C=Array.from(t.cards),[A]=C.splice(parseInt(v),1);C.splice(g,0,A),a({...t,cards:C})};function u(m){const g=t.cards.filter(A=>A.id!==m),v=g[0],C={...t,cards:g,activeCardId:v.id};a(C),r(v.id),l(v)}function x(m,g){const v={...t,cards:[...t.cards,g],activeCardId:m.id};a(v),r(g.id)}function h(){const m={...n,id:s.v4(),title:`${n.title} Copy`,tabTitle:`${n.tabTitle||n.title} Copy`};x(n,m)}function p(m){const g={dataSource:m.dataSource,connectionId:m.connectionId,lastSelectedDatabase:m.lastSelectedDatabase,lastSelectedSchema:m.lastSelectedSchema,lastSelectedTable:m.lastSelectedTable,lastSelectedDatamodelId:m.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};x(m,g)}function w(m,g){return m.cards.length===1&&(g.displayTab===!0||g.displayTab===void 0)||m.activeCardId!==g.id&&(g.displayTab===!0||g.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const v=g.displayTab===void 0?!1:!g.displayTab;l({...g,displayTab:v}),d({...g,displayTab:v})},children:g.displayTab===!0||g.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(mt,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((m,g)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:v=>i(v,g),onDragOver:c,onDrop:v=>o(v,g),className:"",value:m.id,children:[w(t,m),e.jsx(s.Editable,{enabled:t.activeCardId===m.id,text:m.tabTitle||m.title,onSave:v=>{l({...n,tabTitle:v}),d({...n,tabTitle:v})},children:m.tabTitle||m.title},m.id),t.activeCardId===m.id&&e.jsx(s.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:v=>{v.stopPropagation(),h()}}),t.activeCardId===m.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(m.id)})]},m.id)),e.jsx(s.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>p(n),children:e.jsx(s.Plus,{className:"h-4 w-4"})})]})})}function Ue(){const t=s.useEditorStore(v=>v.frame),n=s.useEditorStore(v=>v.card),a=s.useEditorStore(v=>v.isSqlRunning),r=s.useEditorStore(v=>v.isDevMode),{setFrame:l,setActiveTabCardId:d,setCard:i,setIsDevMode:c,setRunSql:o}=s.useEditorActions(),{data:u,isLoading:x,isFetching:h,isError:p}=s.useDashboardCardQuery(n);function w(v){const C=t.cards.find(A=>A.id===v);if(C!=null&&C.sql){r||c(!0),d(v);return}if(C!=null&&C.queryConfig){r&&c(!1),m(v),d(v);return}r||m(v),d(v)}function m(v){const C={...t,cards:t.cards.map(B=>B.id===n.id?n:B),activeCardId:v};l(C);const A=C.cards.find(B=>B.id===v);A.sql&&o(!0),i(A)}function g(){return n.type==="kpi"?x||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:n,data:u==null?void 0:u.records,isPending:x||h,isError:p})})}):n.type==="text"?x||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):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(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:a,card:n,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Ds,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:w,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(v=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:v.id,children:g()},v.id)),e.jsx(nn,{})]})}function os({children:t}){const n=s.useEditorStore(b=>b.frame),a=s.useEditorStore(b=>b.card),r=s.useEditorStore(b=>b.isDevMode),l=s.useEditorStore(b=>b.isShowingVisual),d=s.useDashboardStore(b=>b.isVisualEditing),i=s.useEditorStore(b=>b.pythonStdOut),c=s.useEditorStore(b=>b.actions.setRunSql),{setFrame:o,setCard:u,setActiveTabCardId:x,runAssistant:h,setIsDevMode:p,setCardPreferences:w}=s.useEditorActions(),{data:m,isLoading:g,isFetching:v,errorMessage:C,refetch:A,pagination:B}=s.useDashboardCardQuery(a),O=D.useMemo(()=>(m==null?void 0:m.records)||[],[m==null?void 0:m.records]),[E,N]=D.useState(!1);D.useEffect(()=>{v||N(!1)},[v]);function f(b,I){var L,k;const F={...a,paginationConfig:{page:b+1,pageSize:I}};u(F);const T={...n,cards:n.cards.map(R=>R.id===a.id?F:R)};o(T),a.sql&&((k=(L=a.preferences)==null?void 0:L.tablePrefs)!=null&&k.enableDevModePagination)&&c(!0)}function j(b){var L,k,R,K;const I=s.sortStateToSortByColumns(b,(L=a.config)==null?void 0:L.metricColumns,(k=a.config)==null?void 0:k.groupByColumns),F={...a,config:{...a.config||{},sortByColumns:I}};u(F);const T={...n,cards:n.cards.map(_=>_.id===a.id?F:_)};o(T),a.sql&&((K=(R=a.preferences)==null?void 0:R.tablePrefs)!=null&&K.enableDevModePagination)&&c(!0)}function S(){const b=JSON.stringify(m==null?void 0:m.records,null,2),I=new Blob([b],{type:"application/json"}),F=URL.createObjectURL(I),T=document.createElement("a");T.href=F,T.download=`${a.title}.json`,T.click()}function M(){const I=[Object.keys(m==null?void 0:m.records.reduce((k,R)=>({...k,...R}),{})).join(","),...((m==null?void 0:m.records)||[]).map(k=>Object.values(k).join(","))].join(`
199
+ `),F=new Blob([I],{type:"text/csv"}),T=URL.createObjectURL(F),L=document.createElement("a");L.href=T,L.download=`${a.title}.csv`,L.click()}function y(){const b=`Can you get the documentation for ${a.type} chart?`;h(b)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[l&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(Ms,{}),d&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:y,children:e.jsx(ct,{className:"size-4"})}),!["table","custom"].includes(a.type)&&d&&e.jsx(Ht,{})]}),!l&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:M,children:e.jsx(s.PiFileCsv,{className:"size-4"})}),e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:S,children:e.jsx(xt,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.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:[t,e.jsx(s.IconButton,{tooltip:"Refresh",disabled:g||v,onClick:()=>{N(!0),A()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":E})})}),e.jsx(Ls,{})]}),r&&e.jsx(rn,{})]}),l?e.jsx(Ue,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[i&&e.jsxs(e.Fragment,{children:[e.jsx(s.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(an,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":i}),children:[(m==null?void 0:m.records)&&(m==null?void 0:m.records.length)>0&&e.jsx(s.TableVisual,{card:a,data:O,paginationMetadata:B,onPaginationChange:f,onSortChange:j,isLoading:g||v}),C&&e.jsx(Xt,{error:C})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function an(){const t=s.useEditorStore(a=>a.pythonStdOut);if(!t)return null;const n=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:n}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function rn(){const t=s.useEditorStore(a=>a.isShowingVisual),n=s.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs(s.Toggle,{pressed:!t,onPressedChange:()=>n(!t),variant:"outline",size:"sm",className:"h-8 gap-2",children:[e.jsx(s.Table2,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:"Results"})]})}function ce({value:t,onCommit:n,type:a="text",placeholder:r,className:l}){const[d,i]=D.useState(t),c=D.useRef(!1);D.useEffect(()=>{i(t)},[t]);const o=()=>{if(c.current){c.current=!1;return}d!==t&&n(d)},u=x=>{if(x.key==="Enter"){x.currentTarget.blur();return}x.key==="Escape"&&(c.current=!0,i(t),x.currentTarget.blur())};return e.jsx(s.Input$1,{type:a,placeholder:r,value:d,onChange:x=>i(x.target.value),onBlur:o,onKeyDown:u,className:l})}function he({defaultValue:t,label:n,options:a,value:r,onValueChange:l,className:d,icon:i,showPlaceholderLabel:c=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",d),children:e.jsxs("div",{className:"flex items-center gap-2",children:[i&&e.jsx("span",{children:i}),c&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(o=>e.jsx(s.SelectItem,{value:o.value,children:o.label},o.value))]})})]})}const ln={table:({children:t})=>e.jsx("table",{className:"my-3 w-full border-collapse overflow-hidden rounded-md border border-border text-sm",children:t}),thead:({children:t})=>e.jsx("thead",{className:"bg-muted",children:t}),th:({children:t})=>e.jsx("th",{className:"border border-border px-3 py-2 text-left font-medium",children:t}),td:({children:t})=>e.jsx("td",{className:"border border-border px-3 py-2",children:t}),code:({children:t,className:n})=>(n==null?void 0:n.includes("language-"))?e.jsx("pre",{className:"my-3 overflow-x-auto rounded-md bg-muted p-3 text-xs",children:e.jsx("code",{children:t})}):e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:t}),pre:({children:t})=>e.jsx(e.Fragment,{children:t})};function Fs(){var g,v;const t=s.useEditorStore(C=>C.card.customCardPreferences),{data:n}=s.usePluginQuery(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(C=>C.card),l=s.useEditorStore(C=>C.frame),d=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:i}=s.useEditorActions(),{components:c,manifest:o}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(g=o==null?void 0:o.visuals)==null?void 0:g.find(C=>C.name===(t==null?void 0:t.componentName));function x(C,A){if(!t)return;const O={...(t==null?void 0:t.dataInputCardIds)||{},[C]:{cardId:A,hookRef:null}};i({...t,dataInputCardIds:O})}function h(C){var B,O;const A=(B=l==null?void 0:l.cards)==null?void 0:B.filter(E=>{var N;return((N=E==null?void 0:E.customCardPreferences)==null?void 0:N.visualType)!=="multiple"}).map(E=>({value:E.id,label:E.tabTitle||E.title}));return e.jsx("div",{className:"space-y-2",children:(O=C==null?void 0:C.dataInputs)==null?void 0:O.map((E,N)=>{var f,j;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:E}),e.jsx(he,{className:"col-span-6 h-8 w-full justify-between",label:"",options:A||[],value:((j=(f=t==null?void 0:t.dataInputCardIds)==null?void 0:f[N])==null?void 0:j.cardId)||"",onValueChange:S=>x(N,S)})]},N+Math.random())})})}function p(C,A,B=[],O=""){var E,N;return t?C==="input"?e.jsx(ce,{className:`h-8 w-full ${s.removeRing}`,value:String(((E=t==null?void 0:t.settings)==null?void 0:E[A])??O??""),onCommit:f=>{i({...t,settings:{...t==null?void 0:t.settings,[A]:f}})}},A):C==="select"?e.jsx(he,{className:"h-8 w-full",label:"",options:B,value:((N=t==null?void 0:t.settings)==null?void 0:N[A])||O,onValueChange:f=>{i({...t,settings:{...t==null?void 0:t.settings,[A]:f}})}}):null:null}function w(C){const A=Object.entries((C==null?void 0:C.settings)||{});return e.jsx("div",{className:"space-y-3",children:A.map(([B,O])=>{var E;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:O.title}),((E=O.docs)==null?void 0:E.description)&&e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:O.docs.description})})]})})]}),p(O.ui,B,O.options,O.defaultValue)]},B)})})}function m(C){t&&i({...t,visualType:C,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"",children:[e.jsxs(s.AccordionItem,{value:"plugin-settings",children:[e.jsx(s.AccordionTrigger,{children:"Plugin"}),e.jsx(s.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(he,{icon:e.jsx(Ns,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(t==null?void 0:t.url)||"",onValueChange:C=>i({...t||{url:"",componentName:""},url:C})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:d,onValueChange:m,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:c&&e.jsx(he,{icon:e.jsx(ut,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(c==null?void 0:c.filter(C=>C.type===d).map(C=>({value:C.name,label:C.name})))||[],value:t.componentName,onValueChange:C=>{console.log("changing value",C),i({...t,componentName:C})}})})]})})]}),((v=r==null?void 0:r.customCardPreferences)==null?void 0:v.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:(u==null?void 0:u.name)||"Settings"}),(u==null?void 0:u.docs)&&e.jsxs(s.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,onClick:C=>C.stopPropagation(),children:e.jsx(s.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground transition-colors hover:text-foreground"})}),e.jsx(s.HoverCardContent,{side:"right",align:"start",className:"max-h-[40vh] w-[500px] overflow-y-auto text-left",children:e.jsxs("div",{className:"space-y-4 text-left",children:[u.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:u.docs.description}),u.docs.dataSchema&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Data Schema"}),e.jsx("div",{className:"prose prose-sm dark:prose-invert prose-pre:bg-muted prose-pre:text-xs max-w-none",children:e.jsx(s.Markdown,{remarkPlugins:[s.remarkGfm],components:ln,children:u.docs.dataSchema})})]}),u.docs.useCases&&u.docs.useCases.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Use Cases"}),e.jsx("ul",{className:"space-y-1 text-sm",children:u.docs.useCases.map((C,A)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:C})]},A))})]})]})})]})]})}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:w(u)})})]})]})]})}function Se(){const[t,n]=D.useState([]),a=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(u=>u.actions),d=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var x;return(x=u.card.preferences)==null?void 0:x.filterOnClickColumnIndex}),D.useEffect(()=>{d&&n(new Array(d.length).fill(!1))},[d]);function i(u,x){var h,p;x?a!=null&&a.onClickFilter&&((h=a==null?void 0:a.onClickFilter)==null?void 0:h.length)>0?l({...a,onClickFilter:[...a.onClickFilter,{columnIndex:u,expression:""}]}):l({...a,onClickFilter:[{columnIndex:u,expression:""}]}):(l({...a,onClickFilter:(p=a==null?void 0:a.onClickFilter)==null?void 0:p.filter(w=>w.columnIndex!==u)}),n(w=>{const m=[...w];return m[u]=!1,m}))}function c(u,x){var p;const h=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.map(w=>w.columnIndex===u?{...w,expression:x.target.value}:w);l({...a,onClickFilter:h})}function o(u){var x,h,p,w;if(t!=null&&t[u]||(h=(x=a==null?void 0:a.onClickFilter)==null?void 0:x.find(m=>m.columnIndex===u))!=null&&h.expression)return e.jsx(s.Input$1,{value:(w=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(m=>m.columnIndex===u))==null?void 0:w.expression,onChange:m=>c(u,m),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.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:d==null?void 0:d.map((u,x)=>{var h,p;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(s.Checkbox,{checked:!!((h=a==null?void 0:a.onClickFilter)!=null&&h.find(w=>w.columnIndex===x)),onCheckedChange:w=>i(x,w)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(w=>w.columnIndex===x))&&e.jsx(s.Pencil,{onClick:()=>{n(w=>{const m=[...w];return m[x]=!w[x],m})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),o(x)]})},u)})})}function on({idx:t}){var c;const n=s.useEditorStore(o=>{var u;return(u=o.card)==null?void 0:u.preferences}),a=s.useEditorStore(o=>{var u;return(u=o.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(o=>o.actions.setCardPreferences),l=(c=n==null?void 0:n.chartOptions)==null?void 0:c.indexAxis,d=a==null?void 0:a.find(o=>o.idx===t);function i(o,u){(o==="end"||o==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const x={display:o!=="none",align:o,anchor:o,clamp:!0};if(!d)r({...n,datasetOptions:[...a||[],{idx:u,datalabels:x}]});else{const h={...d};h.datalabels=x;const p=a==null?void 0:a.map(w=>w.idx===u?h:w);r({...n,datasetOptions:p})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(s.Tag,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>i("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>i("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(vt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>i("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ct,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>i("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Nt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function cn(){const t=s.useEditorStore(d=>d.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(d=>!s.METADATA_KEYS.includes(d));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const d=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:i}=s.getKeys(d);l=i.slice(1)}return{transformedMetricKeys:l,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}function Qe({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",n),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Bs(){const t=s.useEditorStore(o=>o.card),n=s.useEditorStore(o=>{var u,x,h;return(h=(x=(u=o==null?void 0:o.card)==null?void 0:u.preferences)==null?void 0:x.chartOptions)==null?void 0:h.indexAxis}),{data:a}=s.useDashboardCardQuery(t),r=n==="y"?"Metric":"Dimension",l=n==="y"?"Dimension":"Metric",{dimensionKeys:d,transformedMetricKeys:i,keys:c}=cn();return c.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:d.map(o=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:o,children:Os(o)},o))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:l}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:i.map((o,u)=>e.jsx(Rs,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:o,idx:u},o))})]})]})}function Os(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function Rs({col:t,idx:n,className:a,iconClassName:r,children:l}){const d=s.useEditorStore(x=>{var h;return(h=x.card)==null?void 0:h.preferences}),i=s.useEditorStore(x=>{var h,p;return(p=(h=x.card)==null?void 0:h.preferences)==null?void 0:p.datasetOptions}),c=i==null?void 0:i.find(x=>x.idx===n),{setCardPreferences:o}=s.useEditorStore(x=>x.actions);function u(x){if(!c)o({...d,datasetOptions:[...i||[],{idx:n,type:x==="area"?"line":x,fill:x==="area"?"origin":""}]});else{const h={...c};h.type=x==="area"?"line":x,h.fill=x==="area"?"origin":"";const p=i==null?void 0:i.map(w=>w.idx===n?h:w);o({...d,datasetOptions:p})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[l||e.jsx(Qe,{className:"max-w-[100px]",title:t,children:Os(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>u("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>u("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>u("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(on,{idx:n})]})]})}function Me(){const t=s.useDashboardStore(c=>c.dashboard.filters),n=s.useEditorStore(c=>c.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=s.useAssignFilter();function d(c){const o=l(c,"frame");a({...n,filterId:o})}const i=t==null?void 0:t.find(c=>c.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(dn,{onSelect:d,columns:r}),i&&e.jsx(s.FilterHeader,{filter:i})]})}function dn({columns:t,onSelect:n}){var i;const[a,r]=qe.useState(!1),[l,d]=qe.useState("");return e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[l?(i=t.find(c=>c.column_name===l))==null?void 0:i.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(c=>e.jsxs(s.CommandItem,{value:c.column_name,onSelect:o=>{const u=o===l?"":o;d(u),r(!1),u&&n(c)},children:[c.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===c.column_name?"opacity-100":"opacity-0")})]},c.column_name))})]})]})})]})}function un({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.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:n=>n.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(Bs,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(Me,{})]})]})]})})}function mn({cardType:t}){function n(a){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:a==="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"}),a==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:d=>d.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(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:n(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(Me,{})]})]})]})})}function Ps(){const t=s.useEditorStore(c=>c.card.type),n=s.useEditorStore(c=>c.isDevMode),a=s.useEditorStore(c=>c.card.preferences),{setCardPreferences:r}=s.useEditorStore(c=>c.actions);function l(c){var x;const o={datalabels:{display:c!=="none",align:c,anchor:c,clamp:!0}},u={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(x=a==null?void 0:a.chartOptions)==null?void 0:x.plugins,...o}}};r(u)}function d(){var c,o,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(o=(c=a==null?void 0:a.chartOptions)==null?void 0:c.plugins)==null?void 0:o.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function i(){var c,o,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(o=(c=a==null?void 0:a.chartOptions)==null?void 0:c.plugins)==null?void 0:o.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:n?d():i()})}const xn={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},hn={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function pn(){const t=s.useEditorStore(n=>n.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:fn(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ps,{}),e.jsx(Se,{}),e.jsx(Me,{})]})]})}function fn(t){if(["line","bar"].includes(t))return e.jsxs(e.Fragment,{children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(s.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(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(s.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(xn,null,2)})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(s.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(hn,null,2)})]})]})]});if(t==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.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(t==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.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(t))return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:t==="polarArea"?"Polar":t.charAt(0).toUpperCase()+t.slice(1)})," ","chart query"]})}),e.jsxs(s.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 gn({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(i,c,o){const u=[...t];u[i]={...u[i],[c]:o},n(u)}function l(i){const c=[...t];c.splice(i,1),n(c)}function d(){n([...t,a])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:"Color Range"}),e.jsx(s.Button,{onClick:d,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((i,c)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input$1,{onChange:o=>r(c,"start",o.target.value),value:i.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input$1,{value:i.end,onChange:o=>r(c,"end",o.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input$1,{onChange:o=>r(c,"color",o.target.value),value:i.color,className:s.cn(`h-7 min-w-14 p-0 ${s.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:s.colors.green[600]}),e.jsx("option",{children:s.colors.red[500]}),e.jsx("option",{children:s.colors.yellow[400]}),e.jsx("option",{children:s.colors.orange[500]})]}),e.jsx(s.Button,{onClick:()=>l(c),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},c))]})}function jn(){var x,h,p,w,m;const t=s.useEditorStore(g=>g.card.preferences),n=s.useEditorStore(g=>g.actions.setCardPreferences),a=s.useEditorStore(g=>g.card),r=s.hasValidCardConfig(a.config),l=s.useEditorStore(g=>g.actions.setNumberFormat);s.useEditorStore(g=>{var v,C;return(C=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:C.decimalPlaces});const d=s.useEditorStore(g=>{var v,C;return(C=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:C.locale}),i=s.useEditorStore(g=>{var v,C;return(C=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:C.currency});s.useEditorStore(g=>g.actions.setFilterOnClickField);const c=s.useEditorStore(g=>{var v,C;return(C=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:C.colorRanges})||[],o=s.useEditorStore(g=>g.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(g=>g.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((x=t==null?void 0:t.formatNumber)!=null&&x.enabled),onCheckedChange:g=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:g}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:d||"none",onValueChange:g=>{var v,C,A;return l(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,((C=t==null?void 0:t.formatNumber)==null?void 0:C.currency)||"",g,((A=t==null?void 0:t.formatNumber)==null?void 0:A.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Format"}),e.jsx(s.SelectItem,{value:"none",children:"Auto"},"none"),s.LOCALE_CURRENCY_PAIRS.map(g=>e.jsx(s.SelectItem,{value:g.locale,children:g.locale},g.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:i||"none",onValueChange:g=>{var v,C,A;console.log("currency",g),l(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,g==="none"?"":g,((C=t==null?void 0:t.formatNumber)==null?void 0:C.locale)||"",((A=t==null?void 0:t.formatNumber)==null?void 0:A.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),u.map(g=>e.jsx(s.SelectItem,{value:g,children:g},g))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Decimals"}),e.jsxs(s.Select,{value:((w=(p=t==null?void 0:t.formatNumber)==null?void 0:p.decimalPlaces)==null?void 0:w.toString())||"0",onValueChange:g=>{var v,C,A;return l(Number(g),((v=t==null?void 0:t.formatNumber)==null?void 0:v.currency)||"",((C=t==null?void 0:t.formatNumber)==null?void 0:C.locale)||"",((A=t==null?void 0:t.formatNumber)==null?void 0:A.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["0","1","2","3","4"].map(g=>e.jsx(s.SelectItem,{value:g,children:g},g))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input$1,{value:((m=t==null?void 0:t.formatNumber)==null?void 0:m.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:g=>{var v,C,A;return l(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,((C=t==null?void 0:t.formatNumber)==null?void 0:C.currency)||"",((A=t==null?void 0:t.formatNumber)==null?void 0:A.locale)||"",g.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(gn,{colorRanges:c,setColorRanges:o})]})]})}function bn(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{type:"single",collapsible:!0,children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(s.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:t=>t.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(jn,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function Ge({children:t,summary:n,open:a,className:r}){return e.jsxs("details",{open:a,className:s.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(s.Label,{children:n}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const vn=[{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"}],yn=["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"],Nn=yn.map(t=>({label:t,value:t}));function Cn(){var o,u,x,h,p,w,m,g,v,C,A,B,O,E,N,f,j,S;const t=s.useEditorStore(M=>M.card),n=(u=(o=t==null?void 0:t.preferences)==null?void 0:o.mapVisualOptions)==null?void 0:u.topoJsonUrl,[a,r]=D.useState(((h=(x=t==null?void 0:t.preferences)==null?void 0:x.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:d}=s.useTopoJson(t),i=Object.keys((d==null?void 0:d.objects)||{}).map(M=>({label:M,value:M}))||[],c=[{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(Ge,{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(s.Separator,{className:"my-4"}),e.jsx(Ge,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(he,{className:"h-9",options:c,onValueChange:M=>{console.log("value",M),l({...t.preferences,mapVisualOptions:{topoJsonUrl:M}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input$1,{onChange:M=>{r(M.target.value)},onBlur:()=>{var M;console.log("onBlur",a),l({...t.preferences,mapVisualOptions:{...(M=t.preferences)==null?void 0:M.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),d&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(he,{className:"h-9",options:i,value:((w=(p=t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:w.objectKey)||"",label:"Map Object",onValueChange:M=>{var y;l({...t.preferences,mapVisualOptions:{...(y=t.preferences)==null?void 0:y.mapVisualOptions,objectKey:M}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(he,{className:"h-9",options:vn,value:((g=(m=t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:g.projection)||"",label:"Projection",onValueChange:M=>{var y;l({...t.preferences,mapVisualOptions:{...(y=t.preferences)==null?void 0:y.mapVisualOptions,projection:M}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(he,{className:"h-9",options:Nn,value:((C=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:C.colorScale)||"",label:"Select Color Scale",onValueChange:M=>{var y;l({...t.preferences,mapVisualOptions:{...(y=t.preferences)==null?void 0:y.mapVisualOptions,colorScale:M}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Ge,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input$1,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((B=(A=t.preferences)==null?void 0:A.mapVisualOptions)==null?void 0:B.projectionScale)||1,onChange:M=>{var y;l({...t.preferences,mapVisualOptions:{...(y=t.preferences)==null?void 0:y.mapVisualOptions,projectionScale:Number(M.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input$1,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((N=(E=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:N[0])||0,onChange:M=>{var y,b,I,F;l({...t.preferences,mapVisualOptions:{...(y=t.preferences)==null?void 0:y.mapVisualOptions,projectionOffset:[Number(M.target.value),((F=(I=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:F[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input$1,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((S=(j=(f=t.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:j.projectionOffset)==null?void 0:S[1])||0,onChange:M=>{var y,b,I,F;l({...t.preferences,mapVisualOptions:{...(y=t.preferences)==null?void 0:y.mapVisualOptions,projectionOffset:[((F=(I=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:F[0])||0,Number(M.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Se,{})]})}function Sn(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:n}=s.useEditorStore(l=>l.actions);function a(l){n({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:a,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.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(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Oe({cardType:t,docContent:n,suffix:a="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${a}`}),e.jsx(s.AccordionContent,{children:n||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:l=>l.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(Sn,{})})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(Me,{})]})]})]})})}function wn(){const t=s.useEditorStore(r=>{var l,d;return(d=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:d.sortChart}),{setSortChart:n}=s.useEditorActions();function a(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(he,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{n(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.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(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[a(),e.jsx(Bs,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(Me,{})]})]})]})})}function kn({cardType:t="table"}){console.log("cardType",t);const n=s.useEditorStore(l=>{var d;return(d=l.card)==null?void 0:d.preferences}),a=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{a({...n,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(Me,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.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"})]})]})}function Vs({color:t,onColorChange:n,onClose:a}){const[r,l]=D.useState(0),[d,i]=D.useState(100),[c,o]=D.useState(50),[u,x]=D.useState(t);D.useEffect(()=>{const v=is(t);if(v){const C=cs(v.r,v.g,v.b);l(C.h),i(C.s),o(C.l),x(t)}},[t]);const h=v=>{l(v),w(v,d,c)},p=v=>{const C=v.currentTarget.getBoundingClientRect(),A=Math.max(0,Math.min(1,(v.clientX-C.left)/C.width)),B=Math.max(0,Math.min(1,(v.clientY-C.top)/C.height)),O=A*100,E=(1-B)*100;i(O),o(E),w(r,O,E)},w=(v,C,A)=>{const B=En(v,C,A),O=Tn(B.r,B.g,B.b);x(O)},m=v=>{if(x(v),/^#[0-9A-Fa-f]{6}$/.test(v)){const C=is(v);if(C){const A=cs(C.r,C.g,C.b);l(A.h),i(A.s),o(A.l)}}},g=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(n(u),a())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:p,onMouseMove:v=>{v.buttons===1&&p(v)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${d}%`,top:`${100-c}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:v=>h(Number(v.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"HEX"}),e.jsx(s.Input$1,{value:u,onChange:v=>m(v.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:u}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:a,children:"Cancel"}),e.jsx(s.Button,{onClick:g,children:"OK"})]})]})}function is(t){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function Tn(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function cs(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),l=Math.min(t,n,a);let d=0,i=0;const c=(r+l)/2;if(r!==l){const o=r-l;switch(i=c>.5?o/(2-r-l):o/(r+l),r){case t:d=((n-a)/o+(n<a?6:0))/6;break;case n:d=((a-t)/o+2)/6;break;case a:d=((t-n)/o+4)/6;break}}return{h:Math.round(d*360),s:Math.round(i*100),l:Math.round(c*100)}}function En(t,n,a){t/=360,n/=100,a/=100;let r,l,d;if(n===0)r=l=d=a;else{const i=(u,x,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?u+(x-u)*6*h:h<.5?x:h<.6666666666666666?u+(x-u)*(.6666666666666666-h)*6:u),c=a<.5?a*(1+n):a+n-a*n,o=2*a-c;r=i(o,c,t+1/3),l=i(o,c,t),d=i(o,c,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(d*255)}}const An=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function zs(){var B,O,E,N,f,j,S,M,y,b;const t=s.useEditorStore(I=>I.card),n=s.useEditorStore(I=>{var F;return(F=I.card)==null?void 0:F.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[d,i]=D.useState({}),[c,o]=D.useState(null),[u,x]=D.useState(null),h=D.useMemo(()=>{var L,k,R,K,_,G,q;if(!(l!=null&&l.records)||l.records.length===0)return[];const I=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",F=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line"||(t==null?void 0:t.type)==="horizontalBar"||(t==null?void 0:t.type)==="bullet",T=((L=t==null?void 0:t.config)==null?void 0:L.pivotByColumns)&&t.config.pivotByColumns.length>0;if((I||F)&&T){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const V=new Set;return l.pivotSchema.forEach(z=>{z.alias&&V.add(z.alias)}),Array.from(V)}if(l.records.length>0){const V=l.records[0],z=Object.keys(V),H=new Set;(k=t==null?void 0:t.config)!=null&&k.groupByColumns&&t.config.groupByColumns.forEach(Y=>{H.add(Y.label||Y.name),H.add(Y.alias||Y.name)});const P=new Set;return(R=t==null?void 0:t.config)!=null&&R.metricColumns&&t.config.metricColumns.forEach(Y=>{const ee=Y.alias||Y.name;P.add(ee),P.add(`${ee}_count`),P.add(`${ee}_sum`),P.add(`${ee}_avg`),P.add(`${ee}_min`),P.add(`${ee}_max`);const J=Y.entityName||Y.qualifiedEntityName;J&&(P.add(`${J}_${ee}`),P.add(`${J}_${ee}_count`))}),z.filter(Y=>!H.has(Y)&&!P.has(Y))}}if((F||I)&&!T&&((_=(K=t==null?void 0:t.config)==null?void 0:K.metricColumns)!=null&&_.length))return t.config.metricColumns.map(V=>V.alias||V.label||V.name);if((q=(G=t==null?void 0:t.config)==null?void 0:G.groupByColumns)!=null&&q.length){const V=t.config.groupByColumns[0],z=V.label||V.name,H=new Set;return l.records.forEach(P=>{const W=P[z];W!=null&&H.add(String(W))}),Array.from(H)}return[]},[l,(B=t==null?void 0:t.config)==null?void 0:B.groupByColumns,(O=t==null?void 0:t.config)==null?void 0:O.pivotByColumns,(E=t==null?void 0:t.config)==null?void 0:E.metricColumns,t==null?void 0:t.type]),p=D.useMemo(()=>s.getDefaultChartColors(),[]);D.useEffect(()=>{const I={};h.forEach((F,T)=>{I[F]=s.getColorForValue(F,T,n==null?void 0:n.colorConfig)}),i(I)},[h,n==null?void 0:n.colorConfig,p]);const w=(I,F)=>{const T={...d,[I]:F};i(T);const L={...n||{},colorConfig:{segments:T}};a(L);const k={...t,preferences:L};r(k)},m=(I,F)=>{var _;const T=p[F%p.length],{[I]:L,...k}=((_=n==null?void 0:n.colorConfig)==null?void 0:_.segments)||{},R={...n||{},colorConfig:{segments:k}};a(R);const K={...t,preferences:R};r(K),i(G=>({...G,[I]:T}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((f=(N=t==null?void 0:t.config)==null?void 0:N.groupByColumns)==null?void 0:f.length)||((S=(j=t==null?void 0:t.config)==null?void 0:j.pivotByColumns)==null?void 0:S.length):(y=(M=t==null?void 0:t.config)==null?void 0:M.groupByColumns)==null?void 0:y.length)||["table","kpi","text","custom","heatmap"].includes(t.type))return null;const C=()=>{const I={...n||{},colorConfig:{segments:{}}};a(I);const F={...t,preferences:I};r(F);const T={};h.forEach((L,k)=>{T[L]=s.getColorForValue(L,k,void 0)}),i(T)},A=Object.keys(((b=n==null?void 0:n.colorConfig)==null?void 0:b.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(St,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(s.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:A&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:C,children:[e.jsx(as,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((I,F)=>{const T=s.isDefaultColor(d[I],F),L=!T;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:c===I,onOpenChange:k=>o(k?I:null),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:d[I]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:p.slice(0,10).map((k,R)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",d[I]===k?"border-gray-900":"border-transparent"),style:{backgroundColor:k},onClick:()=>{w(I,k),o(null)},children:[R===F%p.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:k})]},`default-${R}`))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Popular Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:An.map((k,R)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",d[I]===k?"border-2 border-gray-900":k==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:k},onClick:()=>{w(I,k),o(null)},children:e.jsx("span",{className:"sr-only",children:k})},`preset-${R}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{x({value:I,color:d[I]}),o(null)},children:"Custom color"}),!T&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{m(I,F),o(null)},children:[e.jsx(as,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:I}),L&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},I)})}),u&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>x(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Vs,{color:u.color,onColorChange:I=>{w(u.value,I),x(null)},onClose:()=>x(null)})})]})]})})]})}function pe({value:t,onSave:n,placeholder:a="",type:r="text",className:l=""}){const[d,i]=D.useState(t??""),[c,o]=D.useState(!1);D.useEffect(()=>{i(t??"")},[t]);const u=()=>{n(d),o(!1)},x=()=>{i(t??""),o(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input,{placeholder:a,type:r,value:c?d:t??"",onChange:h=>{i(h.target.value),o(!0)},onFocus:()=>o(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&c&&d!==t?u():h.key==="Escape"&&x()},"aria-label":a||"Edit field"}),c&&d!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:x,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const In=["auto","number","currency","percent","scientific","date"],Dn=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"GBP",label:"GBP - British Pound"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"CHF",label:"CHF - Swiss Franc"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"},{value:"HKD",label:"HKD - Hong Kong Dollar"},{value:"SGD",label:"SGD - Singapore Dollar"},{value:"NZD",label:"NZD - New Zealand Dollar"},{value:"SEK",label:"SEK - Swedish Krona"},{value:"NOK",label:"NOK - Norwegian Krone"},{value:"DKK",label:"DKK - Danish Krone"},{value:"KRW",label:"KRW - South Korean Won"},{value:"INR",label:"INR - Indian Rupee"},{value:"RUB",label:"RUB - Russian Ruble"},{value:"BRL",label:"BRL - Brazilian Real"},{value:"MXN",label:"MXN - Mexican Peso"},{value:"TRY",label:"TRY - Turkish Lira"},{value:"ZAR",label:"ZAR - South African Rand"},{value:"SAR",label:"SAR - Saudi Riyal"},{value:"AED",label:"AED - UAE Dirham"},{value:"ARS",label:"ARS - Argentine Peso"},{value:"CLP",label:"CLP - Chilean Peso"},{value:"COP",label:"COP - Colombian Peso"},{value:"THB",label:"THB - Thai Baht"},{value:"IDR",label:"IDR - Indonesian Rupiah"},{value:"MYR",label:"MYR - Malaysian Ringgit"},{value:"PHP",label:"PHP - Philippine Peso"},{value:"PLN",label:"PLN - Polish Zloty"},{value:"NGN",label:"NGN - Nigerian Naira"},{value:"KES",label:"KES - Kenyan Shilling"},{value:"GHS",label:"GHS - Ghanaian Cedi"},{value:"ZMW",label:"ZMW - Zambian Kwacha"},{value:"ZWL",label:"ZWL - Zimbabwean Dollar"},{value:"EGP",label:"EGP - Egyptian Pound"},{value:"MAD",label:"MAD - Moroccan Dirham"},{value:"UAH",label:"UAH - Ukrainian Hryvnia"},{value:"HUF",label:"HUF - Hungarian Forint"},{value:"CZK",label:"CZK - Czech Koruna"},{value:"RON",label:"RON - Romanian Leu"},{value:"PKR",label:"PKR - Pakistani Rupee"},{value:"BDT",label:"BDT - Bangladeshi Taka"},{value:"VND",label:"VND - Vietnamese Dong"},{value:"TWD",label:"TWD - New Taiwan Dollar"},{value:"ILS",label:"ILS - Israeli New Shekel"}],Mn=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"en-IN",label:"English (India)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"},{value:"ja-JP",label:"Japanese"},{value:"ko-KR",label:"Korean"},{value:"ru-RU",label:"Russian"},{value:"ar-SA",label:"Arabic"},{value:"hi-IN",label:"Hindi"},{value:"nl-NL",label:"Dutch"},{value:"sv-SE",label:"Swedish"}],Ln=t=>t.charAt(0).toUpperCase()+t.slice(1);function Ye({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",d=(c,o)=>{n({...t,[c]:o})},i=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:c=>d("type",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:In.map(c=>e.jsx(s.SelectItem,{value:c,className:"text-xs",children:c==="auto"?"Auto (Default)":Ln(c)},c))})]})]}),l!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(l)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??i(),onChange:c=>d("decimalPlaces",parseInt(c.target.value)||0),className:"h-8 text-xs"})})]}),l==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:c=>d("currency",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Dn.map(c=>e.jsx(s.SelectItem,{value:c.value,className:"text-xs",children:c.label},c.value))})]})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:c=>d("useSuffix",c)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:c=>d("locale",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Mn.map(c=>e.jsx(s.SelectItem,{value:c.value,className:"text-xs",children:c.label},c.value))})]})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{placeholder:"e.g., $",value:t.prefix||"",onChange:c=>d("prefix",c.target.value),className:"h-8 text-xs"})})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{placeholder:"e.g., units",value:t.suffix||"",onChange:c=>d("suffix",c.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:c=>d("negativeInParentheses",c)})]}),l==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:c=>d("multiplyBy",c.target.value?parseFloat(c.target.value):void 0),className:"h-8 text-xs"})})]}),l==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:c=>d("dateFormat",c.target.value),className:"h-8 text-xs"})})]})]})]})}function ds({axis:t,label:n,type:a,config:r,onChange:l}){var h,p,w,m,g,v,C,A,B,O,E,N;const d=(f,j)=>{l({...r,[f]:j})},i=(f,j)=>{var S,M;l({...r,name:{enabled:f==="enabled"?j:((S=r==null?void 0:r.name)==null?void 0:S.enabled)??!1,text:f==="text"?j:(M=r==null?void 0:r.name)==null?void 0:M.text}})},c=(f,j)=>{var S,M;l({...r,labels:{enabled:f==="enabled"?j:((S=r==null?void 0:r.labels)==null?void 0:S.enabled)??!0,rotation:f==="rotation"?j:(M=r==null?void 0:r.labels)==null?void 0:M.rotation}})},o=(f,j)=>{l({...r,scale:{...r==null?void 0:r.scale,[f]:j===""?"auto":Number(j)}})},u=t==="x"?["auto","top","bottom"]:["auto","left","right"],x=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:n})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:f=>d("enabled",f),onClick:f=>f.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:f=>i("enabled",f)})]}),((p=r==null?void 0:r.name)==null?void 0:p.enabled)&&e.jsx(pe,{placeholder:`${n} title`,value:((w=r==null?void 0:r.name)==null?void 0:w.text)||"",onSave:f=>i("text",f),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:f=>d("position",f),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(f=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:f==="auto"?"Auto (Default)":s.titleCase(f)},f))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((m=r==null?void 0:r.labels)==null?void 0:m.enabled)!==!1,onCheckedChange:f=>c("enabled",f)})]}),((g=r==null?void 0:r.labels)==null?void 0:g.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((v=r==null?void 0:r.labels)==null?void 0:v.rotation)||"auto"),onValueChange:f=>c("rotation",f==="auto"?"auto":Number(f)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:x.map(f=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:f==="auto"?"Auto (Default)":`${f}°`},f))})]})]})]}),a==="value"&&e.jsx(Ye,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:f=>l({...r,formatOptions:f}),showTitle:!0,title:"FORMAT"}),a==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"auto",value:((C=r==null?void 0:r.scale)==null?void 0:C.min)==="auto"||((A=r==null?void 0:r.scale)==null?void 0:A.min)===void 0?"":String(r.scale.min),onSave:f=>o("min",f),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"auto",value:((B=r==null?void 0:r.scale)==null?void 0:B.max)==="auto"||((O=r==null?void 0:r.scale)==null?void 0:O.max)===void 0?"":String(r.scale.max),onSave:f=>o("max",f),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"auto",value:((E=r==null?void 0:r.scale)==null?void 0:E.stepSize)==="auto"||((N=r==null?void 0:r.scale)==null?void 0:N.stepSize)===void 0?"":String(r.scale.stepSize),onSave:f=>o("stepSize",f),className:""})})]})]})]})]})]})}function $s(){const t=s.useEditorStore(i=>i.card),n=s.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi","treemap"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,n);if(!l.hasXAxis&&!l.hasYAxis)return null;const d=(i,c)=>{const u={...n||{},[i==="x"?"xAxisConfig":"yAxisConfig"]:c};a(u);const x={...t,preferences:u};r(x)};return e.jsxs(s.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ks,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[l.hasXAxis&&e.jsx(ds,{axis:"x",label:"X-Axis",type:l.xAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(t.type,"x"),n==null?void 0:n.xAxisConfig),onChange:i=>d("x",i)}),l.hasYAxis&&e.jsx(ds,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(t.type,"y"),n==null?void 0:n.yAxisConfig),onChange:i=>d("y",i)})]})})]})}function Ks(){const t=s.useEditorStore(x=>x.card),n=s.useEditorStore(x=>{var h,p,w,m;return(m=(w=(p=(h=x.card)==null?void 0:h.preferences)==null?void 0:p.chartOptions)==null?void 0:w.plugins)==null?void 0:m.legend}),{setLegendOptions:a}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r=s.getDefaultLegendConfig(t.type),l=(r==null?void 0:r.display)??!0,d=(r==null?void 0:r.position)??"top",i=(r==null?void 0:r.align)??"center",c=(x,h)=>{const p={...n,[x]:h};a(p)},o=["top","bottom","left","right"],u=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.display)??l,onCheckedChange:x=>c("display",x)})]}),((n==null?void 0:n.display)??l)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||d,onValueChange:x=>c("position",x),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:o.map(x=>e.jsx(s.SelectItem,{value:x,className:"text-xs",children:s.titleCase(x)},x))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(n==null?void 0:n.align)||i,onValueChange:x=>c("align",x),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(x=>e.jsx(s.SelectItem,{value:x,className:"text-xs",children:s.titleCase(x)},x))})]})]})]})]})})]})}function Gs(){var T,L,k,R,K,_,G,q,V,z,H;const t=s.useEditorStore(P=>P.card),n=s.useEditorStore(P=>{var W,Y;return(Y=(W=P.card)==null?void 0:W.preferences)==null?void 0:Y.dataLabelsConfig}),a=s.useEditorStore(P=>{var W;return(W=P.card)==null?void 0:W.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const d=t.type==="bullet"?((T=a==null?void 0:a.bulletConfig)==null?void 0:T.orientation)??(((L=a==null?void 0:a.chartOptions)==null?void 0:L.indexAxis)==="x"?"vertical":"horizontal"):void 0,i=d!=null?d==="horizontal":((k=a==null?void 0:a.chartOptions)==null?void 0:k.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",o=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",u=!o,x=t.type==="bubble"||t.type==="scatter",h=(K=(R=a==null?void 0:a.chartOptions)==null?void 0:R.plugins)==null?void 0:K.datalabels,p=(h==null?void 0:h.display)!==!1&&((h==null?void 0:h.anchor)||(h==null?void 0:h.align)),w=s.getDefaultDataLabelsConfig(t.type,t.preferences),m=n??w,g=(w==null?void 0:w.enabled)??p??!1,v=(n==null?void 0:n.enabled)!==void 0?n.enabled:g,C=(P,W)=>{const J={...w??{},...n??{},[P]:W};P==="enabled"&&(J.display=W,W&&x&&!J.position&&(J.position="bottom")),P==="position"&&x&&(J.position="bottom");const ne={...t.preferences||{},dataLabelsConfig:J};r(ne);const le={...t,preferences:ne};l(le)},A=(P,W)=>{const Y=n??{},J={...w??{},...Y,font:{...Y.font||{},[P]:W}},ne={...t.preferences||{},dataLabelsConfig:J};r(ne);const le={...t,preferences:ne};l(le)},B=(P,W)=>{const Y=n??{},J={...w??{},...Y,formatOptions:{...Y.formatOptions||{},[P]:W}},ne={...t.preferences||{},dataLabelsConfig:J};r(ne);const le={...t,preferences:ne};l(le)},O=()=>{const P=t.type;return P==="stackedBar"||P==="stackedLine"||P==="pie"||P==="doughnut"?"center":i?"right":"top"},E=t.type!=="treemap"&&t.type!=="heatmap",N=t.type!=="treemap",f=O();let j=[];if(E)if(x)j=["bottom"];else if(c||o)j=["center"];else{const P=i?["center","left","right"]:["center","top","bottom"];j=["auto",...t.type==="bullet"?P:P.filter(Y=>Y!==f),"custom"]}const S=()=>s.titleCase(f),M=["center","start","end"],y=["center","start","end","top","bottom"],b=u?["auto","number","currency","percent","none"]:["number","currency","percent","none"],I=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"}],F=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(It,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:v,onCheckedChange:P=>C("enabled",P)})]}),v&&e.jsxs(e.Fragment,{children:[E&&!c&&!o&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:x?(m==null?void 0:m.position)||"bottom":(m==null?void 0:m.position)||"auto",onValueChange:P=>C("position",P),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:j.map(P=>e.jsx(s.SelectItem,{value:P,className:"text-xs",children:P==="auto"?S():P==="custom"?"Custom (Advanced)":s.titleCase(P)},P))})]})]}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.showTotal)??!1,onCheckedChange:P=>C("showTotal",P)})]}),(m==null?void 0:m.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(s.Select,{value:(m==null?void 0:m.anchor)||"center",onValueChange:P=>C("anchor",P),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:M.map(P=>e.jsx(s.SelectItem,{value:P,className:"text-xs",children:s.titleCase(P)},P))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(s.Select,{value:String((m==null?void 0:m.align)||"center"),onValueChange:P=>C("align",P),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:y.map(P=>e.jsx(s.SelectItem,{value:P,className:"text-xs",children:s.titleCase(P)},P))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(m==null?void 0:m.format)||(u?"auto":"none"),onValueChange:P=>C("format",P),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:b.map(P=>e.jsx(s.SelectItem,{value:P,className:"text-xs",children:P==="auto"&&u?"Auto (Use Axis)":P==="none"?"None (Raw Value)":s.titleCase(P)},P))})]})]}),(m==null?void 0:m.format)&&!["auto","none"].includes(m.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(m.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"0",value:String(((_=m==null?void 0:m.formatOptions)==null?void 0:_.decimalPlaces)??(m.format==="currency"?2:m.format==="percent"?1:0)),onSave:P=>B("decimalPlaces",Number(P)),className:""})})]}),m.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((G=m==null?void 0:m.formatOptions)==null?void 0:G.currency)||"USD",onValueChange:P=>B("currency",P),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:I.map(P=>e.jsx(s.SelectItem,{value:P.value,className:"text-xs",children:P.label},P.value))})]})]}),["number","currency"].includes(m.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((q=m==null?void 0:m.formatOptions)==null?void 0:q.useSuffix)??!1,onCheckedChange:P=>B("useSuffix",P)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Locale"}),e.jsxs(s.Select,{value:((V=m==null?void 0:m.formatOptions)==null?void 0:V.locale)||"en-US",onValueChange:P=>B("locale",P),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:F.map(P=>e.jsx(s.SelectItem,{value:P.value,className:"text-xs",children:P.label},P.value))})]})]})]}),N&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"12",value:String(((z=m==null?void 0:m.font)==null?void 0:z.size)||12),onSave:P=>A("size",Number(P)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(s.Select,{value:((H=m==null?void 0:m.font)==null?void 0:H.weight)||"normal",onValueChange:P=>A("weight",P),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(s.Select,{value:(m==null?void 0:m.color)==="auto"||!(m!=null&&m.color)?"auto":"custom",onValueChange:P=>{P==="auto"&&C("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"0",value:String((m==null?void 0:m.rotation)||0),onSave:P=>C("rotation",Number(P)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const us=["poor","satisfactory","good"];function ms(t){if(!t)return;const n={...t};return n.targetMetricKey||delete n.targetMetricKey,n.comparativeMetricKey||delete n.comparativeMetricKey,!n.targetValue&&n.targetValue!==0&&delete n.targetValue,(!n.rangeKeys||Object.keys(n.rangeKeys).length===0)&&delete n.rangeKeys,(!n.ranges||Object.keys(n.ranges).length===0)&&delete n.ranges,(!n.rangeLabels||Object.keys(n.rangeLabels).length===0)&&delete n.rangeLabels,n}function qs(){var I,F;const t=s.useEditorStore(T=>T.card.preferences),n=s.useEditorStore(T=>T.card),a=s.useEditorStore(T=>T.isDevMode),{setCardPreferences:r,setChartOrientation:l}=s.useEditorActions(),d=D.useMemo(()=>(t==null?void 0:t.bulletConfig)||{},[t==null?void 0:t.bulletConfig]),c=s.hasValidCardConfig(n==null?void 0:n.config)&&!a,[o,u]=D.useState(d.showRanges??!1),[x,h]=D.useState(d.rangesArePercentages??!1),p=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!c,[w,m]=D.useState(p);D.useEffect(()=>{u(d.showRanges??!1)},[d.showRanges]),D.useEffect(()=>{h(d.rangesArePercentages??!1)},[d.rangesArePercentages]);const g=d.targetValue===void 0?"":String(d.targetValue);D.useEffect(()=>{const T=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!c;m(T)},[d.disableAutoComparative,d.comparativeMetricKey,c]);const v=D.useMemo(()=>{var T,L;return((L=(T=n==null?void 0:n.config)==null?void 0:T.metricColumns)==null?void 0:L.map(k=>{const R=k.label||k.name||k.alias||"";return{value:R,label:R}}))||[]},[(I=n==null?void 0:n.config)==null?void 0:I.metricColumns]);D.useEffect(()=>{var q,V;if(!t||v.length===0)return;const T={};let L=!1;const k=(q=v[1])==null?void 0:q.value;!d.targetMetricKey&&k&&(T.targetMetricKey=k,L=!0);const R=(V=v[2])==null?void 0:V.value;!d.comparativeMetricKey&&!d.disableAutoComparative&&R&&(T.comparativeMetricKey=R,L=!0);const K=v.slice(3),_={...d.rangeKeys||{}};let G=!1;if(us.forEach((z,H)=>{!_[z]&&K[H]&&(_[z]=K[H].value,G=!0)}),G&&(T.rangeKeys=_,L=!0,d.showRanges===void 0&&(T.showRanges=!0)),L){const z=ms({...d,...T});r({...t,bulletConfig:z})}},[v,d,t,r]);const C=T=>{const L=ms({...d,...T});r({...t,bulletConfig:L})},A=(T,L)=>{const k={...d.rangeKeys||{},[T]:L.trim()};L.trim()||delete k[T],C({rangeKeys:Object.keys(k).length>0?k:void 0})},B=(T,L)=>{const k=L===""?void 0:Number(L),R={...d.ranges||{}};k===void 0||Number.isNaN(k)?delete R[T]:R[T]=k,C({ranges:Object.keys(R).length?R:void 0})},O=T=>{if(T===""){C({targetValue:void 0});return}const L=Number(T);C({targetValue:Number.isNaN(L)?void 0:L})},E=(T,L)=>{const k=L.trim(),R={...d.rangeLabels||{}};k?R[T]=k:delete R[T],C({rangeLabels:Object.keys(R).length>0?R:void 0})},N=T=>{u(T),C({showRanges:T})},f=T=>{h(T),C({rangesArePercentages:T})},j=d.orientation||(((F=t==null?void 0:t.chartOptions)==null?void 0:F.indexAxis)==="y"?"horizontal":"vertical"),S=T=>{C({orientation:T}),l(T==="horizontal"?"y":"x")},M=[{value:"__none",label:"None"},...v.map(T=>({value:T.value,label:T.label}))],y=M,b=T=>{if(m(T),!T){C({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!c){C({disableAutoComparative:!1});return}if(d.comparativeMetricKey)C({disableAutoComparative:!1});else{const L=v.find(k=>k.value!==d.targetMetricKey);C({comparativeMetricKey:L==null?void 0:L.value,disableAutoComparative:!1})}};return e.jsxs(s.AccordionItem,{value:"bullet-config",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-6 border-t border-border/50 py-4",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"ORIENTATION"}),e.jsxs(s.Select,{value:j,onValueChange:T=>S(T),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"horizontal",className:"text-xs",children:"Horizontal"}),e.jsx(s.SelectItem,{value:"vertical",className:"text-xs",children:"Vertical"})]})]})]}),c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TARGET METRIC"}),e.jsxs(s.Select,{value:d.targetMetricKey||"__none",onValueChange:T=>C({targetMetricKey:T==="__none"?void 0:T}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"__none",className:"text-xs",children:"None"}),v.map(T=>e.jsx(s.SelectItem,{value:T.value,className:"text-xs",children:T.label},T.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),c?e.jsxs(s.Select,{value:d.comparativeMetricKey||"__none",onValueChange:T=>C({comparativeMetricKey:T==="__none"?void 0:T,disableAutoComparative:T==="__none"}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsx(s.SelectContent,{children:M.map(T=>e.jsx(s.SelectItem,{value:T.value,className:"text-xs",children:T.label},T.value))})]}):e.jsxs("div",{className:"space-y-2 rounded-md border border-border/50 p-3 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between font-medium",children:[e.jsx("span",{children:"Show comparative"}),e.jsx(s.SmallSwitch,{checked:w,onCheckedChange:T=>b(T)})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparative values are auto-detected from the third metric in your results."})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TARGET VALUE (FALLBACK)"}),e.jsx(ce,{type:"number",className:"h-8 text-xs",value:g,onCommit:O,placeholder:"Optional numeric fallback"})]})]}),e.jsxs("section",{className:"space-y-4 rounded-md border border-border/60 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"QUALITATIVE RANGES"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(s.Info,{className:"h-3.5 w-3.5"})})}),e.jsx(s.TooltipContent,{side:"top",children:"Use columns or static values for Poor / Average / Good."})]})})]}),e.jsx("div",{className:"flex items-center gap-2 text-xs font-medium",children:e.jsx(s.SmallSwitch,{checked:o,onCheckedChange:N})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:x,disabled:!o,onChange:T=>f(T.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),o&&e.jsx("div",{className:"space-y-3",children:us.map(T=>{var L,k,R,K,_;return e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/40 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[T," LABEL"]}),e.jsx(ce,{placeholder:`Display label (${T})`,value:((L=d.rangeLabels)==null?void 0:L[T])||"",onCommit:G=>E(T,G),className:"h-8 text-xs"})]}),c?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[T," COLUMN"]}),e.jsxs(s.Select,{value:((k=d.rangeKeys)==null?void 0:k[T])||"__none",onValueChange:G=>{G==="__none"?A(T,""):A(T,G)},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select column"})}),e.jsx(s.SelectContent,{children:y.map(G=>e.jsx(s.SelectItem,{value:G.value,className:"text-xs",children:G.label},G.value))})]})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[T," COLUMN KEY"]}),e.jsx(ce,{placeholder:"Column key",value:((R=d.rangeKeys)==null?void 0:R[T])||"",onCommit:G=>A(T,G),className:"h-8 text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[T," VALUE"]}),e.jsx(ce,{type:"number",placeholder:x?"0.80":"Static value",value:((K=d.ranges)==null?void 0:K[T])===void 0?"":String((_=d.ranges)==null?void 0:_[T]),onCommit:G=>B(T,G),className:"h-8 text-xs"})]})]},T)})})]})]})]})}const xs=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Fn=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Fe({value:t,onChange:n,label:a}){const[r,l]=D.useState(!1),[d,i]=D.useState(!1),c=()=>{const o=xs.find(u=>u.value===t);return o?o.color:t.startsWith("#")?t:xs[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:c()},"aria-label":`Change color for ${a}`})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:Fn.map(o=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",c()===o?"border-gray-900":"border-transparent"),style:{backgroundColor:o},onClick:()=>{n(o),l(!1)},children:e.jsx("span",{className:"sr-only",children:o})},o))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{i(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),d&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>i(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Vs,{color:c(),onColorChange:o=>{n(o),i(!1)},onClose:()=>i(!1)})})]})]})}const Bn=Object.keys(s.HEATMAP_PRESET_PALETTES);function Us(){const t=s.useEditorStore(p=>p.card),n=s.useEditorStore(p=>{var w;return(w=p.card)==null?void 0:w.preferences}),{setCardPreferences:a}=s.useEditorActions(),r=(t==null?void 0:t.type)==="heatmap",l=(n==null?void 0:n.heatmapConfig)||{},d=l.colorPalette??"green",i=l.legendPosition??"bottom",c=D.useMemo(()=>l.colorRange&&l.colorRange[0]&&l.colorRange[1]?[l.colorRange[0],l.colorRange[1]]:[...s.DEFAULT_HEATMAP_CUSTOM_RANGE],[l.colorRange]),o=p=>{const w={...l,...p};w.colorPalette!=="custom"?delete w.colorRange:(!w.colorRange||!w.colorRange[0]||!w.colorRange[1])&&(w.colorRange=[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]),a({...n||{},heatmapConfig:w})},u=p=>{o({colorPalette:p,colorRange:p==="custom"?l.colorRange??[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},x=(p,w)=>{const m=[...c];m[p]=w,o({colorPalette:"custom",colorRange:m})},h=p=>{o({legendPosition:p})};return r?e.jsxs(s.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(s.RadioGroup,{value:d,onValueChange:p=>u(p??"blue"),className:"space-y-3",children:[Bn.map(p=>{const w=s.HEATMAP_PRESET_PALETTES[p];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`heatmap-${p}`,value:p}),e.jsxs(s.Label,{htmlFor:`heatmap-${p}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:w.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${w.start}, ${w.end})`}})]})]},p)}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(s.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),d==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(Fe,{value:c[0],onChange:p=>x(0,p),label:"Start color"}),e.jsx(Fe,{value:c[1],onChange:p=>x(1,p),label:"End color"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Color scale position"}),e.jsxs(s.Select,{value:i,onValueChange:p=>h(p??"bottom"),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["top","bottom","left","right"].map(p=>e.jsx(s.SelectItem,{value:p,className:"text-xs",children:p[0].toUpperCase()+p.slice(1)},p))})]})]})]})]}):null}function hs(t){if(!t)return;const n={...t};if(n.xMetricKey||delete n.xMetricKey,n.yMetricKey||delete n.yMetricKey,n.radiusMetricKey||delete n.radiusMetricKey,n.labelKey||delete n.labelKey,n.groupKey||delete n.groupKey,n.enableGrouping===void 0&&delete n.enableGrouping,n.radiusScale||delete n.radiusScale,n.fixedRadius===void 0&&delete n.fixedRadius,n.minRadius===void 0&&delete n.minRadius,n.maxRadius===void 0&&delete n.maxRadius,Object.keys(n).length!==0)return n}function _s(){var E,N,f,j,S,M,y,b,I,F,T,L;const t=s.useEditorStore(k=>k.card.preferences),n=s.useEditorStore(k=>k.card),a=s.useEditorStore(k=>k.card.type),r=s.useEditorStore(k=>k.isDevMode),{setCardPreferences:l,updateCardInFrame:d}=s.useEditorActions(),i=a==="bubble",c=a==="scatter",o=D.useMemo(()=>(t==null?void 0:t.bubbleScatterConfig)||{},[t==null?void 0:t.bubbleScatterConfig]),x=s.hasValidCardConfig(n==null?void 0:n.config)&&!r,h=D.useMemo(()=>{var k,R;return((R=(k=n==null?void 0:n.config)==null?void 0:k.metricColumns)==null?void 0:R.map(K=>{const _=K.label||K.name||K.alias||"";return{value:_,label:_}}))||[]},[(E=n==null?void 0:n.config)==null?void 0:E.metricColumns]),p=D.useMemo(()=>{var k,R;return((R=(k=n==null?void 0:n.config)==null?void 0:k.groupByColumns)==null?void 0:R.map(K=>{const _=K.label||K.name||K.alias||"";return{value:_,label:_}}))||[]},[(N=n==null?void 0:n.config)==null?void 0:N.groupByColumns]),w=D.useMemo(()=>o.enableGrouping!==void 0?o.enableGrouping:!r&&p.length>=2,[o.enableGrouping,r,p.length]),[m,g]=D.useState(w);D.useEffect(()=>{g(w)},[w]);const v=k=>{const R={...t||{},bubbleScatterConfig:k};l(R),n&&d({...n,preferences:R})},C=k=>{l(k),n&&d({...n,preferences:k})};D.useEffect(()=>{if(!t||h.length===0)return;const k={};let R=!1;if(!o.xMetricKey&&h[0]&&(k.xMetricKey=h[0].value,R=!0),!o.yMetricKey&&h[1]&&(k.yMetricKey=h[1].value,R=!0),i&&!o.radiusMetricKey&&h[2]&&(k.radiusMetricKey=h[2].value,R=!0),!o.labelKey&&p[0]&&(k.labelKey=p[0].value,R=!0),w&&!o.groupKey&&p[1]&&(k.groupKey=p[1].value,k.enableGrouping=!0,R=!0),R){const K=hs({...o,...k});v(K)}},[h,p,o,t,l,i,w]);const A=k=>{const R=hs({...o,...k});v(R)},B=k=>{g(k),A({enableGrouping:k,groupKey:k?o.groupKey:void 0})};if(!i&&!c)return null;const O=i?s.Circle:s.ChartScatter;return e.jsxs(s.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(s.AccordionTrigger,{className:"py-2 text-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{className:"h-4 w-4"}),e.jsxs("span",{children:[i?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-1 pb-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-muted-foreground",children:["Dimensions",e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(s.Info,{className:"h-3 w-3"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{children:"Label identifies each point. Group creates separate series in the legend."})})]})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Label Column"}),x?e.jsxs(s.Select,{value:o.labelKey||"",onValueChange:k=>A({labelKey:k}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select label column"})}),e.jsx(s.SelectContent,{children:p.map(k=>e.jsx(s.SelectItem,{value:k.value,children:k.label},k.value))})]}):e.jsx(ce,{className:"h-8 text-xs",placeholder:"Column name for labels",value:o.labelKey||"",onCommit:k=>A({labelKey:k})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Group points into series"}),e.jsx(s.SmallSwitch,{checked:m,onCheckedChange:B})]}),m&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Group By"}),x?e.jsxs(s.Select,{value:o.groupKey||"",onValueChange:k=>A({groupKey:k}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select group column"})}),e.jsx(s.SelectContent,{children:p.map(k=>e.jsx(s.SelectItem,{value:k.value,children:k.label},k.value))})]}):e.jsx(ce,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:o.groupKey||"",onCommit:k=>A({groupKey:k})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Metrics"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"X Axis"}),x?e.jsxs(s.Select,{value:o.xMetricKey||"",onValueChange:k=>A({xMetricKey:k}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select X metric"})}),e.jsx(s.SelectContent,{children:h.map(k=>e.jsx(s.SelectItem,{value:k.value,children:k.label},k.value))})]}):e.jsx(ce,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:o.xMetricKey||"",onCommit:k=>A({xMetricKey:k})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Axis"}),x?e.jsxs(s.Select,{value:o.yMetricKey||"",onValueChange:k=>A({yMetricKey:k}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(s.SelectContent,{children:h.map(k=>e.jsx(s.SelectItem,{value:k.value,children:k.label},k.value))})]}):e.jsx(ce,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:o.yMetricKey||"",onCommit:k=>A({yMetricKey:k})})]}),i&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Radius"}),x?e.jsxs(s.Select,{value:o.radiusMetricKey||"",onValueChange:k=>A({radiusMetricKey:k}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(s.SelectContent,{children:h.map(k=>e.jsx(s.SelectItem,{value:k.value,children:k.label},k.value))})]}):e.jsx(ce,{className:"h-8 text-xs",placeholder:"Column name for radius",value:o.radiusMetricKey||"",onCommit:k=>A({radiusMetricKey:k})})]})]}),i&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Radius Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Scale Mode"}),e.jsxs(s.Select,{value:o.radiusScale||"sqrt",onValueChange:k=>A({radiusScale:k}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"sqrt",children:"Square Root (area-proportional)"}),e.jsx(s.SelectItem,{value:"linear",children:"Linear"}),e.jsx(s.SelectItem,{value:"fixed",children:"Fixed Size"})]})]})]}),o.radiusScale!=="fixed"&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Min Radius"}),e.jsx(ce,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((f=o.minRadius)==null?void 0:f.toString())||"",onCommit:k=>A({minRadius:k?Number(k):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Max Radius"}),e.jsx(ce,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((j=o.maxRadius)==null?void 0:j.toString())||"",onCommit:k=>A({maxRadius:k?Number(k):void 0})})]})]}),o.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(s.Label,{className:"text-xs",children:["Fixed Radius: ",o.fixedRadius||10]}),e.jsx(s.Slider,{value:[o.fixedRadius||10],onValueChange:([k])=>A({fixedRadius:k}),min:3,max:30,step:1,className:"py-2"})]})]}),c&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Point Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(s.Label,{className:"text-xs",children:["Point Size: ",o.fixedRadius||5]}),e.jsx(s.Slider,{value:[o.fixedRadius||5],onValueChange:([k])=>A({fixedRadius:k}),min:2,max:15,step:1,className:"py-2"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Axis Titles"}),e.jsx(s.SmallSwitch,{checked:((M=(S=t==null?void 0:t.xAxisConfig)==null?void 0:S.name)==null?void 0:M.enabled)??!1,onCheckedChange:k=>{var _,G,q,V;const R=o.xMetricKey||"X Axis",K=o.yMetricKey||"Y Axis";C({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{enabled:k,text:((G=(_=t==null?void 0:t.xAxisConfig)==null?void 0:_.name)==null?void 0:G.text)||R}},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{enabled:k,text:((V=(q=t==null?void 0:t.yAxisConfig)==null?void 0:q.name)==null?void 0:V.text)||K}}})}})]}),((b=(y=t==null?void 0:t.xAxisConfig)==null?void 0:y.name)==null?void 0:b.enabled)&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"X Title"}),e.jsx(ce,{className:"h-8 text-xs",placeholder:o.xMetricKey||"X Axis",value:((F=(I=t==null?void 0:t.xAxisConfig)==null?void 0:I.name)==null?void 0:F.text)||"",onCommit:k=>{var R;C({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{...(R=t==null?void 0:t.xAxisConfig)==null?void 0:R.name,enabled:!0,text:k||o.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Title"}),e.jsx(ce,{className:"h-8 text-xs",placeholder:o.yMetricKey||"Y Axis",value:((L=(T=t==null?void 0:t.yAxisConfig)==null?void 0:T.name)==null?void 0:L.text)||"",onCommit:k=>{var R;C({...t??{},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{...(R=t==null?void 0:t.yAxisConfig)==null?void 0:R.name,enabled:!0,text:k||o.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const On=[{value:"percentOfTotal",label:"% of Total",description:"Each stage shows percentage of the sum of all values"},{value:"percentOfFirst",label:"% of Stage 1",description:"First stage = 100%, others relative to first stage"}];function Hs(){const t=s.useEditorStore(p=>p.card),n=s.useEditorStore(p=>{var w;return(w=p.card)==null?void 0:w.preferences}),{setCardPreferences:a}=s.useEditorActions(),r=(t==null?void 0:t.type)==="funnel",l=(n==null?void 0:n.funnelConfig)||{},d=l.percentMode??"percentOfTotal",i=l.shrinkFraction??1,c=l.labelThreshold??0,o=p=>{const w={...l,...p};a({...n||{},funnelConfig:w})},u=p=>{o({percentMode:p})},x=p=>{o({shrinkFraction:p[0]})},h=p=>{o({labelThreshold:p[0]})};return r?e.jsxs(s.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Filter,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Funnel Settings"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"PERCENTAGE MODE"}),e.jsx(s.RadioGroup,{value:d,onValueChange:p=>u(p),className:"space-y-2",children:On.map(p=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`funnel-${p.value}`,value:p.value,className:"mt-0.5"}),e.jsxs(s.Label,{htmlFor:`funnel-${p.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:p.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p.description})]})]},p.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SEGMENT SHRINK"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Same Width"}),e.jsx(s.Slider,{value:[i],onValueChange:x,min:0,max:1,step:.1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Full Shrink"})]}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Current: ",Math.round(i*100),"%"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABEL VISIBILITY THRESHOLD"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Show All"}),e.jsx(s.Slider,{value:[c],onValueChange:h,min:0,max:25,step:1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Hide Small"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:c===0?"Showing all labels":`Hide labels below ${c}%`})]})]})]}):null}function Rn(){const t=s.useEditorStore(n=>n.card);return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[(t==null?void 0:t.type)==="funnel"&&e.jsx(Hs,{}),(t==null?void 0:t.type)==="heatmap"&&e.jsx(Us,{}),(t==null?void 0:t.type)==="bullet"&&e.jsx(qs,{}),((t==null?void 0:t.type)==="bubble"||(t==null?void 0:t.type)==="scatter")&&e.jsx(_s,{}),e.jsx(zs,{}),e.jsx($s,{}),e.jsx(Ks,{}),e.jsx(Gs,{})]})]})}const Pn=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:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),Vn=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:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),zn=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:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function $n(){const t=s.useEditorStore(a=>a.card.type);function n(a){const r=["kpi","table","text","map","custom"],l=d=>r.includes(a)?d:e.jsxs(e.Fragment,{children:[d,e.jsx(Rn,{})]});switch(a){case"stackedBar":case"stackedLine":return l(e.jsx(wn,{}));case"tornado":case"pyramid":return l(e.jsx(Oe,{docContent:Pn,cardType:a}));case"kpi":return e.jsx(bn,{});case"line":case"bar":return l(e.jsx(un,{cardType:a}));case"range":return l(e.jsx(Oe,{docContent:Vn,cardType:a}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(Oe,{cardType:a}));case"bubble":case"scatter":return l(e.jsx(mn,{cardType:a}));case"table":return e.jsx(kn,{cardType:a});case"text":return e.jsx(Oe,{docContent:zn,cardType:a,suffix:"Visual"});case"map":return e.jsx(Cn,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Fs,{})});default:return l(e.jsx(pn,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Kn(){const t=D.useRef(null),n=D.useRef(null),a=s.useEditorStore(l=>l.isShowingVisual),r=s.useEditorStore(l=>l.showAIDialog);return D.useEffect(()=>{var l,d,i,c;r?((l=t.current)==null||l.resize(0),(d=n.current)==null||d.resize(0)):((i=t.current)==null||i.resize(25),(c=n.current)==null||c.resize(25))},[r]),e.jsxs(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(zt,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:a&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx($n,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(os,{})})]}):e.jsx(os,{})})]})}function Gn(t){var oe;s.useAIInteractionStore($=>$.currentAIContext);const[n,a]=D.useState(""),[r,l]=D.useState(null),{authToken:d,tokenProps:i}=s.useSemaphorContext(),c=s.useEditorStore($=>{var se;return(se=$==null?void 0:$.card)==null?void 0:se.sql}),o=s.useEditorStore($=>$.isDevMode),u=s.useEditorStore($=>{var se;return(se=$==null?void 0:$.card)==null?void 0:se.python}),{setCardPython:x,setCardSql:h,setRunSql:p,switchCardType:w,setQueryConfig:m}=s.useEditorActions(),g=s.useEditorStore($=>$.currentAssitantScope)||[],v=s.useEditorStore($=>$.userInputForAI),C=s.useEditorStore($=>$.triggerAIRun),A=s.useEditorStore($=>$.card),B=s.useEditorStore($=>$.selectedDatabaseName),O=s.useEditorStore($=>$.selectedTableName),E=s.useEditorStore($=>$.selectedConnectionId),N=s.useEditorStore($=>$.selectedSchemaName),f=s.useDashboardStore($=>$.dashboard.aiScopeTables),{errorMessage:j,refetch:S,data:M}=s.useDashboardCardQuery(A),{setTriggerAIRun:y,setCurrentAssitantScope:b,setCardConfig:I}=s.useEditorActions(),{selectedDatamodelName:F,connectionType:T,selectedDatamodelId:L}=s.useEditorAside(),k=(oe=s.useDashboardQuery().data)==null?void 0:oe.assistantProfileId,{messages:R,setMessages:K,regenerate:_,error:G,sendMessage:q,status:V,addToolResult:z,stop:H,clearError:P}=s.useChat({transport:new s.DefaultChatTransport({api:`${i.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${d==null?void 0:d.accessToken}`}),body:()=>{const $=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:k,isDevMode:o,aiContext:$.currentAIContext,reasoningEffort:$.reasoningEffort,showReasoning:$.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:$,body:se})=>({body:{...se,messages:s.cleanupIncompleteMessages($)}})}),onError:$=>{var se;if($.name==="AbortError"||(se=$.message)!=null&&se.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",$)},onToolCall:W,onFinish({isAbort:$,isDisconnect:se,isError:de}){a(""),console.log($?"[Editor Assistant] Stream aborted by user":se?"[Editor Assistant] Stream disconnected (network error)":de?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});D.useEffect(()=>{C&&v&&(q({role:"user",parts:[{type:"text",text:v}]}),y(!1))},[C,v,q,y]);async function W({toolCall:$}){var se,de,ue,we,me,je,xe,be,ke,fe,Te,Ee,Ae,Ie,ve,ye;if(["createChartFromSql","createForecast"].includes($.toolName)){const Q=((se=$.input)==null?void 0:se.sql)??((de=$.args)==null?void 0:de.sql),ae=((ue=$.input)==null?void 0:ue.python)??((we=$.args)==null?void 0:we.python),re=((me=$.input)==null?void 0:me.chartType)??((je=$.args)==null?void 0:je.chartType);w(re),h(Q),x(ae),p(!0),z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if($.toolName==="getUserSql"){if(!c){z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",message:"No SQL found"}});return}z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",sql:c,python:u||""}})}else if($.toolName==="generateQueryConfig"){a("Generating query config...");const Q=((xe=$.input)==null?void 0:xe.chartType)??((be=$.args)==null?void 0:be.chartType),ae=((ke=$.input)==null?void 0:ke.queryConfig)??((fe=$.args)==null?void 0:fe.queryConfig);((Te=$.input)==null?void 0:Te.cardConfig)??((Ee=$.args)==null||Ee.cardConfig),w(Q),I(ae),h(void 0),x(void 0);const re=await S();if((Ae=re==null?void 0:re.data)!=null&&Ae.error){z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",queryConfig:ae,message:(Ie=re==null?void 0:re.data)==null?void 0:Ie.error.message}});return}if((ve=re==null?void 0:re.data)!=null&&ve.records){z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:ae,message:"The data has been visualized"}});return}z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:ae,message:"The data has been visualized",records:(ye=re==null?void 0:re.data)==null?void 0:ye.records}})}else a("Analyzing...")}function Y($){const se=s.removeFromScopeArray(g,$);ee(se)}function ee($){const se=s.sanitizeAIScope($);b(se),K(de=>[...de,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(se)}`}]}])}function J(){const $={databaseName:B||"",schemaName:N||"",tableName:O||"",datamodelId:L||"",datamodelName:s.resolveDatamodelName(F),connectionId:E||"",connectionType:T||""},se=s.dedup([...g,$]);ee(se)}function ne(){const $={databaseName:B||"",schemaName:N||"",tableName:O||"",datamodelName:s.resolveDatamodelName(F),connectionId:E||"",connectionType:T||"",datamodelId:L||""};if(!s.isInAiScopeArray([...f||[],...g],$)||g.length===0){const de=s.dedup([...f||[],...g,$]).filter(ue=>ue.connectionId===$.connectionId);ee(de)}}const le=!["ready","error"].includes(V),Z=s.getErrorMessage(G);return{messages:R,setMessages:K,sendMessage:q,regenerate:_,isLoading:le,handleSetAIScope:ne,handleAddCurrentTableToScope:J,removeFromCurrentSelections:Y,currentAssitantScope:g,setCurrentAssitantScope:b,stop:H,status:V,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:Z,clearError:P}}const qn=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function ps({isFullscreen:t,onFullscreenChange:n,fullscreenContainer:a}){const r=D.useRef(null),[l,d]=D.useState(!1),[i,c]=D.useState(s.isDevEnv),[o,u]=D.useState(!1),[x,h]=D.useState(!1),[p,w]=D.useState(!1),m=t??p,g=s.useCurrentAIContext(),{setCurrentAIContext:v}=s.useAIActions(),{clearQueue:C}=s.useQueueActions(),{clearFileAttachments:A}=s.useFileActions(),B=s.useFileAttachments("editor"),O=s.useDashboardStore(Q=>Q.dashboard.aiContext),E=s.useEditorStore(Q=>Q.card.dataSource),N=s.useEditorStore(Q=>Q.actions.setCardSql),f=s.useEditorStore(Q=>Q.actions.setRunSql),j=s.useEditorStore(Q=>Q.showAIDialog),S=s.useDashboardStore(Q=>Q.handleOpenAssistantProfile),{setShowAIDialog:M,setCardPython:y}=s.useEditorActions(),{setDataSource:b}=s.useEditorActions(),{assistantProfile:I}=s.useAssistantProfile(),{messages:F,setMessages:T,sendMessage:L,isLoading:k,stop:R,status:K,llmUsage:_,errorMessage:G,clearError:q}=Gn(),[V,z]=D.useState(""),H=Q=>{z(Q.target.value)},P=Q=>{Q.preventDefault();const ae=V.trim();if(!ae&&B.length===0)return;const re=[];ae&&re.push({type:"text",text:ae}),B.forEach(Ne=>{Ne.data&&re.push({type:"file",mediaType:Ne.type,filename:Ne.name,url:`data:${Ne.type};base64,${Ne.data}`})}),L({role:"user",parts:re}),z(""),A("editor"),se({force:!0})},{visibleMessages:W,hasMoreMessages:Y,totalMessageCount:ee,loadMoreMessages:J,resetMessageWindow:ne}=s.useMessageWindow(F,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:le,isAtBottom:Z,hasNewMessages:oe,newMessageCount:$,scrollToBottom:se,handleScroll:de,resetNewMessageCount:ue}=s.useAutoScroll(W,{threshold:50,behavior:"smooth",isStreaming:k});D.useEffect(()=>{var Q;j&&((Q=r.current)==null||Q.focus(),v({selectedEntities:(E==null?void 0:E.selectedEntities)||[]}))},[j,E,v]),s.useAutoSubmitQueue({assistantType:"editor",status:K,isLoading:k,sendMessage:L});const{hasActiveTools:we}=s.useActiveToolStatus(F),me=D.useCallback(Q=>{n==null||n(Q),t===void 0&&w(Q)},[t,n]);D.useEffect(()=>{if(!m)return;function Q(ae){ae.key==="Escape"&&me(!1)}return window.addEventListener("keydown",Q),()=>{window.removeEventListener("keydown",Q)}},[m,me]);const je=D.useCallback(Q=>{L({role:"user",parts:[{type:"text",text:Q}]}),se({force:!0})},[L,se]),xe=D.useCallback(async()=>{const Q=JSON.stringify(F??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Q),s.ue.success("Conversation copied")}catch(ae){console.error("Failed to copy conversation",ae),s.ue.error("Unable to copy conversation")}},[F]),be=D.useCallback(()=>{me(!m)},[m,me]);function ke(Q,ae){ae==="sql"?(N(Q),f(!0)):ae==="python"&&(y(Q),f(!0))}function fe(){g.selectedEntities.length===0&&v({selectedEntities:(O==null?void 0:O.selectedEntities)||[]})}function Te(Q){fe();const ae={role:"user",parts:[{type:"text",text:Q.title+" "+Q.subtitle}]};L(ae)}function Ee(Q){fe(),L({role:"user",parts:[{type:"text",text:Q}]})}function Ae(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:d,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:c,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:u,children:"System Message"})]})]})}function Ie(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const ve=(V==null?void 0:V.length)===0&&(F==null?void 0:F.filter(Q=>Q.role==="user").length)===0,ye=e.jsxs("div",{"data-role":"editor-assistant",className:s.cn("flex h-full w-full flex-col justify-between px-6 py-4",m&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Ie(),S&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:S,children:(I==null?void 0:I.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Ae(),i&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:xe,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:m?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:be,children:m?e.jsx(s.Minimize2,{className:"size-4"}):e.jsx(s.Maximize2,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{T([]),C("editor"),q(),ne()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{M(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:le,className:"mt-2 flex w-full grow basis-0",onScroll:de,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[Y&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:J,className:"text-xs",children:["Load ",Math.min(5,ee-W.length)," ","more messages (",ee-W.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:W,showTools:i,handleRun:ke,showSystemMessage:o,onQuickReply:je,disableQuickReplies:k}),!we&&e.jsx(s.AssistantStatus,{status:K,errorMessage:G})]})}),j&&!Z&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{se({force:!0}),ue()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),oe&&$>0&&e.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:$>9?"9+":$})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[ve&&!I&&e.jsx(s.Placeholders,{onClick:Te,placeholders:qn}),e.jsx("div",{children:ve&&I&&e.jsx(s.SeedQuestions,{seedQuestions:I.seedQuestions||[],handleSeedQuestionClick:Ee})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:z,stop:R,input:V,handleInputChange:H,handleSubmit:Q=>{fe(),P(Q),se({force:!0})},isLoading:k,status:K,assistantType:"editor",onFocus:()=>{}})]}),_&&l&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",_.inputTokens," prompt tokens, ",_.outputTokens," ","completion tokens, ",_.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(E==null?void 0:E.selectedEntities)||[],open:x,onOpenChange:h,dataSource:E||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return m&&a?nt.createPortal(e.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:e.jsx("div",{className:"flex h-full w-full",children:ye})}),a):ye}const Un="chart-selector-standard-first";function _n(){const[t,n]=Ve(Un,!0);return{standardFirst:t,updatePreference:n}}const fs=({pluginVisual:t,index:n,onSelect:a})=>{const r=s.useDynamicIcon(t.icon||""),l=t.name.charAt(0).toUpperCase(),d=s.getAutoDetectedChartIcon(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:a,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):d||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:l}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${n}`)},gs=["default","standardPlugin","customPlugin"];function Hn({selectedChart:t,onChartChange:n}){var E;const[a,r]=D.useState(!1),{data:l}=s.useCustomVisualsQuery();_n();const i=((E=s.useEditorStore(N=>N.card).customCardPreferences)==null?void 0:E.url)||"";at.useRemoteChartStore(i);const{setCardType:c,setCardPreferences:o,setIsDevMode:u}=s.useEditorStore(N=>N.actions),{setCardCustomCfg:x,setCustomCardPreferences:h,setQueryConfig:p}=s.useEditorActions(),[w,m]=Ve("chart-section-active",null),g=D.useMemo(()=>w?[w,...gs.filter(N=>N!==w)]:gs,[w]);function v(N){x(null),o({}),c(N),["custom","map"].includes(N)&&(u(!0),p(void 0)),n(N),r(!1)}function C(N){x(null),o({}),c("custom"),h({type:"component",visualType:"single",url:N.url,componentName:N.name,icon:N.icon,pluginChartType:N.chartType}),p(void 0),n("custom"),r(!1)}const A=D.useMemo(()=>{let N=s.chartTypes;return N=s.chartTypes.filter(j=>j.id!=="tableBuilder"),N.some(j=>j.id==="bullet")?N:[...N,{id:"bullet",icon:s.BulletChartIcon,label:"Bullet Chart"}]},[]),B=()=>{var f;if(t==="custom"){const j=s.useEditorStore.getState().card;return((f=j==null?void 0:j.customCardPreferences)==null?void 0:f.componentName)||"Custom Visual"}const N=A.find(j=>j.id===t);return(N==null?void 0:N.label)||"Select chart type"},O=()=>{var f,j;if(t==="custom"){const S=s.useEditorStore.getState().card,M=(f=S==null?void 0:S.customCardPreferences)==null?void 0:f.icon,y=(j=S==null?void 0:S.customCardPreferences)==null?void 0:j.componentName;if(M&&y)return e.jsx(Jn,{icon:M,componentName:y});if(y){const b=s.getAutoDetectedChartIcon(y);if(b)return b}return e.jsx(De,{className:"h-4 w-4"})}const N=A.find(S=>S.id===t);if(N){const S=N.icon;return e.jsx(S,{className:"h-4 w-4"})}return e.jsx(De,{className:"h-4 w-4"})};return e.jsx("div",{className:"",children:e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[O(),e.jsx("span",{children:B()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),g.map(N=>{if(N==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:w==="default",onCheckedChange:f=>m(f?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:A.map(f=>{const j=f.icon;return e.jsx(s.CommandItem,{value:`${f.label} ${f.id} chart graph visualization`,onSelect:()=>v(f.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(j,{className:"h-4 w-4"}),e.jsx("span",{children:f.label})]})},f.id)})},"default");if(N==="standardPlugin"){const f=l.filter(j=>j.pluginType==="standard");return f.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:w==="standardPlugin",onCheckedChange:j=>m(j?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:f.filter(j=>j.componentType==="chart").map((j,S)=>e.jsx(fs,{pluginVisual:j,index:S,onSelect:()=>C(j)},`${j.url}-${j.name}-${S}`))},"standardPlugin"):null}if(N==="customPlugin"){const f=l.filter(j=>j.pluginType==="custom");return f.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:w==="customPlugin",onCheckedChange:j=>m(j?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:f.map((j,S)=>e.jsx(fs,{pluginVisual:j,index:S,onSelect:()=>C(j)},`${j.url}-${j.name}-${S}`))},"customPlugin"):null}return null})]})]})})]})})}const Jn=({icon:t,componentName:n})=>{const a=s.useDynamicIcon(),r=s.getAutoDetectedChartIcon(n);return a?e.jsx(a,{className:"h-4 w-4"}):r||e.jsx(De,{className:"h-4 w-4"})},Qn=[{id:"table",icon:s.Table2,label:"Table"},{id:"bar",icon:s.ChartColumnIncreasing,label:"Bar Chart"},{id:"line",icon:s.ChartLine,label:"Line Chart"},{id:"stackedBar",icon:s.ChartColumnStacked,label:"Stacked Bar",requiresPivot:!1},{id:"pie",icon:s.ChartPie,label:"Pie Chart"},{id:"doughnut",icon:s.Donut,label:"Donut Chart"},{id:"kpi",icon:s.TiSortNumerically,label:"KPI"},{id:"treemap",icon:s.TbChartTreemap,label:"Treemap"},{id:"bullet",icon:s.BulletChartIcon,label:"Bullet Chart"},{id:"funnel",icon:s.TbChartFunnel,label:"Funnel Chart"},{id:"tornado",icon:s.Tornado,label:"Tornado Chart"},{id:"heatmap",icon:s.Grid3x3,label:"Heatmap"},{id:"range",icon:s.ChartNoAxesGantt,label:"Range Chart"}];function Yn({selectedChart:t,onChartChange:n,isDropdownExpanded:a,onToggleDropdown:r}){var c;const l=s.useEditorStore(o=>o.card),d=((c=l==null?void 0:l.config)==null?void 0:c.pivotByColumns)&&l.config.pivotByColumns.length>0,i=Qn.filter(o=>!(o.requiresPivot&&!d));return e.jsxs("div",{className:"grid grid-cols-7 gap-2",children:[i.map(o=>{const u=o.icon,x=t===o.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>n(o.id),className:s.cn("h-8 w-8 p-0",x&&"bg-accent text-accent-foreground"),children:[e.jsx(u,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:o.label})]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:"border-foreground/20 bg-foreground text-background",children:[e.jsx("p",{children:o.label}),e.jsx(s.TooltipArrow,{className:"fill-foreground"})]})]},o.id)}),r&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0","aria-label":a?"Hide all charts":"Show all charts",children:a?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})})}),e.jsxs(s.TooltipContent,{side:"bottom",className:"border-foreground/20 bg-foreground text-background",children:[e.jsx("p",{children:a?"Hide dropdown":"Show all charts"}),e.jsx(s.TooltipArrow,{className:"fill-foreground"})]})]})]})}let Wn=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce((n,a)=>(a&=63,a<36?n+=a.toString(36):a<62?n+=(a-26).toString(36).toUpperCase():a>62?n+="-":n+="_",n),"");const Pe=[{id:"sum",label:"Sum",symbol:"+",description:"Add two metrics together",template:()=>"({field_0} + {field_1})",requiresTwoInputs:!0},{id:"difference",label:"Difference",symbol:"−",description:"Subtract one metric from another",template:()=>"({field_0} - {field_1})",requiresTwoInputs:!0},{id:"product",label:"Product (Multiplication)",symbol:"×",description:"Multiply two metrics",template:()=>"({field_0} * {field_1})",requiresTwoInputs:!0},{id:"ratio",label:"Ratio",symbol:"÷",description:"Divide one metric by another",template:()=>"({field_0} / NULLIF({field_1}, 0))",requiresTwoInputs:!0},{id:"change",label:"Change",symbol:"Δ",description:"Calculate percentage change from A to B",template:()=>"(({field_1} - {field_0}) / NULLIF({field_0}, 0))",requiresTwoInputs:!0},{id:"percentage",label:"Percentage",symbol:"%",description:"Calculate (A / B) × 100",template:()=>"(({field_0} / NULLIF({field_1}, 0)) * 100)",requiresTwoInputs:!0},{id:"scale",label:"Scale (Multiply by Factor)",symbol:"×n",description:"Multiply a metric by a constant factor",template:()=>"({field_0} * {constant})",requiresTwoInputs:!1},{id:"custom",label:"Custom Expression",symbol:"{}",description:"Drag fields to create custom expression with tokens",requiresTwoInputs:!1,allowsCustomExpression:!0}];function Xn(t,n,a,r,l,d,i,c,o){const u=Pe.find(g=>g.id===n);if(!u)throw new Error(`Unknown operation: ${n}`);let x,h=[],p;if(n==="custom"){if(!(c!=null&&c.trim()))throw new Error("Custom expression is required");x=c.trim()}else if(n==="scale"){if(!a)throw new Error("Metric A is required for scale operation");if(o===void 0||o===0)throw new Error("Constant factor is required for scale operation");x=u.template().replace("{constant}",String(o)),h=[a],p=o}else{if(!a||!r)throw new Error("Metrics A and B are required for standard operations");x=u.template(),h=[a,r]}const w={operation:n,inputFields:h,...p!==void 0&&{constant:p}};return{id:i||`calc_${Wn(10)}`,name:t.toLowerCase().replace(/\s+/g,"_"),label:t,alias:t.toLowerCase().replace(/\s+/g,"_"),qualifiedFieldName:t.toLowerCase().replace(/\s+/g,"_"),dataType:"number",role:"metric",aggregate:"SUM",expression:x,calculatedFormula:w,entityId:d,entityName:s.CALCULATED_FIELD_ENTITY_MARKER,entityType:"table",description:`Calculated field: ${t}`}}function js(t){var r,l;const n=Pe.find(d=>d.id===t.operation);if(!n)return"Unknown operation";if(t.operation==="custom")return"Custom expression";if(t.operation==="scale"){const d=((r=t.inputFields[0])==null?void 0:r.label)||((l=t.inputFields[0])==null?void 0:l.name)||"A",i=t.constant??1;return`${d} × ${i}`}return t.inputFields.map(d=>d.label||d.name).join(` ${n.symbol} `)}const We=({dataType:t})=>s.getFieldIconComponent(t);function Zn({aliasTemplate:t,onAliasTemplateChange:n}){var o;const[a,r]=D.useState(t),[l,d]=D.useState(!1),i=(o=s.useEditorStore(u=>{var x;return(x=u.card.config)==null?void 0:x.pivotByColumns}))==null?void 0:o[0],c=i?`e.g. Min Sales in {{${i.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.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(s.Input,{placeholder:c,value:l?a:t,onChange:u=>{r(u.target.value),d(!0)},onFocus:()=>d(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&l&&a!==t?(n(a),d(!1)):u.key==="Escape"&&(r(t),d(!1))},"aria-label":"Edit alias template"}),l&&a!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{n(a),d(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),d(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function ea({valueAliases:t,onValueAliasesChange:n}){const[a,r]=D.useState(null),[l,d]=D.useState(""),[i,c]=D.useState(""),o=()=>{n({...t,"":""})},u=h=>{const p={...t};delete p[h],n(p)},x=h=>{const p={...t};delete p[h],p[l]=i,n(p),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,p],w)=>e.jsx("div",{className:"flex items-center gap-2",children:a===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input,{placeholder:"Value key",value:l,onChange:m=>d(m.target.value),className:"h-8 w-24 text-xs",onPointerDown:m=>m.stopPropagation(),onKeyDown:m=>{m.key==="Enter"?x(h):m.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input,{placeholder:"Alias label",value:i,onChange:m=>c(m.target.value),className:"h-8 w-24 text-xs",onPointerDown:m=>m.stopPropagation(),onKeyDown:m=>{m.key==="Enter"?x(h):m.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>x(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),d(h),c(p)},"aria-label":"Edit value alias key"}),e.jsx(s.Input,{placeholder:"Alias label",value:p,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),d(h),c(p)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+w)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:o,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function sa({column:t}){const n=s.useEditorStore(o=>o.card.type),a=s.useEditorStore(o=>{var u,x;return(x=(u=o.card)==null?void 0:u.config)==null?void 0:x.metricColumns}),r=(a==null?void 0:a.map(o=>o.label))||[],l=r==null?void 0:r.find(o=>o===t.label||o===t.name),d=l?r.indexOf(l):-1;function i(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(Rs,{idx:d,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function c(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Ps,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&i(),["pie","doughnut"].includes(n)&&c()]})}function ta({field:t,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:l}=s.useSemaphorContext(),d=s.useEditorStore(u=>u.card),i=d==null?void 0:d.dataSource,c=["attribute-values",t.entityName,t.name,n,a],o=s.useQuery({queryKey:c,queryFn:async()=>{if(!(i!=null&&i.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},x={connection_id:i.connectionId,cardConfig:u,cardDataSource:i,cache_config:s.getCacheConfig({card:d})};console.log("requestBody",x);const h=await s.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",x);if(h!=null&&h.error)return console.error("Error fetching attribute values:",h.error),[];const p=t.name;return((h==null?void 0:h.records)||[]).map(m=>{const g=m[p]||m[t.alias||p]||m[t.label];return{id:g||"",value:g||"",label:String(g||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(i!=null&&i.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:o.data||[],isLoading:o.isLoading,isFetching:o.isFetching,isError:o.isError,error:o.error,refetch:o.refetch}}function Js({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:l,onSave:d}){var B,O;const i=!!l,[c,o]=D.useState(i?"values":"fields"),[u,x]=D.useState(""),[h,p]=D.useState({id:(l==null?void 0:l.id)||s.v4(),field:(l==null?void 0:l.field)||null,selectedValues:l?Array.isArray(l.value)?l.value:[l.value]:[]}),w=a.filter(E=>{var f;return i?!1:!((f=r==null?void 0:r.conditions)==null?void 0:f.some(j=>j.field.id===E.id))&&E.label.toLowerCase().includes(u.toLowerCase())}),m=E=>{p({...h,field:E}),o("values")},g=()=>{if(h.field&&h.selectedValues.length>0){const E={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let N;if(i){const f=((r==null?void 0:r.conditions)||[]).map(j=>j.id===l.id?E:j);N={...r,conditions:f}}else{const f=(r==null?void 0:r.conditions)||[];N={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...f,E],groups:[]}}d(N),n(!1)}},v=()=>{if(!i||!l)return;const E=((r==null?void 0:r.conditions)||[]).filter(N=>N.id!==l.id);if(E.length>0){const N={...r,conditions:E};d(N)}else d(void 0);n(!1)},C=E=>{p({...h,selectedValues:E})},A=()=>{i&&l?(p({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),o("values")):(p({id:s.v4(),field:null,selectedValues:[]}),o("fields")),x("")};return D.useEffect(()=>{t&&A()},[t,i,l]),e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:i?`Edit Filter: ${(B=h.field)==null?void 0:B.label}`:c==="fields"?"Select Field to Filter":`Select Values for ${(O=h.field)==null?void 0:O.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!i&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&c==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(E=>e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted rounded-md text-xs",children:[e.jsxs("span",{className:"font-medium",children:[E.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(E.value)?`${E.value.length} values`:String(E.value)})]},E.id))})]}),c==="fields"&&!i?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search fields...",value:u,onChange:E=>x(E.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:w.map(E=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>m(E),children:[e.jsx(We,{dataType:s.getDataType(E.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:E.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[E.entityName,".",E.name]})]})]},E.id))}),w.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),w.length===0&&!u&&a.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(na,{field:h.field,selectedValues:h.selectedValues,onValuesChange:C,onBack:i?void 0:()=>o("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:i?e.jsx(s.Button,{variant:"destructive",onClick:v,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:A,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:g,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function na({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[l,d]=D.useState(""),{values:i,isLoading:c,isFetching:o}=ta({field:t,searchQuery:l,limit:500}),u=l?i.filter(p=>String(p.value).toLowerCase().includes(l.toLowerCase())):i,x=p=>{const w=n.includes(p);a(w?n.filter(m=>m!==p):[...n,p])},h=()=>{n.length===u.length&&u.length>0?a([]):a(u.map(p=>p.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search values...",value:l,onChange:p=>d(p.target.value),className:"pl-10"})]}),c||o?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(s.Checkbox,{checked:n.length===u.length&&u.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",u.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:u.map(p=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>x(p.value),children:[e.jsx(s.Checkbox,{checked:n.includes(p.value),onCheckedChange:()=>x(p.value)}),e.jsx(Qe,{className:"text-sm",children:p.label})]},p.id))})]})]})}function Qs({open:t,onOpenChange:n,availableMetrics:a,existingField:r,onSave:l,cardId:d}){const[i,c]=D.useState(""),[o,u]=D.useState("ratio"),[x,h]=D.useState(null),[p,w]=D.useState(null),[m,g]=D.useState(1),[v,C]=D.useState(""),[A,B]=D.useState({format:"number",decimalPlaces:2}),[O,E]=D.useState({}),N=Pe.find(b=>b.id===o),f=a.find(b=>b.id===x),j=a.find(b=>b.id===p);D.useEffect(()=>{if(r&&t)if(c(r.label),r.calculatedFormula)if(u(r.calculatedFormula.operation),r.calculatedFormula.operation==="custom")C(r.expression||"");else if(r.calculatedFormula.operation==="scale"){const b=r.calculatedFormula.inputFields;if(b.length>=1){const I=a.find(F=>F.qualifiedFieldName===b[0].qualifiedFieldName);h((I==null?void 0:I.id)||null)}r.calculatedFormula.constant!==void 0&&g(r.calculatedFormula.constant)}else{const b=r.calculatedFormula.inputFields;if(b.length>=2){const I=a.find(T=>T.qualifiedFieldName===b[0].qualifiedFieldName),F=a.find(T=>T.qualifiedFieldName===b[1].qualifiedFieldName);h((I==null?void 0:I.id)||null),w((F==null?void 0:F.id)||null)}}else u("custom"),C(r.expression||"")},[r,t,a]);const S=()=>{const b={};return i.trim()||(b.name="Name is required"),o==="custom"?v.trim()||(b.customExpression="Custom expression is required"):o==="scale"?(x||(b.inputA="Please select a metric for input A"),(isNaN(m)||m===0)&&(b.constantFactor="Please enter a valid non-zero number"),r&&x===r.id&&(b.circular="Cannot reference the field being edited")):(x||(b.inputA="Please select a metric for input A"),p||(b.inputB="Please select a metric for input B"),x===p&&(b.inputs="Inputs A and B must be different metrics"),r&&(x===r.id||p===r.id)&&(b.circular="Cannot reference the field being edited")),E(b),Object.keys(b).length===0},M=()=>{if(!S())return;const b=Xn(i,o,f||null,j||null,A,d,r==null?void 0:r.id,o==="custom"?v:void 0,o==="scale"?m:void 0);l(b),y()},y=()=>{c(""),u("ratio"),h(null),w(null),g(1),C(""),E({}),n(!1)};return e.jsxs(s.Dialog,{modal:!1,open:t,onOpenChange:n,children:[t&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-w-md max-h-[90vh] overflow-y-auto",onInteractOutside:b=>{b.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsxs(s.DialogTitle,{children:[r?"Edit":"Create"," Calculated Metric"]}),e.jsx(s.DialogDescription,{children:"Combine existing metrics to create a new calculated field"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"name",children:"Name"}),e.jsx(s.Input$1,{id:"name",value:i,onChange:b=>c(b.target.value),placeholder:"e.g., Profit Margin",className:O.name?"border-red-500":""}),O.name&&e.jsx("p",{className:"text-xs text-red-500",children:O.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"operation",children:"Outcome is"}),e.jsxs(s.Select,{value:o,onValueChange:b=>{u(b),b==="custom"?(h(null),w(null)):o==="custom"&&C("")},children:[e.jsx(s.SelectTrigger,{id:"operation",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"CALCULATED"}),Pe.map(b=>e.jsx(s.SelectItem,{value:b.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm",children:b.symbol}),e.jsx("span",{children:b.label})]})},b.id))]})})]}),N&&e.jsx("p",{className:"text-xs text-muted-foreground",children:N.description})]}),o==="custom"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"customExpression",children:"SQL Expression"}),e.jsx(s.Textarea,{id:"customExpression",value:v,onChange:b=>C(b.target.value),placeholder:"e.g., CASE WHEN revenue > 1000 THEN revenue - cost ELSE 0 END",className:s.cn("font-mono text-sm",O.customExpression&&"border-red-500"),rows:4}),O.customExpression&&e.jsx("p",{className:"text-xs text-red-500",children:O.customExpression}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Write a SQL expression using column names from your data source"})]}):e.jsxs("div",{className:"rounded-md bg-muted p-3 font-mono text-sm",children:["= ",x&&f?f.label:"A"," ",N==null?void 0:N.symbol," ",p&&j?j.label:"B"]}),o!=="custom"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"inputA",children:"Where"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded bg-muted font-mono text-sm font-medium",children:"A"}),e.jsxs(s.Select,{value:x||"",onValueChange:h,children:[e.jsx(s.SelectTrigger,{id:"inputA",className:O.inputA?"border-red-500":"",children:e.jsx(s.SelectValue,{placeholder:"+ Choose metric"})}),e.jsx(s.SelectContent,{children:a.filter(b=>!s.isCalculatedMetric(b)||b.id!==(r==null?void 0:r.id)).map(b=>e.jsxs(s.SelectItem,{value:b.id,children:[b.label||b.name,b.aggregate&&` (${b.aggregate})`]},b.id))})]})]}),O.inputA&&e.jsx("p",{className:"text-xs text-red-500",children:O.inputA})]}),o!=="custom"&&o!=="scale"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded bg-muted font-mono text-sm font-medium",children:"B"}),e.jsxs(s.Select,{value:p||"",onValueChange:w,children:[e.jsx(s.SelectTrigger,{id:"inputB",className:O.inputB?"border-red-500":"",children:e.jsx(s.SelectValue,{placeholder:"+ Choose metric"})}),e.jsx(s.SelectContent,{children:a.filter(b=>!s.isCalculatedMetric(b)||b.id!==(r==null?void 0:r.id)).map(b=>e.jsxs(s.SelectItem,{value:b.id,children:[b.label||b.name,b.aggregate&&` (${b.aggregate})`]},b.id))})]})]}),O.inputB&&e.jsx("p",{className:"text-xs text-red-500",children:O.inputB})]}),o==="scale"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"constantFactor",children:"Multiplication Factor"}),e.jsx(s.Input$1,{id:"constantFactor",type:"number",step:"any",value:m,onChange:b=>g(parseFloat(b.target.value)||0),placeholder:"e.g., 0.15",className:O.constantFactor?"border-red-500":""}),O.constantFactor&&e.jsx("p",{className:"text-xs text-red-500",children:O.constantFactor}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Enter the constant value to multiply the metric by (e.g., 0.15 for 15%)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"format",children:"Format"}),e.jsxs(s.Select,{value:A.format,onValueChange:b=>B({...A,format:b}),children:[e.jsx(s.SelectTrigger,{id:"format",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsxs(s.SelectItem,{value:"number",children:["Decimal (",A.decimalPlaces,")"]}),e.jsx(s.SelectItem,{value:"currency",children:"Currency"}),e.jsx(s.SelectItem,{value:"percent",children:"Percentage"})]})]})]}),(O.inputs||O.circular)&&e.jsxs(s.Alert,{variant:"destructive",children:[e.jsx(s.CircleAlert,{className:"h-4 w-4"}),e.jsx(s.AlertDescription,{children:O.inputs||O.circular})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:y,children:"Cancel"}),e.jsxs(s.Button,{onClick:M,children:[r?"Update":"Create"," Metric"]})]})]})]})}function aa({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:d=!1,cardType:i}){var Ze,es,ss,ts,ns;const{attributes:c,listeners:o,setNodeRef:u,transform:x,transition:h,isDragging:p}=s.useSortable({id:t.id}),w=s.useEditorStore(U=>U.card),{updateLabel:m,handleAggregationChange:g,handleDateFormatChange:v,handleGranularityChange:C,handleAliasTemplateChange:A,handleValueAliasesChange:B,removeField:O,handleKpiComparisonTypeChange:E,handleKpiShowTrendlineChange:N,handleKpiTrendlineWindowChange:f,handleKpiTrendlineGranularityChange:j,handleKpiTargetValueChange:S}=s.useFieldManagement(w),[M,y]=D.useState(!1),[b,I]=D.useState(!1),[F,T]=D.useState(!1),[L,k]=D.useState(null),[R,K]=D.useState(t.dateFormat||"YYYY-MM-DD"),[_,G]=D.useState(t.customFormat||""),[q,V]=D.useState(!!t.customFormat),[z,H]=D.useState(t.granularity||"day"),[P,W]=D.useState(t.aliasTemplate||""),[Y,ee]=D.useState(t.valueAliases||{}),[J,ne]=D.useState((Ze=t.parameters)==null?void 0:Ze.filters),le=U=>{U==="custom"?V(!0):(V(!1),K(U),n==="groupBy"&&v(a,U,""))},Z=U=>{G(U),n==="groupBy"&&v(a,"custom",U)},oe=U=>{var ie;H(U);const X=(ie=s.getDateFormatOptionsForGranularity(U)[0])==null?void 0:ie.value;X&&!q&&(K(X),n==="groupBy"&&v(a,X,"")),n==="groupBy"&&C(a,U)},$=U=>{W(U),n==="metrics"&&A(a,U)},se=U=>{ee(U),n==="metrics"&&B(a,U)},de=U=>{m(n,a,U)},ue=U=>{var te;if(ne(U),n==="metrics"){const X={...t,parameters:{...t.parameters,filters:U}},ie=[...((te=w.config)==null?void 0:te.metricColumns)||[]];ie[a]=X,s.useEditorStore.getState().actions.updateCardConfig(w.id,{metricColumns:ie})}I(!1)},we=()=>{O(n,a)},me={transform:s.CSS.Transform.toString(x),transition:h},je=s.getDataType(t.dataType),xe=je==="date",be=i==="kpi",ke=s.getDateFormatOptionsForGranularity(z),fe=n!=="pivotBy",Te=xe&&n==="groupBy"&&(!be||((es=w.config)==null?void 0:es.comparisonType)==="start_vs_end"),Ee=!be&&xe&&n==="groupBy",Ae=i&&s.COMPARISON_SUPPORTED_CHART_TYPES.includes(i)&&xe&&n==="groupBy",Ie=i==="kpi"&&xe&&n==="groupBy",ve=i&&i!=="pivotTable"&&n==="metrics"&&((ss=w.config)==null?void 0:ss.comparisonType)==="target",ye=n==="metrics",Q=()=>{const U=t,te=n==="metrics"&&s.isCalculatedMetric(U);return e.jsxs("div",{className:"space-y-1",children:[!te&&e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:X=>{X.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),te&&U.calculatedFormula&&e.jsxs("div",{title:js(U.calculatedFormula),onPointerDown:X=>{X.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap rounded bg-muted/50 px-1.5 py-0.5 font-mono text-xs text-primary",children:["= ",js(U.calculatedFormula)]})]})},ae=()=>fe?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(pe,{value:t.label??"",onSave:de,placeholder:"Display label...",type:"text"})]}):null,re=()=>Te?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:z,onValueChange:oe,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(U=>e.jsx(s.SelectItem,{className:"text-xs",value:U,children:s.toTitleCase(U)},U))})]})]}):null,Ne=()=>Ee?e.jsxs(e.Fragment,{children:[re(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(s.Select,{value:q?"custom":R,onValueChange:le,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:ke.map(U=>e.jsx(s.SelectItem,{className:"text-xs",value:U.value,children:U.label},U.value))})]}),q&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:_,onChange:U=>{U.stopPropagation(),Z(U.target.value)},onClick:U=>U.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,Ws=()=>{var X,ie,Ce,Le,ge;const U=Ae,te=Ie;return!U&&!te?null:e.jsxs(e.Fragment,{children:[U&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((X=w.config)==null?void 0:X.comparisonType)||"none",onValueChange:E,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"start_vs_end",children:"Start vs End"})]})]})]}),te&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((ie=w.config)==null?void 0:ie.showTrendline)||!1,onCheckedChange:N})]})}),((Ce=w.config)==null?void 0:Ce.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input,{type:"number",min:"1",max:"365",value:((Le=w.config)==null?void 0:Le.trendlineWindow)||30,onChange:Be=>{const tt=parseInt(Be.target.value)||30;f(tt)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(s.Select,{value:((ge=w.config)==null?void 0:ge.trendlineGranularity)||"day",onValueChange:j,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]})]})},Xs=()=>{var U,te;return ve?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(pe,{value:((U=w.config)==null?void 0:U.targetValue)!==void 0&&((te=w.config)==null?void 0:te.targetValue)!==null?String(w.config.targetValue):"",onSave:X=>{!isNaN(Number(X))&&X!==null?S(Number(X)):S(0)},placeholder:"Enter target value...",type:"text"})]}):null},Zs=()=>{if(!ye)return null;const U=t,te=s.isCalculatedMetric(U);return e.jsxs(e.Fragment,{children:[te&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Formula"}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>T(!0),children:[e.jsx(s.Pencil,{className:"mr-2 h-3 w-3"}),"Edit Formula"]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:X=>{g(a,X)},disabled:te,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(J==null?void 0:J.conditions)&&J.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:J.conditions.map(X=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{k(X),I(!0)},children:[e.jsxs("span",{className:"font-medium",children:[X.field.label,":"]}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(X.value)?X.value.length===1?String(X.value[0]):X.value.length<=2?X.value.join(", "):`${X.value.slice(0,2).join(", ")} +${X.value.length-2}`:String(X.value)})}),Array.isArray(X.value)&&X.value.length>1&&e.jsx(s.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",X.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:X.value.map((ie,Ce)=>e.jsx("div",{children:String(ie)},Ce))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:ie=>{var Le;ie.stopPropagation();const Ce=J.conditions.filter(ge=>ge.id!==X.id);if(Ce.length>0){const ge={...J,conditions:Ce};ue(ge)}else if(ne(void 0),n==="metrics"){const ge={...t,parameters:{...t.parameters,filters:void 0}},Be=[...((Le=w.config)==null?void 0:Le.metricColumns)||[]];Be[a]=ge,s.useEditorStore.getState().actions.updateCardConfig(w.id,{metricColumns:Be})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},X.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{k(null),I(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(sa,{column:t}),d&&e.jsxs(e.Fragment,{children:[e.jsx(Zn,{aliasTemplate:P,onAliasTemplateChange:$}),e.jsx(ea,{valueAliases:Y,onValueAliasesChange:se})]})]})},{columns:et=[]}=s.useColumns(),st=(J==null?void 0:J.conditions)&&J.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:me,...c,...o,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${p?"z-50 scale-95 opacity-50":"border-slate-200"} ${n==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(We,{dataType:je}),e.jsx(Qe,{className:s.cn("w-[140px] flex-1 text-sm",st&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((ts=J==null?void 0:J.conditions)==null?void 0:ts.length)&&!M&&e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:J.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:J.conditions.map(U=>e.jsxs("div",{children:[U.field.label,":"," ",Array.isArray(U.value)?`${U.value.length} values`:String(U.value)]},U.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:U=>{U.stopPropagation(),y(!M)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${M?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:U=>{U.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const te=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",te),l(te)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:U=>{U.stopPropagation(),we()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),M&&e.jsxs("div",{className:"space-y-3",children:[Q(),ae(),i==="kpi"&&re(),Ne(),Ws(),Xs(),Zs()]})]}),b&&e.jsx(Js,{open:b,onOpenChange:U=>{I(U),U||k(null)},availableFields:et,existingFilters:J,editingCondition:L,onSave:U=>{var te;if(U)ue(U);else if(ne(void 0),n==="metrics"){const X={...t,parameters:{...t.parameters,filters:void 0}},ie=[...((te=w.config)==null?void 0:te.metricColumns)||[]];ie[a]=X,s.useEditorStore.getState().actions.updateCardConfig(w.id,{metricColumns:ie})}k(null)}}),F&&n==="metrics"&&e.jsx(Qs,{open:F,onOpenChange:T,availableMetrics:((ns=w.config)==null?void 0:ns.metricColumns)||[],existingField:t,onSave:U=>{var X;const te=[...((X=w.config)==null?void 0:X.metricColumns)||[]];te[a]=U,s.useEditorStore.getState().actions.updateCardConfig(w.id,{metricColumns:te})},cardId:w.id})]})}function ra({concept:t}){const n=()=>{switch(t){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:"Pivot 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:"Metric 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(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:n()})]})})}function Re({zone:t,fields:n,label:a,placeholder:r,shouldShow:l,hasPivotColumns:d=!1,activeField:i=null}){const{isOver:c,setNodeRef:o}=s.useDroppable({id:t}),{updateSortByColumn:u}=s.useEditorActions(),x=s.useEditorStore(v=>v.card),h=s.useEditorStore(v=>v.card.type),p=n.length>0,w=D.useMemo(()=>!i||!c?!0:s.validateFieldForChartType(i,t,h).isValid,[i,c,t,h]),m=(v,C)=>{var B;!((B=x.config)!=null&&B.sortByColumns)||x.config.sortByColumns.findIndex(O=>O.id===v)===-1||u(x.id,v,{direction:C})};if(t==="sortBy"&&l===!1)return null;const g=t!=="sortBy"&&h!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:a}),g&&e.jsx(ra,{concept:t})]}),e.jsx("div",{ref:o,className:s.cn("rounded-lg border-2 border-dotted p-0.5 transition-all",{"border-green-500 bg-green-50 dark:bg-green-950":c&&w,"border-red-500 bg-red-50 dark:bg-red-950":c&&!w,"border-muted-foreground/30 bg-muted/40":!c&&p,"min-h-[60px] border-muted-foreground/20 bg-background":!c&&!p}),children:n.length===0?e.jsx("div",{className:"flex min-h-[60px] items-center justify-center text-sm text-muted-foreground/60",children:r}):e.jsx(s.SortableContext,{items:n.map(v=>v.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((v,C)=>{const B=v.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(aa,{field:v,zone:t,index:C,sortDirection:B,onSortDirectionChange:O=>m(v.id,O),hasPivotColumns:d,cardType:h})})},v.id)})})})})]})}const bs={difference:{label:"Difference",description:"Shows the exact difference between two values.",formula:"Primary - Secondary",example:"Sales increased by $5,000 compared to last year."},change:{label:"Change",description:"Shows the percentage increase or decrease between two values.",formula:"(Primary - Secondary) / Secondary × 100%",example:"Year-over-year sales change of 25%."},change_difference:{label:"Change (difference)",description:"Shows both the percentage change and the exact difference between two values.",formula:`% Change: (Primary - Secondary) / Secondary × 100%
200
+ Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function la(){var p,w,m,g,v,C,A,B,O,E,N;const t=s.useEditorStore(f=>f.card),{setCardPreferences:n}=s.useEditorActions(),a=((p=t.config)==null?void 0:p.metricColumns)||[],r=((w=t.config)==null?void 0:w.groupByColumns)||[],l=a.length===2&&r.length===0,d=a.length>=1&&r.length>0;if(!(t.type==="kpi"&&(l||d)))return null;const c=((g=(m=t.preferences)==null?void 0:m.kpiVisualOptions)==null?void 0:g.metricComparison)||{},o=f=>{var S;const j={...t.preferences,kpiVisualOptions:{...(S=t.preferences)==null?void 0:S.kpiVisualOptions,metricComparison:{...c,...f}}};n(j)},u=d||c.enabled,x=((v=t.config)==null?void 0:v.comparisonType)||"none",h=x==="previous_period"||x==="same_period_last_year"||x==="start_vs_end";return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pt,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[l&&a.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:c.enabled||!1,onCheckedChange:f=>o({enabled:f,...f&&!c.calculationType?{calculationType:"difference"}:{}})})]}),u&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const f=c.calculationType||"difference",j=bs[f];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:j==null?void 0:j.label}),e.jsx("p",{children:j==null?void 0:j.description}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-[10px]",children:j==null?void 0:j.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",j==null?void 0:j.example]})]})})()})]})]}),e.jsxs(s.Select,{value:c.calculationType||"difference",onValueChange:f=>o({calculationType:f}),children:[e.jsx(s.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Object.entries(bs).map(([f,j])=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:j.label},f))})]})]}),e.jsx(Ye,{formatOptions:c.formatOptions||{},onFormatOptionsChange:f=>o({formatOptions:f}),showTitle:!0,title:"COMPARISON FORMAT"}),(h||l)&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),l&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:c.position||"right",onValueChange:f=>o({position:f}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:c.showArrow!==!1,onCheckedChange:f=>o({showArrow:f})}),e.jsx(s.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-color",checked:c.showColor!==!1,onCheckedChange:f=>o({showColor:f})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),c.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Fe,{value:((C=c.colorConfig)==null?void 0:C.increase)||"green",onChange:f=>o({colorConfig:{...c.colorConfig,increase:f}}),label:"Primary > Secondary"}),e.jsx(Fe,{value:((A=c.colorConfig)==null?void 0:A.decrease)||"red",onChange:f=>o({colorConfig:{...c.colorConfig,decrease:f}}),label:"Primary < Secondary"}),e.jsx(Fe,{value:((B=c.colorConfig)==null?void 0:B.noChange)||"neutral",onChange:f=>o({colorConfig:{...c.colorConfig,noChange:f}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"conditional-label",checked:c.conditionalLabel||!1,onCheckedChange:f=>o({conditionalLabel:f})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),c.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input$1,{id:"label-increase",type:"text",value:((O=c.conditionalLabels)==null?void 0:O.increase)??"Increase",onChange:f=>o({conditionalLabels:{...c.conditionalLabels,increase:f.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(s.Input$1,{id:"label-decrease",type:"text",value:((E=c.conditionalLabels)==null?void 0:E.decrease)??"Decrease",onChange:f=>o({conditionalLabels:{...c.conditionalLabels,decrease:f.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(s.Input$1,{id:"label-no-change",type:"text",value:((N=c.conditionalLabels)==null?void 0:N.noChange)??"No change",onChange:f=>o({conditionalLabels:{...c.conditionalLabels,noChange:f.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Previous Label"}),e.jsx(s.Input$1,{id:"label-name",type:"text",value:c.labelName??"",onChange:f=>o({labelName:f.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function oa(){var l,d;const t=s.useEditorStore(i=>i.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((d=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:d.formatOptions)||{},r=i=>{var o;const c={...t.preferences,kpiVisualOptions:{...(o=t.preferences)==null?void 0:o.kpiVisualOptions,formatOptions:i}};n(c)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Hash,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(Ye,{formatOptions:a,onFormatOptionsChange:r,showTitle:!1})})]})}function ia(){var d;const t=s.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.type}),n=s.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.preferences}),{setCardPreferences:a}=s.useEditorActions();if(t!=="treemap")return null;const r=((d=n==null?void 0:n.chartOptions)==null?void 0:d.treemapColorMode)??"branch",l=i=>{const c={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,treemapColorMode:i}};a(c)};return e.jsxs(s.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(s.RadioGroup,{value:r,onValueChange:i=>l(i??"branch"),className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:"treemap-color-branch",value:"branch"}),e.jsxs(s.Label,{htmlFor:"treemap-color-branch",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Shade by value (default)"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Keeps parent hue and adjusts lightness based on the node's share within the branch."})]})]}),e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:"treemap-color-category",value:"category"}),e.jsxs(s.Label,{htmlFor:"treemap-color-category",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Single color per category"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Applies the top-level color to all descendants without lightening/darkening."})]})]})]})})]})}function ca({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r,activeField:l}){const[d,i]=D.useState(!1),c=s.useEditorStore(B=>{var O;return((O=B.card.customCardPreferences)==null?void 0:O.url)&&B.card.type==="custom"}),o=s.useEditorStore(B=>B.card),u=s.useEditorStore(B=>B.actions.updateCardConfig),x=o==null?void 0:o.type,h=t.length>0||a.length>0,p=x!=="kpi"||a.length<=2,w=x!=="kpi",m=x!=="kpi"&&h,g=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(x),v=w&&!g,C=()=>x==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},A=()=>x==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Columns",placeholder:"Drop fields to measure"};return e.jsxs(e.Fragment,{children:[e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.List,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[p&&e.jsx(Re,{zone:"groupBy",fields:t,label:C().label,placeholder:C().placeholder,activeField:l}),v&&e.jsx(Re,{zone:"pivotBy",fields:n,label:"Pivot Columns",placeholder:"Drop fields to pivot data",activeField:l}),e.jsx(Re,{zone:"metrics",fields:a,label:A().label,placeholder:A().placeholder,hasPivotColumns:n.length>0,activeField:l}),a.length>=1&&e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:()=>i(!0),className:"mt-2 w-full justify-start text-xs text-muted-foreground hover:text-foreground",children:[e.jsx(s.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),m&&e.jsx(Re,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics",activeField:l})]})]}),!c&&e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings2,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(oa,{}),e.jsx(la,{}),e.jsx(zs,{}),e.jsx(ia,{}),e.jsx(Us,{}),x==="bullet"&&e.jsx(qs,{}),x==="funnel"&&e.jsx(Hs,{}),(x==="bubble"||x==="scatter")&&e.jsx(_s,{}),e.jsx($s,{}),e.jsx(Ks,{}),e.jsx(Gs,{})]})})]}),c&&e.jsxs(s.AccordionItem,{value:"plugin",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ns,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsx(Fs,{})})]})]}),e.jsx(Qs,{open:d,onOpenChange:i,availableMetrics:a,onSave:B=>{u(o.id,{metricColumns:[...a,B]})},cardId:o.id})]})}function da({onEditJoins:t}){const n=s.useEditorStore(c=>c.card),{autoJoinMetadata:a}=s.useDashboardCardQuery(n);if(!(a!=null&&a.autoResolved))return null;const{resolvedJoinPlan:r}=a,l=(r==null?void 0:r.joins)||[];if(l.length===0)return null;const d=c=>!c||c.length===0?"No conditions":c.map(o=>{var p,w,m,g;const u=`${(p=o.source)==null?void 0:p.entityName}.${(w=o.source)==null?void 0:w.name}`,x=`${(m=o.target)==null?void 0:m.entityName}.${(g=o.target)==null?void 0:g.name}`,h=o.operator||"=";return`${u} ${h} ${x}`}).join(" AND "),i=c=>!c.joinKeyGroups||c.joinKeyGroups.length===0?"No conditions defined":c.joinKeyGroups.length===1?d(c.joinKeyGroups[0].keys):c.joinKeyGroups.map((o,u)=>({id:u,operator:o.operator,condition:d(o.keys)}));return e.jsx(s.Card,{className:"border-blue-500/30 bg-blue-50/30 dark:bg-blue-950/20",children:e.jsxs("div",{className:"flex items-center justify-between p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dt,{className:"size-4 text-blue-600 dark:text-blue-400"}),e.jsx("h3",{className:"text-sm font-medium text-blue-900 dark:text-blue-100",children:"Auto-Resolved Joins"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"secondary",className:"cursor-help bg-blue-100 text-xs text-blue-700 dark:bg-blue-900 dark:text-blue-300",children:l.length})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:l.map((c,o)=>{const u=i(c),x=Array.isArray(u);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children:c.source.name}),e.jsx(s.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:c.target.name})]}),e.jsx(s.Badge,{variant:"outline",className:"border-green-500/40 bg-green-50/30 text-xs text-green-700 dark:bg-green-950/30 dark:text-green-300",children:c.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:x?u.map(h=>e.jsxs("div",{className:"rounded bg-muted/30 px-2 py-1",children:[e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:h.condition}),h.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",h.operator,")"]})]},h.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:u})})})]},c.id||o)})})})]})})]}),t&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:t,className:"h-7 gap-1 p-2 text-xs text-blue-700 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-100",children:e.jsx(s.SquarePen,{className:"size-3.5"})})]})})}const vs={getItem(t){if(typeof window>"u")return null;try{return localStorage.getItem(t)}catch(n){return console.warn(`Failed to read from localStorage (${t}):`,n),null}},setItem(t,n){if(!(typeof window>"u"))try{localStorage.setItem(t,n)}catch(a){console.warn(`Failed to write to localStorage (${t}):`,a)}}};function ua({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:d,activeField:i}){var f,j;const[c,o]=D.useState(()=>vs.getItem("chart-selector-expanded")==="true"),[u,x]=D.useState(!1),h=s.useEditorStore(S=>S.card),p=s.useEditorStore(S=>S.actions.updateCardConfig),w=a.length>0||r.length>0||l.length>0,{data:m,autoJoinMetadata:g}=s.useDashboardCardQuery(h),v=((f=h==null?void 0:h.config)==null?void 0:f.joinPlan)||(g!=null&&g.autoResolved?g.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),C=((j=h==null?void 0:h.dataSource)==null?void 0:j.selectedEntities)||[],A=S=>{p(h.id,{...h==null?void 0:h.config,joinPlan:S}),x(!1)},B=()=>{p(h.id,{...h==null?void 0:h.config,joinPlan:void 0}),x(!1)},O=()=>{x(!1)},E=()=>{x(!0)};D.useEffect(()=>{vs.setItem("chart-selector-expanded",String(c))},[c]);const N=()=>{o(S=>!S)};return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col border-x border-border",children:[e.jsxs("div",{className:s.cn("px-6 pt-4",{"space-y-4":c}),children:[e.jsx("div",{className:s.cn("overflow-hidden transition-all duration-300 ease-in-out",c?"max-h-[200px] opacity-100":"max-h-0 opacity-0"),children:c&&e.jsx(Hn,{selectedChart:t,onChartChange:n})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:"flex items-center justify-center",children:e.jsx(Yn,{selectedChart:t,onChartChange:n,isDropdownExpanded:c,onToggleDropdown:N})})]}),e.jsx("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:e.jsx("div",{className:s.cn("invisible flex gap-2",{visible:w||m}),children:e.jsx(_e.EditorClearButton,{})})}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx(da,{onEditJoins:E}),e.jsx(ca,{groupByFields:a,pivotByFields:r,metricsFields:l,sortByFields:d,activeField:i})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]}),e.jsx(Ts,{open:u,onOpenChange:x,joinPlan:v,availableDataSources:C,onSave:A,onCancel:O,onRemove:B,children:e.jsx("div",{})})]})}function ma({initialFilters:t,availableFields:n}={}){const[a,r]=D.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(E=>E.card.dataSource);const{columns:l,isLoading:d}=s.useColumns(),c=n||l||[],o={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=E=>{const N=f=>{if(f.id===E){const j=c[0]||o,S=s.getDataType(j.dataType)==="date";return{...f,conditions:[...f.conditions,{id:`condition-${Date.now()}`,field:j,operator:S?"between":"=",value:S?[]:""}]}}return{...f,groups:f.groups.map(N)}};r(N(a))},x=E=>{const N=f=>{if(f.id===E){const j=c[0]||o,S=s.getDataType(j.dataType)==="date";return{...f,groups:[...f.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:j,operator:S?"between":"=",value:S?[]:""}],groups:[]}]}}return{...f,groups:f.groups.map(N)}};r(N(a))},h=(E,N)=>{const f=j=>j.id===E?{...j,conditions:j.conditions.filter(S=>S.id!==N)}:{...j,groups:j.groups.map(f)};r(f(a))},p=(E,N)=>{const f=j=>j.id===E?{...j,groups:j.groups.filter(S=>S.id!==N)}:{...j,groups:j.groups.map(f)};r(f(a))},w=(E,N,f,j)=>{if(f==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const S=M=>M.id===E?{...M,conditions:M.conditions.map(y=>y.id===N?{...y,[f]:j}:y)}:{...M,groups:M.groups.map(S)};r(S(a))},m=(E,N,f)=>{const j=S=>S.id===E?{...S,conditions:S.conditions.map(M=>M.id===N?{...M,...f}:M)}:{...S,groups:S.groups.map(j)};r(j(a))},g=(E,N)=>{const f=j=>j.id===E?{...j,logicalOperator:N}:{...j,groups:j.groups.map(f)};r(f(a))},v=(E,N)=>{const f=j=>j.id===E?{...j,negate:N}:{...j,groups:j.groups.map(f)};r(f(a))},C=(E,N,f)=>{const j=S=>S.id===E?{...S,conditions:s.arrayMove(S.conditions,N,f)}:{...S,groups:S.groups.map(j)};r(j(a))},A=(E,N,f)=>{const j=S=>S.id===E?{...S,groups:s.arrayMove(S.groups,N,f)}:{...S,groups:S.groups.map(j)};r(j(a))},B=E=>{if(!E||E.conditions.length===0&&E.groups.length===0)return"-- No filters defined";const N=j=>{let S="";typeof j.field=="object"?S=j.field.entityName?`${j.field.entityName}.${j.field.name}`:j.field.name:S=String(j.field);const M=j.operator;let y=j.value;if(j.field.dataType==="string"&&!["in","not in"].includes(j.operator))typeof y=="string"?y=`'${y}'`:Array.isArray(y)&&(y=`'${y.join(", ")}'`);else if(j.field.dataType==="date"||j.field.dataType==="datetime"||j.field.dataType==="timestamp")if(j.operator==="between"&&Array.isArray(y)&&y.length===2){const b=y[0]?`'${y[0]}'`:"NULL",I=y[1]?`'${y[1]}'`:"NULL";return`${S} BETWEEN ${b} AND ${I}`}else if((j.operator==="in"||j.operator==="not in")&&Array.isArray(y)){const b=y.map(I=>I?`'${I}'`:"NULL").join(", ");return`${S} ${M} (${b})`}else typeof y=="string"||y instanceof Date?y=`'${y}'`:Array.isArray(y)&&y.length>0&&(y=`'${y[0]}'`);else if(["in","not in"].includes(j.operator)){let b=[];Array.isArray(y)?b=y.map(I=>typeof I=="string"?`'${I}'`:String(I)):typeof y=="string"?b=y.split(",").map(I=>{const F=I.trim();return j.field.dataType==="string"?`'${F}'`:F}):typeof y=="number"&&(b=[String(y)]),y=`(${b.join(", ")})`}switch(M){case"contains":return typeof y=="string"?`${S} LIKE '%${y.replace(/'/g,"")}'`:`${S} LIKE '%${String(y)}'`;case"startsWith":return typeof y=="string"?`${S} LIKE '${y.replace(/'/g,"")}%'`:`${S} LIKE '${String(y)}%'`;case"endsWith":return typeof y=="string"?`${S} LIKE '%${y.replace(/'/g,"")}'`:`${S} LIKE '%${String(y)}'`;case"isNull":return`${S} IS NULL`;case"isNotNull":return`${S} IS NOT NULL`;default:return`${S} ${M} ${y}`}},f=j=>{const S=j.conditions.map(N),M=j.groups.map(F=>f(F)),y=[...S,...M].filter(Boolean);if(y.length===0)return"";const b=y.join(` ${j.logicalOperator} `),I=y.length>1?`(${b})`:b;return j.negate?`NOT ${I}`:I};return f(E)},O=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:c,isLoading:d,addCondition:u,addGroup:x,removeCondition:h,removeGroup:p,updateCondition:w,updateConditionFields:m,updateGroupOperator:g,updateGroupNegate:v,reorderConditions:C,reorderGroups:A,generateSQLPreview:B,hasAnyFilters:O}}function xa({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const ha=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function pa({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:l="w-64"}){const[d,i]=D.useState(!1),c=D.useMemo(()=>{const o={};return a.forEach(u=>{const x=ha(u);o[x]||(o[x]={}),o[x][u.entityId]||(o[x][u.entityId]=[]),o[x][u.entityId].push(u)}),o},[a]);return e.jsxs(s.Popover,{modal:!0,open:d,onOpenChange:i,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":d,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(xa,{children:[t.entityName,".",t.name]})}):r,e.jsx(dt,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(c).map(([o,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),o]}),children:Object.entries(u).map(([x,h])=>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:[s.getEntityIcon(h[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:h[0].entityName})]}),h.map((p,w)=>e.jsxs(s.CommandItem,{value:p.id,onSelect:()=>{n(p),i(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===p.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:p.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:p.description&&e.jsx("span",{children:p.description})})]})]},p.id+w))]},`${o}-${x}`))},o))})]})})]})}function Xe(t){var g;const n=s.useEditorStore(v=>v.card),{authToken:a,tokenProps:r}=s.useSemaphorContext(),l=s.useEditorStore(v=>v.card.config),d=l==null?void 0:l.joinPlan,i={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},o={...i,role:"sortby",direction:"asc"},u={joinPlan:d,groupByColumns:[i],metricColumns:[c],sortByColumns:[o]},x=((g=n.dataSource)==null?void 0:g.connectionId)||n.connectionId,{data:h,isPending:p,error:w}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(a==null?void 0:a.accessToken)||"",{connection_id:x,cardConfig:u,cardDataSource:n.dataSource})}catch(v){console.log(t),console.error("error",v)}},enabled:!!x,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(v=>({label:v.value||"BLANK",value:v.value||"BLANK",count:(v==null?void 0:v.count)||0})),isPending:p,error:w}}function fa({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:l}){const[d,i]=qe.useState(!1),{filterValues:c}=Xe(t),o=x=>{a(n.filter(h=>h!==x))},u=x=>{n.includes(x)?a(n.filter(h=>h!==x)):a([...n,x])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:d,onOpenChange:i,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":d,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:n.length>0?n.map(x=>{const h=c.find(p=>p.value===x);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.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:p=>{p.key==="Enter"&&o(x)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.stopPropagation(),o(x)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},x)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:c.map((x,h)=>e.jsxs(s.CommandItem,{onSelect:()=>u(x.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.includes(x.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:x.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x.count})]})]},x.value+h))})]})]})})]})})}function ga({field:t,value:n,onChange:a,placeholder:r="Select value...",className:l}){const{filterValues:d,isPending:i,error:c}=Xe(t);return i?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):c?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:n,onValueChange:a,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:d.map((o,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:o.value,children:o.label},o.value+u))})]})}function ja({value:t,operator:n,onChange:a,className:r}){var o;const{tokenProps:l}=s.useSemaphorContext(),d=(o=l==null?void 0:l.params)==null?void 0:o.timezone,i=D.useMemo(()=>{if(t){if(n==="between"||n==="not between"){if(Array.isArray(t)&&t.length===2){const u=t[0]?new Date(t[0]):void 0,x=t[1]?new Date(t[1]):void 0;if(u&&x)return{from:u,to:x}}}else if(n==="="||n==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(n===">"||n===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(n==="<"||n==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((n==="in"||n==="not in")&&Array.isArray(t)&&t.length>0){const u=new Date(t[0]),x=t.length>1?new Date(t[t.length-1]):u;if(!isNaN(u.getTime()))return{from:u,to:x}}}},[t,n]),c=u=>{if(!u){a(void 0);return}if(u.from&&u.to)a([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const x=new Date(u.from);x.setHours(23,59,59,999),a([u.from.toISOString(),x.toISOString()])}else if(u.to){const x=new Date(u.to);x.setHours(0,0,0,0),a([x.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:i,onChange:c,timezone:d,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const ba=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],va=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],ya=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Na=["=","!=","isNull","isNotNull"],Ca=["between","isNull","isNotNull"],Sa={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null","not between":"Not Between"};function ys(t){return Sa[t]||s.titleCase(t)}function wa(t){switch(t){case"string":return va;case"number":return ya;case"boolean":return Na;case"date":return Ca;default:return ba}}function Ys({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:d,onUpdateGroupOperator:i,availableFields:c,updateConditionFields:o}){const{attributes:u,listeners:x,setNodeRef:h,transform:p,transition:w,isDragging:m}=s.useSortable({id:t.id}),{isPending:g,error:v}=Xe(t.field),C={transform:s.CSS.Transform.toString(p),transition:w};return e.jsxs("div",{ref:h,style:C,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${m?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...x,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(s.Select,{value:r,onValueChange:A=>i(a,A),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx(pa,{value:t.field,onValueChange:A=>{const B=A,O=s.getDataType(B.dataType)==="date";o(a,t.id,{field:B,value:"",operator:O?"between":"="})},availableFields:c,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:A=>{A==="in"||A==="not in"?o(a,t.id,{operator:A,value:[]}):A==="isNull"||A==="isNotNull"?o(a,t.id,{operator:A,value:null}):o(a,t.id,{operator:A,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?ys(t.operator):""})}),e.jsx(s.SelectContent,{children:wa(s.getDataType(t.field.dataType)).map(A=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:A,children:ys(A)},A))})]}),t.operator==="isNull"||t.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?g?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):v?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(fa,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(A=>typeof A=="string")?t.value:[],onChange:A=>o(a,t.id,{value:A}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input,{value:typeof t.value=="string"?t.value:"",onChange:A=>o(a,t.id,{value:A.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(ga,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:A=>o(a,t.id,{value:A}),placeholder:"Select value...",className:"flex-1"}):s.getDataType(t.field.dataType)==="boolean"?e.jsxs(s.Select,{value:typeof t.value=="boolean"?String(t.value):"",onValueChange:A=>o(a,t.id,{value:A==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):s.getDataType(t.field.dataType)==="date"?e.jsx(ja,{value:t.value,operator:t.operator,onChange:A=>o(a,t.id,{value:A}),className:"flex-1"}):e.jsx(s.Input,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:A=>l(a,t.id,"value",A.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>d(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function ka({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:d,onUpdateCondition:i,onUpdateField:c,onRemoveCondition:o,onReorderConditions:u,onReorderGroups:x,onAddCondition:h,onAddGroup:p,availableFields:w,renderFilterGroup:m,updateConditionFields:g}){const{attributes:v,listeners:C,setNodeRef:A,transform:B,transition:O,isDragging:E}=s.useSortable({id:t.id}),N={transform:s.CSS.Transform.toString(B),transition:O},f=S=>{const{active:M,over:y}=S;if(y&&M.id!==y.id){const b=t.conditions.findIndex(F=>F.id===M.id),I=t.conditions.findIndex(F=>F.id===y.id);b!==-1&&I!==-1&&u(t.id,b,I)}},j=S=>{const{active:M,over:y}=S;if(y&&M.id!==y.id&&a){const b=t.groups.findIndex(F=>F.id===M.id),I=t.groups.findIndex(F=>F.id===y.id);b!==-1&&I!==-1&&x(a,b,I)}};return e.jsxs("div",{ref:A,style:N,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${E?"z-50 opacity-50":""}`,children:[n>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",{...v,...C,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>l(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:S=>r(t.id,S),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>a&&d(a,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:f,children:e.jsx(s.SortableContext,{items:t.conditions.map(S=>S.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((S,M)=>e.jsx(Ys,{condition:S,index:M,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:i,onUpdateField:c,onRemoveCondition:o,onUpdateGroupOperator:r,availableFields:w,updateConditionFields:g},S.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:j,children:e.jsx(s.SortableContext,{items:t.groups.map(S=>S.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(S=>m(S,n+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>p(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Ta({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:l}){const{currentFilters:d,availableFields:i,isLoading:c,addCondition:o,addGroup:u,removeCondition:x,removeGroup:h,updateCondition:p,updateConditionFields:w,updateGroupOperator:m,updateGroupNegate:g,reorderConditions:v,reorderGroups:C,generateSQLPreview:A,hasAnyFilters:B,setCurrentFilters:O}=ma({initialFilters:t,availableFields:n}),E=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[N,f]=D.useState(!1),j=(y,b,I)=>{const F=T=>T.id===y?{...T,conditions:T.conditions.map(L=>L.id===b?{...L,field:I,dataType:I.dataType}:L)}:{...T,groups:T.groups.map(F)};O(F(d))},S=(y,b=0,I)=>b===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:F=>{const{active:T,over:L}=F;if(L&&T.id!==L.id){const k=y.conditions.findIndex(K=>K.id===T.id),R=y.conditions.findIndex(K=>K.id===L.id);k!==-1&&R!==-1&&v(y.id,k,R)}},children:e.jsx(s.SortableContext,{items:y.conditions.map(F=>F.id),strategy:s.verticalListSortingStrategy,children:y.conditions.map((F,T)=>e.jsx(Ys,{condition:F,index:T,groupId:y.id,groupLogicalOperator:y.logicalOperator,onUpdateCondition:p,onUpdateField:j,onRemoveCondition:x,onUpdateGroupOperator:m,availableFields:i,updateConditionFields:w},F.id))})}),e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:F=>{const{active:T,over:L}=F;if(L&&T.id!==L.id){const k=y.groups.findIndex(K=>K.id===T.id),R=y.groups.findIndex(K=>K.id===L.id);k!==-1&&R!==-1&&C(y.id,k,R)}},children:e.jsx(s.SortableContext,{items:y.groups.map(F=>F.id),strategy:s.verticalListSortingStrategy,children:y.groups.map(F=>S(F,b+1,y.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>o(y.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),N&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(y.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},y.id):e.jsx(ka,{group:y,depth:b,parentGroupId:I,onUpdateGroupOperator:m,onUpdateGroupNegate:g,onRemoveGroup:h,onUpdateCondition:p,onUpdateField:j,onRemoveCondition:x,onReorderConditions:v,onReorderGroups:C,onAddCondition:o,onAddGroup:u,availableFields:i,renderFilterGroup:S,updateConditionFields:w},y.id),M=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[c?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..."})]}):S(d),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(s.SmallSwitch,{id:"advanced-mode",checked:N,onCheckedChange:y=>f(y)}),e.jsx(s.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)"})]})}),B&&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:A(d)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),M>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(B?d:null),children:"Apply Filters"})]})]})}function Ea({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:l,isOpen:d,onOpenChange:i}){const c=u=>{a(t,u),i(!1)},o=()=>{r(t),i(!1)};return e.jsxs(s.Dialog,{modal:!1,open:d,onOpenChange:i,children:[d&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Ta,{filters:n,availableFields:l,onSave:c,onCancel:()=>i(!1),onClearAll:o})]})]})}function Aa({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var v,C;const[l,d]=D.useState(null),i=s.useEditorStore(A=>A.card),c=s.useEditorStore(A=>A.actions.updateCardConfig),o=(v=i==null?void 0:i.config)==null?void 0:v.joinPlan,u=(C=i==null?void 0:i.dataSource)==null?void 0:C.semanticDomainId,{data:x}=s.useJoinabilityMap(u),h=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")],p=D.useCallback(A=>A.startsWith("card-")?null:A.startsWith("source-")||n.find(B=>B.id===A)?"source":a("groupBy").find(B=>B.id===A)?"groupBy":a("metrics").find(B=>B.id===A)?"metrics":a("pivotBy").find(B=>B.id===A)?"pivotBy":a("sortBy").find(B=>B.id===A)?"sortBy":null,[n,a]),w=D.useCallback(A=>{d(A.active.id)},[]),m=D.useCallback(A=>{var S;const{active:B,over:O}=A;if(!O||!t){d(null);return}const E=B.id,N=O.id,f=p(E),j=p(N)||N;if(j==="sortBy"){if(f==="source"){const M=n.find(b=>b.id===E);if(!M){d(null);return}if(!(a("groupBy").some(b=>b.name===M.name&&b.qualifiedEntityName===M.qualifiedEntityName)||a("metrics").some(b=>b.name===M.name&&b.qualifiedEntityName===M.qualifiedEntityName))){d(null);return}}else if(f==="pivotBy"){d(null);return}else if(f!=="groupBy"&&f!=="metrics"&&f!=="sortBy"){d(null);return}}if(f==="source"&&j==="sortBy"){const M=[...n].find(F=>F.id===E);if(!M){d(null);return}const y=a("sortBy");if(s.fieldAlreadyExists(M,y)){d(null);return}const b=s.validateFieldForChartType(M,"sortBy",i.type);if(!b.isValid){s.ue.error("Invalid Field Type",{description:b.reason,position:"top-center",duration:3e3}),d(null);return}const I=s.getNewField(M,"sortBy",y);d(null),r("sortBy",[...y,I]);return}if(f==="source"&&j!=="source"&&j!=="sortBy"){const M=[...n].find(L=>L.id===E);if(!M){d(null);return}const y=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(y.length>0){const L=y[0].qualifiedEntityName;if(!L){d(null);return}if(L!==M.qualifiedEntityName&&M.qualifiedEntityName)if(u&&(x!=null&&x.joinabilityMap)){if(s.calculateFieldState(M,{joinabilityMap:x.joinabilityMap,selectedFields:y,baseEntityName:(S=o==null?void 0:o.baseEntity)==null?void 0:S.name}).state==="unreachable"){s.showJoinRequiredNotification(),d(null);return}}else{if(!o){s.showJoinRequiredNotification(),d(null);return}if(!s.areEntitiesJoined(L,M.qualifiedEntityName,o)){s.showJoinRequiredNotification(),d(null);return}}}const b=a(j);if(s.fieldAlreadyExists(M,b)){d(null);return}const I=s.validateFieldForChartType(M,j,i.type);if(!I.isValid){s.ue.error("Invalid Field Type",{description:I.reason,position:"top-center",duration:3e3}),d(null);return}const F=s.getNewField(M,j,b),T=[...b,F];d(null),r(j,T),j==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(i.type,i.config,c,t,T);return}if(f&&j&&f!=="source"&&j!=="source"&&f!==j){const M=a(f),y=a(j),b=M.find(k=>k.id===E);if(!b){d(null);return}const I=s.validateFieldForChartType(b,j,i.type);if(!I.isValid){s.ue.error("Invalid Field Type",{description:I.reason,position:"top-center",duration:3e3}),d(null);return}const F=s.getNewField(b,j,y);if(d(null),j==="sortBy"){s.fieldAlreadyExists(b,y)||r(j,[...y,F]);return}const T=M.filter(k=>k.id!==E),L=[...y,F];r(f,T),r(j,L),j==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(i.type,i.config,c,t,L);return}if(f&&j&&f===j&&f!=="source"){const M=a(f),y=M.findIndex(I=>I.id===E),b=M.findIndex(I=>I.id===N);if(y!==b){const I=s.arrayMove(M,y,b);r(f,I)}}d(null)},[t,n,a,r,p,o,u,x,i.type,c,i.config]),g=l?h.find(A=>A.id===l):null;return{activeId:l,activeField:g,handleDragStart:w,handleDragEnd:m}}function Ia({activeView:t,onViewChange:n,splitViewEnabled:a}){const r=s.useEditorStore(o=>o.card),{config:l}=D.useContext(s.SemaphorContext).tokenProps,d=(l==null?void 0:l.showInfoTab)!==!1,{errorMessage:i}=s.useDashboardCardQuery(r),c=()=>a?!1:!["table","pivotTable","aggregateTable"].includes(r.type);return e.jsx(s.Tabs,{value:t,onValueChange:o=>n(o),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),c()&&e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),r.type!=="kpi"&&d&&e.jsx(s.TabsTrigger,{value:"info",className:s.cn("rounded-md transition data-[state=active]:bg-muted",i&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:i?"Error":"Info"})]})})}const Da=[{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 Ma(){var o,u;const t=s.useEditorStore(x=>x.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=D.useState(!1),[l,d]=D.useState(""),i=x=>{if(x==="custom"){r(!0);return}r(!1),n(t.id,parseInt(x))},c=x=>{const h=x.target.value;d(h),h&&!isNaN(parseInt(h))&&n(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(s.Input$1,{type:"number",value:l,onChange:c,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(o=t.config)==null?void 0:o.rowLimit)==null?void 0:u.toString())||"100",onValueChange:i,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:Da.map(x=>e.jsx(s.SelectItem,{value:x.value,children:x.label},x.value))})]})})}function La({card:t,queryData:n,isLoading:a,isFetching:r,pagination:l,onPaginationChange:d,onSortChange:i,sortState:c,splitViewEnabled:o}){const u=D.useMemo(()=>(n==null?void 0:n.records)||[],[n==null?void 0:n.records]);return!o||["table","pivotTable","aggregateTable"].includes(t.type)?e.jsx(Ue,{}):e.jsxs(s.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(s.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:e.jsx(Ue,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:(n==null?void 0:n.records)&&e.jsx(s.TableVisual,{card:t,data:u,paginationMetadata:l,onPaginationChange:d,isLoading:a||r,onSortChange:i,sortState:c})})})]})}const Fa="semaphor-split-view-enabled";function Ba(){return Ve(Fa,!0)}function Oa({isOpen:t,onClose:n}){const a=rt.useClickOutside(n,{enabled:t}),r=s.useEditorStore(x=>{var h;return((h=x.card.customCardPreferences)==null?void 0:h.url)||""}),l=s.useEditorStore(x=>x.card),d=s.useEditorStore(x=>{var h;return((h=x.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),i=s.useEditorStore(x=>{var h;return((h=x.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:c}=s.useDashboardCardQuery(l),{getCard:o}=s.useCustomVisual(r),u=D.useMemo(()=>!r||r.trim()===""?null:o("Chart Settings"),[o,r]);return e.jsx("div",{ref:a,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:n,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(D.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(c==null?void 0:c.records)||[],chartType:d,settings:i})})})]})})}function Ra({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onFiltersClick:l,activeCard:d,columns:i,columnsLoading:c,columnsError:o}){var J,ne,le;const u=s.useEditorStore(Z=>Z.card),x=s.useDashboardStore(Z=>Z.filterValues),h=s.useDashboardStore(Z=>Z.selectedSheetId),p=s.useDashboardStore(Z=>Z.inlineFilterValuesMap[(d==null?void 0:d.id)||""]),{updateCardConfig:w,setCard:m,updateCardInFrame:g,setShowAIDialog:v}=s.useEditorActions(),C=s.useEditorStore(Z=>Z.showAIDialog),A=s.useDashboardStore(Z=>Z.isVisualEditing),[B,O]=D.useState(!1),[E,N]=D.useState(!1),[f,j]=D.useState(null),{config:S}=D.useContext(s.SemaphorContext).tokenProps,M=(S==null?void 0:S.showInfoTab)!==!1,[y,b]=Ba(),I=s.useEditorStore(Z=>{var oe;return((oe=Z.card.customCardPreferences)==null?void 0:oe.url)&&Z.card.type==="custom"}),{data:F,errorMessage:T,isLoading:L,isFetching:k,errorSql:R,pagination:K,refetch:_,comparisonMetadata:G}=s.useDashboardCardQuery(d),q=D.useMemo(()=>(F==null?void 0:F.records)||[],[F==null?void 0:F.records]),[V,z]=D.useState(!1);D.useEffect(()=>{k||z(!1)},[k]);const H=()=>{const Z=!y;Z&&t==="table"&&n("chart"),b(Z)},P=(Z,oe)=>{const $={...d,paginationConfig:{page:Z+1,pageSize:oe}};m($),g($)};function W(){return e.jsxs("div",{className:"relative border-b border-border bg-background p-4",children:[e.jsx("button",{onClick:r,className:"absolute right-4 top-4 rounded-md p-1 hover:bg-muted","aria-label":"Close Debug Panel",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsxs("div",{className:"space-y-4 pr-8",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(u.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(x||{},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(d.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",i.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:c?"Loading...":o?"Error loading columns":JSON.stringify(i.slice(0,5),null,2)})]})]})]})}const Y=Z=>{if(!u.config)return;const oe=s.sortStateToSortByColumns(Z,u.config.metricColumns,u.config.groupByColumns);w(u.id,{...u.config,sortByColumns:oe})},ee=D.useMemo(()=>{var Z;return s.sortByColumnsToSortState((Z=u.config)==null?void 0:Z.sortByColumns)},[(J=u.config)==null?void 0:J.sortByColumns]);return e.jsxs("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":C&&A}),children:[a&&W(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&C&&e.jsx(Ms,{variant:"outline"}),e.jsx(Ia,{activeView:t,onViewChange:n,splitViewEnabled:y}),e.jsx(s.FilterInfo,{cardId:d.id,cardFilters:(ne=d.config)==null?void 0:ne.filters,cardFilterCount:s.getFilterCount(((le=d.config)==null?void 0:le.filters)||null),onFiltersClick:l,inlineFilters:d.inlineFilters,inlineFilterValues:p,sheetId:h||""}),G&&e.jsx(s.ComparisonMetadataBadge,{metadata:G,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Ma,{})}),C&&e.jsx(_e.EditorClearButton,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:L||k,onClick:()=>{z(!0),_()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":V})})}),t==="chart"&&e.jsx(s.IconButton,{tooltip:y?"Hide Results Table":"Show Results Table",onClick:H,children:y?e.jsx(ht,{className:"size-4"}):e.jsx(Et,{className:"size-4"})}),t==="chart"&&e.jsx(e.Fragment,{children:e.jsx(Ls,{})}),!C&&e.jsx(s.IconButton,{onClick:()=>v(!C),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),r&&s.isDevEnv]})]}),!B&&I&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>O(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(s.Settings2,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex min-h-0 grow flex-col",children:[t==="chart"&&e.jsx("div",{className:s.cn("flex grow flex-col pb-6",{"pb-0":y&&!["table","pivotTable","aggregateTable"].includes(d.type)}),children:e.jsx(La,{card:d,queryData:F,isLoading:L,isFetching:k,pagination:K,onPaginationChange:P,onSortChange:Y,sortState:ee,splitViewEnabled:y})}),t==="table"&&(F==null?void 0:F.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:d,data:q,paginationMetadata:K,onPaginationChange:P,isLoading:L||k,onSortChange:Y,sortState:ee})}),t==="info"&&M&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col pb-6",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col rounded-md bg-background px-6",children:T?e.jsx(Je,{error:T,errorSql:R,onSendFeedback:()=>{const Z=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:u.config,dataSource:d.dataSource,dashboardFilters:x,errorMessage:T,errorSql:R,generatedSql:F==null?void 0:F.sql});j(Z),N(!0)},onOpenInEditor:()=>{v(!0),setTimeout(()=>{const Z=s.useEditorStore.getState().actions;Z.setIsDevMode(!0),Z.setCardSql(R||""),setTimeout(()=>{Z.setRunSql(!0)},100)},100)}}):e.jsx(As,{sql:F==null?void 0:F.sql,error:T,errorSql:R})})})]}),e.jsx(Oa,{isOpen:B,onClose:()=>O(!1)}),f&&e.jsx(s.FeedbackDialog,{open:E,onOpenChange:N,feedbackData:f})]})]})}function Pa({activeField:t}){const[n,a]=D.useState(!0);return D.useEffect(()=>{t&&a(!0)},[t]),t?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 ${n?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(We,{dataType:t.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:t.label||t.name})]}):null}const Va=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const n=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},a=r=>{var l;if((l=r.reason)!=null&&l.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",n,!0),window.addEventListener("unhandledrejection",a,!0),()=>{console.error=t,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function za({column:t,isSelected:n,onSelect:a,availableFields:r,width:l,onWidthChange:d}){var K,_,G;const i=s.useEditorStore(q=>q.card),{updateCardConfig:c,removeGroupByColumn:o,removeMetricColumn:u,updateFilters:x}=s.useEditorActions(),[h,p]=D.useState(!1),[w,m]=D.useState(!1),g=D.useRef(null),v=D.useCallback(q=>{q.preventDefault(),q.stopPropagation(),m(!0),g.current={startX:q.clientX,startWidth:l||150};const V=H=>{if(!g.current)return;const P=H.clientX-g.current.startX,W=Math.max(80,g.current.startWidth+P);d==null||d(t.id,W)},z=()=>{m(!1),g.current=null,document.removeEventListener("mousemove",V),document.removeEventListener("mouseup",z)};document.addEventListener("mousemove",V),document.addEventListener("mouseup",z)},[l,t.id,d]),C=(K=i==null?void 0:i.config)==null?void 0:K.filters,A=(_=C==null?void 0:C.conditions)==null?void 0:_.some(q=>q.field.name===t.name&&q.field.qualifiedEntityName===t.qualifiedEntityName),B=q=>{q?x(i.id,q):c(i.id,{filters:void 0})},{attributes:O,listeners:E,setNodeRef:N,transform:f,transition:j,isDragging:S}=s.useSortable({id:t.id}),M={transform:s.CSS.Transform.toString(f),transition:j},y=s.getDataType(t.dataType),b=$a(y),I=()=>{var z;const q=((z=i==null?void 0:i.config)==null?void 0:z.sortByColumns)||[],V=q.findIndex(H=>H.name===t.name);if(V!==-1){const H=[...q];H[V]={...H[V],direction:"asc"},c(i.id,{sortByColumns:H})}else c(i.id,{sortByColumns:[...q,{...t,id:`sort-${t.id}`,role:"sortby",direction:"asc"}]})},F=()=>{var z;const q=((z=i==null?void 0:i.config)==null?void 0:z.sortByColumns)||[],V=q.findIndex(H=>H.name===t.name);if(V!==-1){const H=[...q];H[V]={...H[V],direction:"desc"},c(i.id,{sortByColumns:H})}else c(i.id,{sortByColumns:[...q,{...t,id:`sort-${t.id}`,role:"sortby",direction:"desc"}]})},T=()=>{var z;const q=((z=i==null?void 0:i.config)==null?void 0:z.groupByColumns)||[];if(!q.some(H=>H.name===t.name)){const H={...t,id:`groupby-${t.id}-${Date.now()}`,role:"groupby"};c(i.id,{groupByColumns:[...q,H]})}},L=q=>{var H;const V=((H=i==null?void 0:i.config)==null?void 0:H.metricColumns)||[];if(!V.some(P=>P.name===t.name&&P.aggregate===q)){const P={...t,id:`metric-${t.id}-${q}-${Date.now()}`,label:`${q} of ${t.label||t.name}`,role:"metric",aggregate:q};c(i.id,{metricColumns:[...V,P]})}},k=()=>{t.role==="groupby"?o(i.id,t.id):t.role==="metric"&&u(i.id,t.id)},R={...M,width:l?`${l}px`:void 0,minWidth:l?`${l}px`:"120px"};return e.jsxs("th",{ref:N,style:R,className:s.cn("group relative border-r border-border bg-background px-1 py-0",S&&"opacity-50",n&&"bg-primary/10",w&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...O,...E,className:"cursor-grab p-1 text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100 active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-3 w-3"})}),e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs("button",{onClick:a,className:s.cn("flex flex-1 items-center justify-between gap-1 rounded px-2 py-2 text-left text-sm font-medium transition-colors hover:bg-muted/50",n&&"bg-primary/10"),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(b,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:t.label||t.name}),t.role==="metric"&&t.aggregate&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",t.aggregate,")"]}),A&&e.jsx(s.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(s.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(s.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(s.DropdownMenuItem,{onClick:()=>p(!0),children:[e.jsx(s.Filter,{className:s.cn("mr-2 h-4 w-4",A&&"text-primary")}),A?"Edit Filter":"Filter"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:I,children:[e.jsx(it,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(s.DropdownMenuItem,{onClick:F,children:[e.jsx(ot,{className:"mr-2 h-4 w-4"}),"Sort Z → A"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuSub,{children:[e.jsxs(s.DropdownMenuSubTrigger,{children:[e.jsx(s.Calculator,{className:"mr-2 h-4 w-4"}),"Summarize"]}),e.jsxs(s.DropdownMenuSubContent,{children:[e.jsx(s.DropdownMenuItem,{onClick:()=>L("SUM"),children:"Sum"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("AVG"),children:"Average"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("COUNT"),children:"Count"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("DISTINCT"),children:"Count Distinct"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("MIN"),children:"Min"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("MAX"),children:"Max"})]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:T,children:[e.jsx(He,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(s.DropdownMenuItem,{disabled:!0,children:[e.jsx(Ss,{className:"mr-2 h-4 w-4"}),"Pivot by this column"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{disabled:!0,children:[e.jsx(s.EyeOff,{className:"mr-2 h-4 w-4"}),"Hide column"]}),e.jsxs(s.DropdownMenuItem,{onClick:k,className:"text-destructive focus:text-destructive",children:[e.jsx(s.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:v,className:s.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",w&&"bg-primary")}),e.jsx(Js,{open:h,onOpenChange:p,availableFields:r.length>0?r:[t],existingFilters:C,editingCondition:A?(G=C==null?void 0:C.conditions)==null?void 0:G.find(q=>q.field.name===t.name&&q.field.qualifiedEntityName===t.qualifiedEntityName):void 0,onSave:B})]})}function $a(t){switch(t){case"number":return s.Hash;case"date":return s.Calendar;case"string":default:return s.Type}}function Ka({selectedColumn:t,onColumnSelect:n,isLoading:a=!1,sourceFields:r=[]}){var j,S,M,y;const l=s.useEditorStore(b=>b.card),{updateCardConfig:d}=s.useEditorActions(),[i,c]=D.useState(null),[o,u]=D.useState({}),[x,h]=D.useState(!1),p=D.useMemo(()=>{var F,T;const b=((F=l==null?void 0:l.config)==null?void 0:F.groupByColumns)||[],I=((T=l==null?void 0:l.config)==null?void 0:T.metricColumns)||[];return[...b,...I]},[(j=l==null?void 0:l.config)==null?void 0:j.groupByColumns,(S=l==null?void 0:l.config)==null?void 0:S.metricColumns]),w=D.useMemo(()=>{const b=new Set(p.map(I=>`${I.qualifiedEntityName}.${I.name}`));return r.filter(I=>!b.has(`${I.qualifiedEntityName}.${I.name}`))},[r,p]),{data:m,isLoading:g}=s.useDashboardCardQuery(l),v=(m==null?void 0:m.records)||[],C=D.useCallback((b,I)=>{u(F=>({...F,[b]:I}))},[]),A=D.useCallback(b=>{var L,k;const I=s.getDataType(b.dataType),F=((L=l==null?void 0:l.config)==null?void 0:L.groupByColumns)||[],T=((k=l==null?void 0:l.config)==null?void 0:k.metricColumns)||[];if(I==="number"){const R={...b,id:`metric-${b.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};d(l.id,{metricColumns:[...T,R]})}else{const R={...b,id:`groupby-${b.id}-${Date.now()}`,role:"groupby"};d(l.id,{groupByColumns:[...F,R]})}h(!1)},[(M=l==null?void 0:l.config)==null?void 0:M.groupByColumns,(y=l==null?void 0:l.config)==null?void 0:y.metricColumns,l.id,d]),B=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),O=b=>{c(b.active.id)},E=b=>{const{active:I,over:F}=b;if(c(null),!F||I.id===F.id)return;const T=p.findIndex(k=>k.id===I.id),L=p.findIndex(k=>k.id===F.id);if(T!==-1&&L!==-1){const k=s.arrayMove(p,T,L),R=k.filter(_=>_.role==="groupby"),K=k.filter(_=>_.role==="metric");d(l.id,{groupByColumns:R,metricColumns:K})}},N=i?p.find(b=>b.id===i):null,f=b=>{let I="";for(;b>=0;)I=String.fromCharCode(b%26+65)+I,b=Math.floor(b/26)-1;return I};return a?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):p.length===0?e.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-4 p-8 text-center",children:e.jsxs("div",{className:"rounded-lg border-2 border-dashed border-muted-foreground/25 p-12",children:[e.jsx("h3",{className:"text-lg font-medium text-muted-foreground",children:"No columns selected"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground/75",children:"Select columns from the panel on the right to build your table"})]})}):e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(s.DndContext,{sensors:B,collisionDetection:s.closestCenter,onDragStart:O,onDragEnd:E,children:[e.jsxs("table",{className:"w-full border-collapse",children:[e.jsxs("thead",{children:[e.jsxs("tr",{className:"border-b border-border bg-muted/30",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-1 text-center text-xs font-medium text-muted-foreground"}),e.jsx(s.SortableContext,{items:p.map(b=>b.id),strategy:s.horizontalListSortingStrategy,children:p.map((b,I)=>e.jsx("th",{style:{width:o[b.id]?`${o[b.id]}px`:void 0,minWidth:o[b.id]?`${o[b.id]}px`:"120px"},className:"border-r border-border bg-muted/30 px-2 py-1 text-center text-xs font-medium text-muted-foreground",children:f(I)},`letter-${b.id}`))}),e.jsx("th",{className:"w-10 border-r border-border bg-muted/30 px-2 py-1"})]}),e.jsxs("tr",{className:"border-b-2 border-border bg-background",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-2 text-center text-xs font-medium text-muted-foreground",children:"#"}),e.jsx(s.SortableContext,{items:p.map(b=>b.id),strategy:s.horizontalListSortingStrategy,children:p.map(b=>e.jsx(za,{column:b,isSelected:(t==null?void 0:t.id)===b.id,onSelect:()=>n(b),availableFields:r,width:o[b.id],onWidthChange:C},b.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(s.Popover,{open:x,onOpenChange:h,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Add column",children:e.jsx(s.Plus,{className:"h-4 w-4"})})}),e.jsx(s.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search columns..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No columns available."}),e.jsx(s.CommandGroup,{heading:"Available Columns",children:w.map(b=>{const I=s.getDataType(b.dataType),F=I==="number"?s.Hash:I==="date"?s.Calendar:s.Type;return e.jsxs(s.CommandItem,{value:b.label||b.name,onSelect:()=>A(b),children:[e.jsx(F,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm",children:b.label||b.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:b.entityName})]})]},b.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:g?e.jsx("tr",{children:e.jsx("td",{colSpan:p.length+2,className:"h-32 text-center",children:e.jsx(s.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):v.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:p.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):v.slice(0,100).map((b,I)=>e.jsxs("tr",{className:s.cn("border-b border-border transition-colors hover:bg-muted/50",I%2===0?"bg-background":"bg-muted/20"),children:[e.jsx("td",{className:"sticky left-0 z-10 w-12 border-r border-border bg-muted/50 px-2 py-2 text-center text-xs font-medium text-muted-foreground",children:I+1}),p.map(F=>{const T=b[F.name]??b[F.label??""];return e.jsx("td",{style:{width:o[F.id]?`${o[F.id]}px`:void 0,minWidth:o[F.id]?`${o[F.id]}px`:"120px"},className:s.cn("border-r border-border px-3 py-2 text-sm",(t==null?void 0:t.id)===F.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:Ga(T,F)})},`${I}-${F.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},I))})]}),e.jsx(s.DragOverlay,{children:N&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:N.label||N.name})})]})}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border bg-muted/30 px-4 py-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Showing ",Math.min(v.length,100)," of ",v.length," rows"]}),e.jsxs("span",{children:[p.length," columns"]})]})]})}function Ga(t,n){if(t==null)return"—";if(typeof t=="number")return n.role==="metric"?new Intl.NumberFormat("en-US",{minimumFractionDigits:0,maximumFractionDigits:2}).format(t):t.toString();if(t instanceof Date||typeof t=="string"&&!isNaN(Date.parse(t))){const a=new Date(t);if(!isNaN(a.getTime()))return a.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(t)}function qa({entityGroups:t,isLoading:n=!1}){var B,O;const a=s.useEditorStore(E=>E.card),{updateCardConfig:r,removeGroupByColumn:l,removeMetricColumn:d}=s.useEditorActions(),[i,c]=D.useState(!0),[o,u]=D.useState(""),[x,h]=D.useState(new Set),p=((B=a==null?void 0:a.config)==null?void 0:B.groupByColumns)||[],w=((O=a==null?void 0:a.config)==null?void 0:O.metricColumns)||[],m=E=>{const N=new Set(x);N.has(E)?N.delete(E):N.add(E),h(N)},g=E=>p.some(N=>N.name===E.name&&N.qualifiedEntityName===E.qualifiedEntityName)||w.some(N=>N.name===E.name&&N.qualifiedEntityName===E.qualifiedEntityName),v=(E,N)=>{if(N)if(s.getDataType(E.dataType)==="number"){const j={...E,id:`metric-${E.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(a.id,{metricColumns:[...w,j]})}else{const j={...E,id:`groupby-${E.id}-${Date.now()}`,role:"groupby"};r(a.id,{groupByColumns:[...p,j]})}else{const f=p.findIndex(S=>S.name===E.name&&S.qualifiedEntityName===E.qualifiedEntityName),j=w.findIndex(S=>S.name===E.name&&S.qualifiedEntityName===E.qualifiedEntityName);f!==-1&&l(a.id,p[f].id),j!==-1&&d(a.id,w[j].id)}},C=E=>{if(!o)return E;const N=o.toLowerCase();return E.filter(f=>f.name.toLowerCase().includes(N)||f.label&&f.label.toLowerCase().includes(N))},A=E=>{switch(s.getDataType(E)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.Type}};return i?e.jsxs("div",{className:"flex h-full w-72 flex-col border-l border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Columns"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>c(!1),title:"Close panel",children:e.jsx(wt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search columns...",value:o,onChange:E=>u(E.target.value),className:"h-8 pl-8 text-sm"})]})}),(p.length>0||w.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[p.length>0&&e.jsxs(s.Collapsible,{defaultOpen:!0,children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(He,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsx("span",{children:"Groupings"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:p.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:p.map(E=>{const N=A(E.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(s.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(N,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:E.label||E.name}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>l(a.id,E.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},E.id)})})})]}),w.length>0&&e.jsxs(s.Collapsible,{defaultOpen:!0,children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(s.Calculator,{className:"h-3.5 w-3.5 text-green-500"}),e.jsx("span",{children:"Metrics"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:w.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:w.map(E=>{const N=A(E.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(s.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(N,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:E.label||E.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:E.aggregate}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>d(a.id,E.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},E.id)})})})]})]}),e.jsx(s.ScrollArea,{className:"flex-1",children:e.jsx("div",{className:"p-2",children:n?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent"})}):t.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No columns available"}):t.map(E=>{const N=C(E.columns);if(N.length===0)return null;const f=x.has(E.entityId)||o.length>0;return e.jsxs(s.Collapsible,{open:f,onOpenChange:()=>m(E.entityId),children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:s.cn("h-3.5 w-3.5 transition-transform duration-200",f&&"rotate-90")}),e.jsx(s.Table2,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate text-left",children:E.label||E.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:N.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:N.map(j=>{const S=A(j.dataType),M=g(j);return e.jsxs("label",{className:s.cn("flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-sm transition-colors hover:bg-muted/50",M&&"bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:M,onCheckedChange:y=>v(j,y),className:"h-3.5 w-3.5"}),e.jsx(S,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:j.label||j.name})]},j.id)})})})]},E.entityId)})})})]}):e.jsx("div",{className:"flex h-full items-start border-l border-border bg-muted/30 p-2",children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(!0),title:"Open panel",children:e.jsx(kt,{className:"h-4 w-4"})})})}const Ua=[{name:"SUM",description:"Sum of values",syntax:"SUM([column])"},{name:"AVG",description:"Average of values",syntax:"AVG([column])"},{name:"COUNT",description:"Count of rows",syntax:"COUNT([column])"},{name:"COUNTD",description:"Count distinct values",syntax:"COUNTD([column])"},{name:"MIN",description:"Minimum value",syntax:"MIN([column])"},{name:"MAX",description:"Maximum value",syntax:"MAX([column])"},{name:"IF",description:"Conditional logic",syntax:"IF(condition, then, else)"},{name:"CASE",description:"Multiple conditions",syntax:"CASE WHEN ... THEN ... END"},{name:"CONCAT",description:"Concatenate text",syntax:"CONCAT([col1], [col2])"},{name:"ROUND",description:"Round number",syntax:"ROUND([column], decimals)"},{name:"FLOOR",description:"Round down",syntax:"FLOOR([column])"},{name:"CEIL",description:"Round up",syntax:"CEIL([column])"},{name:"ABS",description:"Absolute value",syntax:"ABS([column])"},{name:"DATEPART",description:"Extract date part",syntax:"DATEPART(year, [date])"},{name:"DATEDIFF",description:"Difference between dates",syntax:"DATEDIFF(day, [date1], [date2])"}];function _a({value:t,onChange:n,onSubmit:a,onCancel:r,selectedColumn:l,availableColumns:d}){const[i,c]=D.useState(!1),[o,u]=D.useState("column"),x=D.useRef(null);D.useEffect(()=>{const m=g=>{g.key==="Escape"&&t?r():g.key==="Enter"&&t&&!i&&a(t)};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[t,r,a,i]);const h=m=>{const g=`[${m.label||m.name}]`,v=x.current;if(v){const C=v.selectionStart||0,A=v.selectionEnd||0,B=t.slice(0,C)+g+t.slice(A);n(B),setTimeout(()=>{v.setSelectionRange(C+g.length,C+g.length),v.focus()},0)}else n(t+g);c(!1)},p=m=>{const g=x.current;if(g){const v=g.selectionStart||0,C=g.selectionEnd||0,A=t.slice(0,v)+m.syntax+t.slice(C);n(A),setTimeout(()=>{g.setSelectionRange(v+m.name.length+1,v+m.syntax.length-1),g.focus()},0)}else n(t+m.syntax);c(!1)},w=m=>{switch(s.getDataType(m)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.Type}};return e.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-1.5",children:[e.jsx("div",{className:"flex min-w-[100px] items-center justify-center rounded border border-border bg-background px-2 py-1 text-xs font-medium text-muted-foreground",children:l?e.jsx("span",{className:"truncate",children:l.label||l.name}):e.jsx("span",{children:"—"})}),e.jsxs(s.Popover,{open:i&&o==="function",onOpenChange:m=>{c(m),m&&u("function")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Insert function",children:e.jsx(Tt,{className:"h-4 w-4"})})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search functions..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No functions found."}),e.jsx(s.CommandGroup,{heading:"Functions",children:Ua.map(m=>e.jsx(s.CommandItem,{value:m.name,onSelect:()=>p(m),children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm font-medium",children:m.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:m.syntax})]})},m.name))})]})]})})]}),e.jsxs(s.Popover,{open:i&&o==="column",onOpenChange:m=>{c(m),m&&u("column")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",className:"h-7 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground",title:"Insert column reference",children:[e.jsx("span",{children:"Columns"}),e.jsx(s.ChevronDown,{className:"h-3 w-3"})]})}),e.jsx(s.PopoverContent,{className:"w-[250px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search columns..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No columns found."}),e.jsx(s.CommandGroup,{heading:"Available Columns",children:d.map(m=>{const g=w(m.dataType);return e.jsxs(s.CommandItem,{value:m.label||m.name,onSelect:()=>h(m),children:[e.jsx(g,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:m.label||m.name})]},m.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(s.Input$1,{ref:x,value:t,onChange:m=>n(m.target.value),placeholder:"Enter a formula or select a column...",className:"h-7 border-border bg-background font-mono text-sm"})}),t&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-destructive hover:bg-destructive/10 hover:text-destructive",onClick:r,title:"Cancel (Esc)",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-green-600 hover:bg-green-600/10 hover:text-green-600",onClick:()=>a(t),title:"Apply (Enter)",children:e.jsx(s.Check,{className:"h-4 w-4"})})]})]})}function Ha({className:t}){var p,w,m,g;const n=s.useEditorStore(v=>v.card),[a,r]=D.useState(null),[l,d]=D.useState(""),{columns:i=[],columnGroups:c=[],isLoading:o}=s.useColumns();(p=n==null?void 0:n.config)!=null&&p.groupByColumns,(w=n==null?void 0:n.config)!=null&&w.metricColumns,(m=n==null?void 0:n.config)!=null&&m.groupByColumns,(g=n==null?void 0:n.config)!=null&&g.pivotByColumns;const u=v=>{r(v),d(v?`[${v.label||v.name}]`:"")},x=v=>{console.log("Formula submitted:",v),d(""),r(null)},h=()=>{d(""),r(null)};return e.jsxs("div",{className:s.cn("flex h-full w-full flex-col",t),children:[e.jsx(_a,{value:l,onChange:d,onSubmit:x,onCancel:h,selectedColumn:a,availableColumns:i}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(Ka,{selectedColumn:a,onColumnSelect:u,isLoading:o,sourceFields:i})}),e.jsx(qa,{entityGroups:c,isLoading:o})]})]})}function Ja(){var K,_;const[t,n]=D.useState("chart"),[a,r]=D.useState(!1),[l,d]=D.useState(!1),[i,c]=D.useState(!0),o=s.useEditorStore(G=>G.showAIDialog),u=s.useDashboardStore(G=>G.isVisualEditing),{setCardType:x}=s.useEditorActions(),h=s.useEditorStore(G=>G.card.type);D.useEffect(()=>Va(),[]);const p=G=>{x(G)},w=s.useEditorStore(G=>G.frame),m=s.useEditorStore(G=>G.card);s.useEditorStore(G=>G.activeTabCardId),s.useEditorStore(G=>G.actions.getAvailableFields);const{addCard:g,removeCard:v,updateCard:C,setActiveCard:A,updateFilters:B}=s.useEditorActions(),{columns:O=[],isLoading:E,error:N}=s.useColumns(),f=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),j=m,{getFieldsForContainer:S,setFieldsForContainer:M}=s.useFieldManagement(j),{activeField:y,handleDragStart:b,handleDragEnd:I}=Aa({activeCardId:w.activeCardId,sourceFields:O,getFieldsForContainer:S,setFieldsForContainer:M}),F=(G,q)=>{q&&B(G,q)},T=G=>{var q;C(G,{config:{...(q=w.cards.find(V=>V.id===G))==null?void 0:q.config,filters:void 0}})},L=O,k=G=>{if(!G)return 0;let q=G.conditions.length;return G.groups.forEach(V=>{q+=k(V)}),q},R=k(((K=j==null?void 0:j.config)==null?void 0:K.filters)||null);return e.jsxs(s.DndContext,{sensors:f,collisionDetection:s.closestCenter,onDragStart:b,onDragEnd:I,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Es,{isVisible:i,onToggleVisibility:()=>c(!i)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:h==="tableBuilder"?e.jsx(Ha,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!o&&e.jsx(ua,{selectedChart:h,onChartChange:p,groupByFields:S("groupBy"),pivotByFields:S("pivotBy"),metricsFields:S("metrics"),sortByFields:S("sortBy"),activeField:y}),e.jsx(Ra,{selectedChart:h,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onFiltersClick:()=>d(!0),filterCount:R,activeCard:j,dataSourceState:m.dataSource||s.EMPTY_DATA_SOURCE,columns:O,columnsLoading:E,columnsError:N,getFieldsForContainer:S,cards:w.cards,activeCardId:w.activeCardId,addCard:g,setActiveCard:A})]})}),!i&&u&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>c(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),j&&e.jsx(Ea,{cardId:j.id,filters:((_=j.config)==null?void 0:_.filters)||null,onFiltersChange:F,onClearFilters:T,availableFields:L,isOpen:l,onOpenChange:d}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Pa,{activeField:y||null})})]})}function Qa({authToken:t,onSave:n,onClose:a}){const r=D.useRef(null),l=s.useEditorStore(N=>N.showAIDialog),d=s.useEditorStore(N=>N.isDevMode),i=s.useAssistantLayoutStore(N=>N.setFullscreen),c=s.useAssistantLayoutStore(N=>N.setPanelOpen),o=s.useAssistantLayoutStore(N=>N.setContainer),u=s.useAssistantPanel("editor"),x=s.useFullscreenAssistant(),h=s.useAssistantContainer("editor"),p=x==="editor",w=D.useCallback(N=>{o("editor",N)},[o]),{setAuthToken:m}=s.useDashboardActions(),{setShowAIDialog:g,setOnSave:v,setOnClose:C}=s.useEditorActions(),{setActiveAssistantType:A}=s.useAIActions();D.useEffect(()=>{n&&v(n),a&&C(a)},[n,v,a,C]),D.useEffect(()=>{t&&t.accessToken&&m(t)},[t,m]),D.useEffect(()=>{var N,f;l?((N=r.current)==null||N.resize(40),c("editor",!0),A("editor")):((f=r.current)==null||f.resize(0),c("editor",!1),x==="editor"&&i(null),A(null))},[l,c,A,i,x]);function B(N){N<1?(g(!1),c("editor",!1),x==="editor"&&i(null),A(null)):(l||(g(!0),A("editor")),u.isOpen||c("editor",!0))}function O(){return e.jsxs(e.Fragment,{children:[e.jsx(Es,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow border-l",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:s.cn("grow transition-opacity",p&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Kn,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:B,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(ps,{isFullscreen:p,onFullscreenChange:N=>i(N?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:w,className:s.cn("absolute inset-0",!p&&"pointer-events-none")})]})]})}function E(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:s.cn("flex grow transition-opacity",p&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Ja,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:B,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(ps,{isFullscreen:p,onFullscreenChange:N=>i(N?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:w,className:s.cn("absolute inset-0",!p&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:d?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:O()}):E()})}function Ya(){s.useDashboardStore(i=>i.selectedCardId);const t=s.useDashboardStore(i=>i.selectedSheetId),{setIsVisualEditing:n}=s.useDashboardStore(i=>i.actions),a=s.useDashboardStore(i=>i.isVisualEditing),r=s.useDashboardStore(i=>i.actions.updateFrame);function l(i){t&&(r(t,i),n(!1))}function d(){n(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!a}),children:e.jsx(Qa,{onSave:l,onClose:d})})}exports.default=Ya;