react-semaphor 0.1.200 → 0.1.202

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 (31) hide show
  1. package/dist/chunks/{dashboard-controls-DgtdC01F.js → dashboard-controls-CkfdfqNi.js} +1 -1
  2. package/dist/chunks/{dashboard-controls-CR7lL9Et.js → dashboard-controls-Ct4PKzi_.js} +5 -5
  3. package/dist/chunks/{dashboard-json-FBuHMfmM.js → dashboard-json-BoT-Wp2i.js} +1 -1
  4. package/dist/chunks/{dashboard-json-Bmbz02KL.js → dashboard-json-DcdjxLFv.js} +1 -1
  5. package/dist/chunks/{dashboard-summary-settings-dialog-DYTNK2ms.js → dashboard-summary-settings-dialog-BVWeRbN7.js} +1 -1
  6. package/dist/chunks/{dashboard-summary-settings-dialog-DV5YCuwR.js → dashboard-summary-settings-dialog-D1QDJSfs.js} +1 -1
  7. package/dist/chunks/{edit-dashboard-visual-Nxbr8BSI.js → edit-dashboard-visual-DGebHYIi.js} +17 -19
  8. package/dist/chunks/{edit-dashboard-visual-BIYh-RkG.js → edit-dashboard-visual-DH5QSGaK.js} +10 -10
  9. package/dist/chunks/{editor-action-buttons-CG41Ltln.js → editor-action-buttons-B2STBcxD.js} +1 -1
  10. package/dist/chunks/{editor-action-buttons-DbcFVAEa.js → editor-action-buttons-CmYVGMmU.js} +2 -2
  11. package/dist/chunks/{index-DVYihXOb.js → index-2UB7egQD.js} +19522 -19484
  12. package/dist/chunks/{index-BpOENSQP.js → index-VMtFUqKe.js} +194 -194
  13. package/dist/chunks/{notification-bell-elxLrm2b.js → notification-bell-B3-Ju7ln.js} +1 -1
  14. package/dist/chunks/{notification-bell-CJIzPr5F.js → notification-bell-ClsbaKmk.js} +3 -3
  15. package/dist/chunks/{resource-management-panel-BTPmfdMd.js → resource-management-panel-D9IRB31b.js} +3 -3
  16. package/dist/chunks/{resource-management-panel-DIFmTV1p.js → resource-management-panel-JhskGQEY.js} +1 -1
  17. package/dist/chunks/{use-role-aware-display-preferences-Ld4jvyhY.js → use-role-aware-display-preferences-CLjqnHpY.js} +1 -1
  18. package/dist/chunks/{use-role-aware-display-preferences-CwhsIdSD.js → use-role-aware-display-preferences-CNicmmdy.js} +1 -1
  19. package/dist/chunks/{use-visual-utils-B6X9311f.js → use-visual-utils-CzWIOx1O.js} +1 -1
  20. package/dist/chunks/{use-visual-utils-B9Bw0478.js → use-visual-utils-DhK1ng8v.js} +1 -1
  21. package/dist/dashboard/index.cjs +1 -1
  22. package/dist/dashboard/index.js +1 -1
  23. package/dist/index.cjs +1 -1
  24. package/dist/index.js +5 -5
  25. package/dist/surfboard/index.cjs +1 -1
  26. package/dist/surfboard/index.js +2 -2
  27. package/dist/types/dashboard.d.ts +1 -1
  28. package/dist/types/main.d.ts +1 -1
  29. package/dist/types/surfboard.d.ts +1 -1
  30. package/dist/types/types.d.ts +1 -1
  31. 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-BpOENSQP.js"),k=require("react"),ye=require("./editor-action-buttons-CG41Ltln.js"),Lt=require("react-dom");function Mt(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 as=Mt(k);/**
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),s=require("./index-VMtFUqKe.js"),I=require("react"),ye=require("./editor-action-buttons-B2STBcxD.js"),Lt=require("react-dom");function Mt(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 as=Mt(I);/**
2
2
  * @license lucide-react v0.453.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -118,7 +118,7 @@
118
118
  *
119
119
  * This source code is licensed under the ISC license.
120
120
  * See the LICENSE file in the root directory of this source tree.
121
- */const ks=s.createLucideIcon("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
121
+ */const Is=s.createLucideIcon("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
122
122
  * @license lucide-react v0.453.0 - ISC
123
123
  *
124
124
  * This source code is licensed under the ISC license.
@@ -158,13 +158,13 @@
158
158
  *
159
159
  * This source code is licensed under the ISC license.
160
160
  * See the LICENSE file in the root directory of this source tree.
161
- */const ta=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 Ws({storeValue:t,defaultValue:n="",onStoreUpdate:a,delay:r=300}){const[i,c]=k.useState(t??n),l=s.useDebounce(i,r),d=k.useRef(t),o=k.useRef(!1);k.useEffect(()=>{t!==d.current&&(c(t??n),d.current=t)},[t,n]),k.useEffect(()=>{o.current&&l!==d.current&&(a(l),d.current=l)},[l,a]);const x=k.useCallback(p=>{o.current=!0,c(p??n)},[n]);return{value:i,onChange:x}}function aa({initialJoinPlan:t,availableDataSources:n}){const[a,r]=k.useState(t),[i,c]=k.useState(new Set),l=()=>{const g=a.joins.length>0?Math.max(...a.joins.map(E=>E.sequence))+1:1,w={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:g,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,w]}),c(new Set([...i,w.id]))},d=g=>{r({...a,joins:a.joins.filter(w=>w.id!==g)}),c(new Set([...i].filter(w=>w!==g)))},o=(g,w)=>{var I,D,P,v,A;const E=a.joins.find(S=>S.id===g);if(!E)return;const f={...E,...w};if((I=f.source)!=null&&I.name&&((D=f.target)!=null&&D.name)&&f.source.name===f.target.name){s.ue.error("Self-joins are not yet supported",{description:`Joining ${f.source.name} to itself is not currently supported. Please select a different target table.`});return}const M=a.joins.filter(S=>{var R;return S.id!==g&&S.target.name===((R=f.target)==null?void 0:R.name)});if((P=f.target)!=null&&P.name&&M.length>0){s.ue.error("Duplicate join targets are not supported",{description:`The table ${f.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const j=a.joins.map(S=>S.id===g?f:S);if((v=f.source)!=null&&v.name&&((A=f.target)!=null&&A.name)&&f.joinKeyGroups[0].keys.length===0){const S=n.find(G=>{var V;return G.name===((V=f.source)==null?void 0:V.name)}),R=n.find(G=>{var V;return G.name===((V=f.target)==null?void 0:V.name)}),F={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:(R==null?void 0:R.name)||"",entityName:(R==null?void 0:R.name)||"",entityType:(R==null?void 0:R.type)||"table"},operator:"="},z=[...f.joinKeyGroups];z[0]={...z[0],keys:[F]},f.joinKeyGroups=z,j[j.findIndex(G=>G.id===g)]=f}r({...a,joins:j})};return{joinPlan:a,expandedJoins:i,setJoinPlan:r,addJoin:l,removeJoin:d,updateJoin:o,moveJoinUp:g=>{const w=a.joins.findIndex(E=>E.id===g);if(w>0){const E=[...a.joins],f={...E[w]},M={...E[w-1]};E[w]=M,E[w-1]=f,E.forEach((I,D)=>{I.sequence=D+1});const j={...a,joins:E};r(j)}},moveJoinDown:g=>{const w=a.joins.findIndex(E=>E.id===g);if(w<a.joins.length-1){const E=[...a.joins],f={...E[w]},M={...E[w+1]};E[w]=M,E[w+1]=f,E.forEach((I,D)=>{I.sequence=D+1});const j={...a,joins:E};r(j)}},toggleJoinExpansion:g=>{const w=new Set(i);w.has(g)?w.delete(g):w.add(g),c(w)},getAvailableSourceEntities:g=>{if(a.joins.length===0)return n;const w=a.joins.findIndex(f=>f.id===g);if(w===0)return n.filter(f=>f.name===a.baseEntity.name);const E=new Set;return a.baseEntity.name&&E.add(a.baseEntity.name),a.joins.slice(0,w).forEach(f=>{E.add(f.source.name),E.add(f.target.name)}),n.filter(f=>E.has(f.name))},getAvailableTargetEntities:g=>n.filter(w=>w.name!==g),addJoinKeyGroup:g=>{const w=a.joins.find(f=>f.id===g);if(!w)return;const E=[...w.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];o(g,{joinKeyGroups:E})},updateGroupOperator:(g,w,E)=>{const f=a.joins.find(j=>j.id===g);if(!f)return;const M=[...f.joinKeyGroups];M[w]={...M[w],operator:E},o(g,{joinKeyGroups:M})},removeJoinKeyGroup:(g,w)=>{const E=a.joins.find(M=>M.id===g);if(!E)return;const f=[...E.joinKeyGroups];f.splice(w,1),o(g,{joinKeyGroups:f})},addJoinKey:(g,w)=>{const E=a.joins.find(D=>D.id===g);if(!E)return;const f=n.find(D=>D.name===E.source.name),M=n.find(D=>D.name===E.target.name),j=[...E.joinKeyGroups],I={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(f==null?void 0:f.name)||"",entityName:(f==null?void 0:f.name)||"",entityType:(f==null?void 0:f.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:"="};j[w]={...j[w],keys:[...j[w].keys,I]},o(g,{joinKeyGroups:j})},updateJoinKey:(g,w,E,f,M)=>{const j=a.joins.find(A=>A.id===g);if(!j)return;const I=n.find(A=>A.name===j.source.name),D=n.find(A=>A.name===j.target.name),P=[...j.joinKeyGroups],v=P[w].keys[E];f==="sourceColumnName"&&I?P[w].keys[E]={...v,source:{...v.source,name:M}}:f==="targetColumnName"&&D?P[w].keys[E]={...v,target:{...v.target,name:M}}:f==="operator"&&(P[w].keys[E]={...v,operator:M}),o(g,{joinKeyGroups:P})},removeJoinKey:(g,w,E)=>{const f=a.joins.find(j=>j.id===g);if(!f)return;const M=[...f.joinKeyGroups];M[w].keys.splice(E,1),o(g,{joinKeyGroups:M})},generateSQLPreview:()=>{const g=[...a.joins].sort((f,M)=>f.sequence-M.sequence),w=a.baseEntity;if(!w.name)return"SELECT * FROM table -- Please select a base entity";let E=`SELECT *
162
- FROM ${w.name}`;return g.forEach(f=>{const M=n.find(D=>D.name===f.target.name);if(!M)return;const j=f.joinKeyGroups.filter(D=>D.keys&&D.keys.length>0).map(D=>{const P=D.keys.filter(v=>{var A,S,R,F;return((A=v.source)==null?void 0:A.name)&&((S=v.target)==null?void 0:S.name)&&((R=v.source)==null?void 0:R.entityName)&&((F=v.target)==null?void 0:F.entityName)}).map(v=>`${v.source.entityName}.${v.source.name} ${v.operator} ${v.target.entityName}.${v.target.name}`);return P.length>1?`(${P.join(` ${D.operator} `)})`:P[0]}).filter(Boolean),I=j.length>1?j.join(" OR "):j[0]||"condition_here";E+=`
161
+ */const ta=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 Ws({storeValue:t,defaultValue:n="",onStoreUpdate:a,delay:r=300}){const[i,c]=I.useState(t??n),l=s.useDebounce(i,r),d=I.useRef(t),o=I.useRef(!1);I.useEffect(()=>{t!==d.current&&(c(t??n),d.current=t)},[t,n]),I.useEffect(()=>{o.current&&l!==d.current&&(a(l),d.current=l)},[l,a]);const x=I.useCallback(p=>{o.current=!0,c(p??n)},[n]);return{value:i,onChange:x}}function aa({initialJoinPlan:t,availableDataSources:n}){const[a,r]=I.useState(t),[i,c]=I.useState(new Set),l=()=>{const g=a.joins.length>0?Math.max(...a.joins.map(E=>E.sequence))+1:1,w={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:g,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,w]}),c(new Set([...i,w.id]))},d=g=>{r({...a,joins:a.joins.filter(w=>w.id!==g)}),c(new Set([...i].filter(w=>w!==g)))},o=(g,w)=>{var k,D,P,v,A;const E=a.joins.find(S=>S.id===g);if(!E)return;const f={...E,...w};if((k=f.source)!=null&&k.name&&((D=f.target)!=null&&D.name)&&f.source.name===f.target.name){s.ue.error("Self-joins are not yet supported",{description:`Joining ${f.source.name} to itself is not currently supported. Please select a different target table.`});return}const M=a.joins.filter(S=>{var R;return S.id!==g&&S.target.name===((R=f.target)==null?void 0:R.name)});if((P=f.target)!=null&&P.name&&M.length>0){s.ue.error("Duplicate join targets are not supported",{description:`The table ${f.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const j=a.joins.map(S=>S.id===g?f:S);if((v=f.source)!=null&&v.name&&((A=f.target)!=null&&A.name)&&f.joinKeyGroups[0].keys.length===0){const S=n.find(G=>{var V;return G.name===((V=f.source)==null?void 0:V.name)}),R=n.find(G=>{var V;return G.name===((V=f.target)==null?void 0:V.name)}),F={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:(R==null?void 0:R.name)||"",entityName:(R==null?void 0:R.name)||"",entityType:(R==null?void 0:R.type)||"table"},operator:"="},z=[...f.joinKeyGroups];z[0]={...z[0],keys:[F]},f.joinKeyGroups=z,j[j.findIndex(G=>G.id===g)]=f}r({...a,joins:j})};return{joinPlan:a,expandedJoins:i,setJoinPlan:r,addJoin:l,removeJoin:d,updateJoin:o,moveJoinUp:g=>{const w=a.joins.findIndex(E=>E.id===g);if(w>0){const E=[...a.joins],f={...E[w]},M={...E[w-1]};E[w]=M,E[w-1]=f,E.forEach((k,D)=>{k.sequence=D+1});const j={...a,joins:E};r(j)}},moveJoinDown:g=>{const w=a.joins.findIndex(E=>E.id===g);if(w<a.joins.length-1){const E=[...a.joins],f={...E[w]},M={...E[w+1]};E[w]=M,E[w+1]=f,E.forEach((k,D)=>{k.sequence=D+1});const j={...a,joins:E};r(j)}},toggleJoinExpansion:g=>{const w=new Set(i);w.has(g)?w.delete(g):w.add(g),c(w)},getAvailableSourceEntities:g=>{if(a.joins.length===0)return n;const w=a.joins.findIndex(f=>f.id===g);if(w===0)return n.filter(f=>f.name===a.baseEntity.name);const E=new Set;return a.baseEntity.name&&E.add(a.baseEntity.name),a.joins.slice(0,w).forEach(f=>{E.add(f.source.name),E.add(f.target.name)}),n.filter(f=>E.has(f.name))},getAvailableTargetEntities:g=>n.filter(w=>w.name!==g),addJoinKeyGroup:g=>{const w=a.joins.find(f=>f.id===g);if(!w)return;const E=[...w.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];o(g,{joinKeyGroups:E})},updateGroupOperator:(g,w,E)=>{const f=a.joins.find(j=>j.id===g);if(!f)return;const M=[...f.joinKeyGroups];M[w]={...M[w],operator:E},o(g,{joinKeyGroups:M})},removeJoinKeyGroup:(g,w)=>{const E=a.joins.find(M=>M.id===g);if(!E)return;const f=[...E.joinKeyGroups];f.splice(w,1),o(g,{joinKeyGroups:f})},addJoinKey:(g,w)=>{const E=a.joins.find(D=>D.id===g);if(!E)return;const f=n.find(D=>D.name===E.source.name),M=n.find(D=>D.name===E.target.name),j=[...E.joinKeyGroups],k={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(f==null?void 0:f.name)||"",entityName:(f==null?void 0:f.name)||"",entityType:(f==null?void 0:f.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:"="};j[w]={...j[w],keys:[...j[w].keys,k]},o(g,{joinKeyGroups:j})},updateJoinKey:(g,w,E,f,M)=>{const j=a.joins.find(A=>A.id===g);if(!j)return;const k=n.find(A=>A.name===j.source.name),D=n.find(A=>A.name===j.target.name),P=[...j.joinKeyGroups],v=P[w].keys[E];f==="sourceColumnName"&&k?P[w].keys[E]={...v,source:{...v.source,name:M}}:f==="targetColumnName"&&D?P[w].keys[E]={...v,target:{...v.target,name:M}}:f==="operator"&&(P[w].keys[E]={...v,operator:M}),o(g,{joinKeyGroups:P})},removeJoinKey:(g,w,E)=>{const f=a.joins.find(j=>j.id===g);if(!f)return;const M=[...f.joinKeyGroups];M[w].keys.splice(E,1),o(g,{joinKeyGroups:M})},generateSQLPreview:()=>{const g=[...a.joins].sort((f,M)=>f.sequence-M.sequence),w=a.baseEntity;if(!w.name)return"SELECT * FROM table -- Please select a base entity";let E=`SELECT *
162
+ FROM ${w.name}`;return g.forEach(f=>{const M=n.find(D=>D.name===f.target.name);if(!M)return;const j=f.joinKeyGroups.filter(D=>D.keys&&D.keys.length>0).map(D=>{const P=D.keys.filter(v=>{var A,S,R,F;return((A=v.source)==null?void 0:A.name)&&((S=v.target)==null?void 0:S.name)&&((R=v.source)==null?void 0:R.entityName)&&((F=v.target)==null?void 0:F.entityName)}).map(v=>`${v.source.entityName}.${v.source.name} ${v.operator} ${v.target.entityName}.${v.target.name}`);return P.length>1?`(${P.join(` ${D.operator} `)})`:P[0]}).filter(Boolean),k=j.length>1?j.join(" OR "):j[0]||"condition_here";E+=`
163
163
  ${f.joinType} JOIN ${M.name}
164
- ON ${I}`}),E},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(f=>!f.source.name||!f.target.name)||a.joins.some(f=>f.joinKeyGroups.some(M=>M.keys.length===0))||a.joins.some(f=>f.joinKeyGroups.some(M=>M.keys.some(j=>!j.source.name||!j.target.name||!j.operator))))}}function na({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:i}){const{setCardConfig:c}=s.useEditorActions();s.useEditorStore(I=>I.card.config);const{columnGroups:l}=s.useColumns(),d=l.filter(I=>I.entityName!==s.CALCULATED_FIELDS_GROUP_NAME),{joinPlan:o,expandedJoins:x,setJoinPlan:p,addJoin:m,removeJoin:u,updateJoin:N,moveJoinUp:b,moveJoinDown:h,toggleJoinExpansion:y,getAvailableSourceEntities:T,getAvailableTargetEntities:C,addJoinKeyGroup:B,updateGroupOperator:O,removeJoinKeyGroup:L,addJoinKey:g,updateJoinKey:w,removeJoinKey:E,generateSQLPreview:f,isValidConfiguration:M}=aa({initialJoinPlan:t,availableDataSources:n}),j=I=>{const D=d.find(P=>P.entityName===I);return(D==null?void 0:D.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:o.baseEntity.name,onValueChange:I=>{const D=n.find(P=>P.name===I);p({...o,baseEntity:{connectionId:(D==null?void 0:D.connectionId)||"",connectionType:(D==null?void 0:D.connectionType)||"none",type:(D==null?void 0:D.type)||"table",name:I,database:D==null?void 0:D.database,schema:D==null?void 0:D.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:n.map(I=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:I.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:I.type}),I.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},I.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:f()})]}),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 (",o.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:m,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),o.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:o.joins.map(I=>{const D=n.find(A=>A.name===I.source.name),P=n.find(A=>A.name===I.target.name),v=x.has(I.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:I.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",I.sequence,D&&P&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",D.name," → ",P.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>b(I.id),disabled:I.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(I.id),disabled:I.sequence===o.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>y(I.id),children:v?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:()=>u(I.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),v&&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:I.source.name,onValueChange:A=>{const S=n.find(R=>R.name===A);N(I.id,{source:{connectionId:(S==null?void 0:S.connectionId)||"",connectionType:(S==null?void 0:S.connectionType)||"none",type:(S==null?void 0:S.type)||"table",name:A,database:S==null?void 0:S.database,schema:S==null?void 0:S.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:T(I.id).map(A=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:A.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:A.type}),A.name]})},A.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:I.joinType,onValueChange:A=>N(I.id,{joinType:A}),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:I.target.name,onValueChange:A=>{const S=n.find(R=>R.name===A);N(I.id,{target:{connectionId:(S==null?void 0:S.connectionId)||"",connectionType:(S==null?void 0:S.connectionType)||"none",type:(S==null?void 0:S.type)||"table",name:A,database:S==null?void 0:S.database,schema:S==null?void 0:S.schema}})},disabled:!I.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:I.source.name?C(I.source.name).map(A=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:A.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:A.type}),A.name,A.name===I.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},A.name)):[]})]})]})]}),I.source.name&&I.target.name&&D&&P&&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:()=>B(I.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),I.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:I.joinKeyGroups.map((A,S)=>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 ",S+1]}),S>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:A.operator,onValueChange:R=>O(I.id,S,R),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:()=>L(I.id,S),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[A.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:A.keys.map((R,F)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[F>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:A.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:R.source.name,onValueChange:z=>w(I.id,S,F,"sourceColumnName",z),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:j(I.source.name).map(z=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:z.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:z.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:z.dataType})]})},z.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:R.operator,onValueChange:z=>w(I.id,S,F,"operator",z),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:R.target.name,onValueChange:z=>w(I.id,S,F,"targetColumnName",z),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:j(I.target.name).map(z=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:z.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:z.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:z.dataType})]})},z.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>E(I.id,S,F),children:e.jsx(s.X,{className:"size-3.5"})})]},R.id||F))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>g(I.id,S),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},A.id))})]})]})]},I.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),i()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:i,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>a(o),disabled:!M(),children:"Save"})]})]})}function Xs({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:i,onRemove:c,onSave:l,onCancel:d}){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(na,{joinPlan:r,availableDataSources:i,onSave:l,onCancel:d,onRemove:c})]}),t]})}function ra({joins:t,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"my-2 max-h-[400px] divide-y divide-border overflow-y-auto",children:[t.length>0&&e.jsxs("div",{className:"px-4 py-2",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 i=[...t].sort((l,d)=>l.sequence-d.sequence),c=a.find(l=>l.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:c==null?void 0:c.type}),e.jsx("span",{className:"text-xs font-medium",children:c==null?void 0:c.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),i.map(l=>{const d=a.find(o=>o.name===l.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:l.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:d==null?void 0:d.type}),e.jsx("span",{className:"text-xs font-medium",children:d==null?void 0:d.name})]})]},l.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((i,c)=>i.sequence-c.sequence).map((i,c)=>{const l=a.find(x=>x.name===i.source.name),d=a.find(x=>x.name===i.target.name),o=i.joinKeyGroups.reduce((x,p)=>x+p.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:c+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:i.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:[l==null?void 0:l.name," → ",d==null?void 0:d.name]})]},i.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 Is({open:t,onOpenChange:n,variant:a="button"}={}){var C,B;const r=s.useEditorStore(O=>O.card),{autoJoinMetadata:i}=s.useDashboardCardQuery(r),c=s.useEditorStore(O=>O.actions.updateCardConfig),l=((C=r==null?void 0:r.config)==null?void 0:C.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[d,o]=k.useState(!1),x=t!==void 0,p=x?t:d,m=x?n:o,u=((B=r==null?void 0:r.dataSource)==null?void 0:B.selectedEntities)||[],N=O=>{c(r.id,{...r==null?void 0:r.config,joinPlan:O}),m(!1)},b=()=>{c(r.id,{...r==null?void 0:r.config,joinPlan:void 0})},h=()=>{m(!1)},y=()=>{const O=[...l.joins].sort((w,E)=>w.sequence-E.sequence),L=l.baseEntity;if(!L.name)return"SELECT * FROM table -- Please select a base entity";let g=`SELECT *
165
- FROM ${L.name}`;return O.forEach(w=>{const E=u.find(j=>j.name===w.target.name);if(!E)return;const f=w.joinKeyGroups.filter(j=>j.keys&&j.keys.length>0).map(j=>{const I=j.keys.filter(D=>{var P,v,A,S;return((P=D.source)==null?void 0:P.name)&&((v=D.target)==null?void 0:v.name)&&((A=D.source)==null?void 0:A.entityName)&&((S=D.target)==null?void 0:S.entityName)}).map(D=>`${D.source.entityName}.${D.source.name} ${D.operator} ${D.target.entityName}.${D.target.name}`);return I.length>1?`(${I.join(` ${j.operator} `)})`:I[0]}).filter(Boolean),M=f.length>1?f.join(" OR "):f[0]||"condition_here";g+=`
164
+ ON ${k}`}),E},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(f=>!f.source.name||!f.target.name)||a.joins.some(f=>f.joinKeyGroups.some(M=>M.keys.length===0))||a.joins.some(f=>f.joinKeyGroups.some(M=>M.keys.some(j=>!j.source.name||!j.target.name||!j.operator))))}}function na({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:i}){const{setCardConfig:c}=s.useEditorActions();s.useEditorStore(k=>k.card.config);const{columnGroups:l}=s.useColumns(),d=l.filter(k=>k.entityName!==s.CALCULATED_FIELDS_GROUP_NAME),{joinPlan:o,expandedJoins:x,setJoinPlan:p,addJoin:m,removeJoin:u,updateJoin:N,moveJoinUp:b,moveJoinDown:h,toggleJoinExpansion:y,getAvailableSourceEntities:T,getAvailableTargetEntities:C,addJoinKeyGroup:B,updateGroupOperator:O,removeJoinKeyGroup:L,addJoinKey:g,updateJoinKey:w,removeJoinKey:E,generateSQLPreview:f,isValidConfiguration:M}=aa({initialJoinPlan:t,availableDataSources:n}),j=k=>{const D=d.find(P=>P.entityName===k);return(D==null?void 0:D.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:o.baseEntity.name,onValueChange:k=>{const D=n.find(P=>P.name===k);p({...o,baseEntity:{connectionId:(D==null?void 0:D.connectionId)||"",connectionType:(D==null?void 0:D.connectionType)||"none",type:(D==null?void 0:D.type)||"table",name:k,database:D==null?void 0:D.database,schema:D==null?void 0:D.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:n.map(k=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:k.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:k.type}),k.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},k.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:f()})]}),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 (",o.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:m,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),o.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:o.joins.map(k=>{const D=n.find(A=>A.name===k.source.name),P=n.find(A=>A.name===k.target.name),v=x.has(k.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:k.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",k.sequence,D&&P&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",D.name," → ",P.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>b(k.id),disabled:k.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(k.id),disabled:k.sequence===o.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>y(k.id),children:v?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:()=>u(k.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),v&&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:k.source.name,onValueChange:A=>{const S=n.find(R=>R.name===A);N(k.id,{source:{connectionId:(S==null?void 0:S.connectionId)||"",connectionType:(S==null?void 0:S.connectionType)||"none",type:(S==null?void 0:S.type)||"table",name:A,database:S==null?void 0:S.database,schema:S==null?void 0:S.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:T(k.id).map(A=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:A.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:A.type}),A.name]})},A.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:k.joinType,onValueChange:A=>N(k.id,{joinType:A}),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:k.target.name,onValueChange:A=>{const S=n.find(R=>R.name===A);N(k.id,{target:{connectionId:(S==null?void 0:S.connectionId)||"",connectionType:(S==null?void 0:S.connectionType)||"none",type:(S==null?void 0:S.type)||"table",name:A,database:S==null?void 0:S.database,schema:S==null?void 0:S.schema}})},disabled:!k.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:k.source.name?C(k.source.name).map(A=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:A.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:A.type}),A.name,A.name===k.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},A.name)):[]})]})]})]}),k.source.name&&k.target.name&&D&&P&&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:()=>B(k.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),k.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:k.joinKeyGroups.map((A,S)=>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 ",S+1]}),S>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:A.operator,onValueChange:R=>O(k.id,S,R),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:()=>L(k.id,S),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[A.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:A.keys.map((R,F)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[F>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:A.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:R.source.name,onValueChange:z=>w(k.id,S,F,"sourceColumnName",z),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:j(k.source.name).map(z=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:z.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:z.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:z.dataType})]})},z.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:R.operator,onValueChange:z=>w(k.id,S,F,"operator",z),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:R.target.name,onValueChange:z=>w(k.id,S,F,"targetColumnName",z),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:j(k.target.name).map(z=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:z.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:z.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:z.dataType})]})},z.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>E(k.id,S,F),children:e.jsx(s.X,{className:"size-3.5"})})]},R.id||F))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>g(k.id,S),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},A.id))})]})]})]},k.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),i()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:i,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>a(o),disabled:!M(),children:"Save"})]})]})}function Xs({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:i,onRemove:c,onSave:l,onCancel:d}){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(na,{joinPlan:r,availableDataSources:i,onSave:l,onCancel:d,onRemove:c})]}),t]})}function ra({joins:t,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"my-2 max-h-[400px] divide-y divide-border overflow-y-auto",children:[t.length>0&&e.jsxs("div",{className:"px-4 py-2",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 i=[...t].sort((l,d)=>l.sequence-d.sequence),c=a.find(l=>l.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:c==null?void 0:c.type}),e.jsx("span",{className:"text-xs font-medium",children:c==null?void 0:c.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),i.map(l=>{const d=a.find(o=>o.name===l.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:l.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:d==null?void 0:d.type}),e.jsx("span",{className:"text-xs font-medium",children:d==null?void 0:d.name})]})]},l.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((i,c)=>i.sequence-c.sequence).map((i,c)=>{const l=a.find(x=>x.name===i.source.name),d=a.find(x=>x.name===i.target.name),o=i.joinKeyGroups.reduce((x,p)=>x+p.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:c+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:i.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:[l==null?void 0:l.name," → ",d==null?void 0:d.name]})]},i.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 ks({open:t,onOpenChange:n,variant:a="button"}={}){var C,B;const r=s.useEditorStore(O=>O.card),{autoJoinMetadata:i}=s.useDashboardCardQuery(r),c=s.useEditorStore(O=>O.actions.updateCardConfig),l=((C=r==null?void 0:r.config)==null?void 0:C.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[d,o]=I.useState(!1),x=t!==void 0,p=x?t:d,m=x?n:o,u=((B=r==null?void 0:r.dataSource)==null?void 0:B.selectedEntities)||[],N=O=>{c(r.id,{...r==null?void 0:r.config,joinPlan:O}),m(!1)},b=()=>{c(r.id,{...r==null?void 0:r.config,joinPlan:void 0})},h=()=>{m(!1)},y=()=>{const O=[...l.joins].sort((w,E)=>w.sequence-E.sequence),L=l.baseEntity;if(!L.name)return"SELECT * FROM table -- Please select a base entity";let g=`SELECT *
165
+ FROM ${L.name}`;return O.forEach(w=>{const E=u.find(j=>j.name===w.target.name);if(!E)return;const f=w.joinKeyGroups.filter(j=>j.keys&&j.keys.length>0).map(j=>{const k=j.keys.filter(D=>{var P,v,A,S;return((P=D.source)==null?void 0:P.name)&&((v=D.target)==null?void 0:v.name)&&((A=D.source)==null?void 0:A.entityName)&&((S=D.target)==null?void 0:S.entityName)}).map(D=>`${D.source.entityName}.${D.source.name} ${D.operator} ${D.target.entityName}.${D.target.name}`);return k.length>1?`(${k.join(` ${j.operator} `)})`:k[0]}).filter(Boolean),M=f.length>1?f.join(" OR "):f[0]||"condition_here";g+=`
166
166
  ${w.joinType} JOIN ${E.name}
167
- ON ${M}`}),g};if(u.length<2)return null;const T=l.joins.length>0&&e.jsx(s.TooltipContent,{side:"bottom",className:"ml-4 max-w-md overflow-hidden p-0",children:e.jsx(ra,{joins:l.joins,baseEntityId:l.baseEntity.name,availableDataSources:u,generateSQLPreview:y})});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(),m(!0)},children:[e.jsx(s.Link,{className:"h-3 w-3"}),l.joins.length]}):e.jsxs(s.Button,{onClick:()=>m(!0),variant:"outline",className:"w-full bg-muted/50",children:[e.jsx(s.Link,{className:"mr-2 h-3.5 w-3.5"}),l.joins.length===0?"Configure Joins":l.joins.length===1?"Join":"Joins",l.joins.length>0&&e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full border bg-muted-foreground px-1.5 text-xs font-medium text-background",children:l.joins.length}),(i==null?void 0:i.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"]})]})}),T]})}),e.jsx(Xs,{open:p,onOpenChange:m,joinPlan:l,availableDataSources:u,onSave:N,onCancel:h,onRemove:b,children:e.jsx("div",{})})]})}function la({open:t,onOpenChange:n}){const[a,r]=k.useState([]),{updateDataSource:i}=s.useEditorActions(),c=s.useDashboardStore(b=>b.dashboard.aiContext),l=(c==null?void 0:c.selectedEntities)||[];k.useEffect(()=>{t&&r([])},[t]);const d=b=>{r(h=>h.some(T=>T.name===b.name&&T.type===b.type)?h.filter(T=>!(T.name===b.name&&T.type===b.type)):[...h,b])},o=()=>{r([...l])},x=()=>{r([])},p=()=>{if(a.length===0)return;const b=a[0],h=b.connectionId||"",y=b.connectionType||"",C=a.some(O=>O.type==="dataset")?"semanticDomain":"database";i({connectionId:h,connectionType:y,mode:C,selectedEntities:a}),n(!1)},m=b=>"label"in b&&b.label?b.label:b.name,u=b=>{if("description"in b&&b.description)return b.description;const h=[];return b.database&&h.push(b.database),b.schema&&h.push(b.schema),b.name&&h.push(b.name),h.join(".")},N=b=>a.some(h=>h.name===b.name&&h.type===b.type);return l.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===l.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:x,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[a.length," of ",l.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:l.map((b,h)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",N(b)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:N(b),onCheckedChange:()=>d(b)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:s.getEntityIcon(b.type)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:m(b)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:u(b)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:b.type})]},`${b.type}-${b.name}-${h}`))})})]}),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:p,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function As({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,i)=>{const c=s.getEntityDetails(r),l=c.find(o=>o.label==="Description"&&o.value),d=c.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)}),l&&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:l.value})]}),d.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:d.map((o,x)=>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})]},x))})]},`remaining-${r.type}-${r.name}-${i}`)})})]})})}function Zs(t,n){const[a,r]=k.useState(()=>{const i=localStorage.getItem(t);return i?JSON.parse(i):n});return k.useEffect(()=>{localStorage.setItem(t,JSON.stringify(a))},[a,t]),[a,r]}function et({isVisible:t}){var h,y;const n=s.useEditorStore(T=>T.isDevMode);s.useSyncLegacyEditorState();const[a,r]=k.useState(!1),[i,c]=k.useState(!1),[l,d]=Zs("semaphor:data-source-collapsed",!1),o=s.useEditorStore(T=>T.card.dataSource),x=s.useEditorStore(T=>{var C,B;return(B=(C=T.card)==null?void 0:C.config)==null?void 0:B.joinPlan}),{updateDataSource:p}=s.useEditorActions(),m=((h=o==null?void 0:o.selectedEntities)==null?void 0:h.length)||0,u=((y=x==null?void 0:x.joins)==null?void 0:y.length)||0,b={...{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:[m===0&&u===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-4",l?"pb-0":"pb-3"),onClick:()=>d(!l),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Data Source"}),l&&e.jsxs("div",{className:"flex items-center gap-1.5",onClick:T=>T.stopPropagation(),children:[m>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"}),m]})}),e.jsx(As,{entities:b.selectedEntities,title:`${m} selected ${m===1?"entity":"entities"}`})]})}),u>0&&!n&&e.jsx(Is,{variant:"badge"})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:T=>{T.stopPropagation(),d(!l)},children:l?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden transition-all duration-200 ease-in-out",l?"max-h-0 opacity-0":"max-h-96 opacity-100"),children:[e.jsx("div",{className:"px-6",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"}),m===1?"Dataset":"Datasets",e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full border bg-muted-foreground px-1.5 text-xs font-medium text-background",children:m})]})}),e.jsx(As,{entities:b.selectedEntities,title:`${m} selected ${m===1?"entity":"entities"}`})]})})}),!n&&m>1&&e.jsx("div",{className:"mt-3 px-6",children:e.jsx(Is,{})})]})]}),e.jsx(s.FieldsSection,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(o==null?void 0:o.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:b}),e.jsx(la,{open:i,onOpenChange:c})]})}function oa(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 st(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(h=>h.theme),r=s.useEditorStore(h=>h.frame),i=s.useEditorStore(h=>h.card),c=s.useEditorStore(h=>h.activeTabCardId),l=s.Le(),{refetch:d}=s.useDashboardCardQuery(i),{updateCardTab:o,setRunSql:x}=s.useEditorActions(),p=k.useRef(void 0),m=k.useRef({}),u=r.cards.find(h=>h.id===c),N=k.useCallback(()=>{let h="";return t==="python"&&(h=(u==null?void 0:u.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(h=(u==null?void 0:u.sql)||""),h},[t,u]);k.useEffect(()=>{if(c&&i.id&&i.id!==c){if(p.current&&l){const h=p.current.getModel();h&&(m.current[i.id]=h);let y=m.current[c];if(!y){const T=N();y=l.editor.createModel(T,t),m.current[c]=y}p.current.setModel(y)}o(c,i),x(!0)}},[c,i,o,l,x,t,N]),k.useEffect(()=>{if(!l)return;const h=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",y=a==="system"?h:a;l.editor.defineTheme("default",{base:y==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":y==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),l.editor.setTheme("default")},[n,a,l]),k.useEffect(()=>{const h=p.current;h&&l&&i&&h.addCommand(l.KeyMod.Shift|l.KeyCode.Enter,function(){return d(),!1})},[l,d,i]);function b(h,y){if(p.current=h,!m.current[i.id]){const T=h.getModel(),C=N();m.current[i.id]=T||(y==null?void 0:y.editor.createModel(C,t))||h.getModel()}h.setModel(m.current[i.id])}return{handleEditorDidMount:b}}const ia=300;function ca(){const t=s.useEditorStore(p=>p.card.sql),n=s.useEditorStore(p=>p.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:i}=st("sql"),c=k.useRef(n);c.current=n;const l=k.useCallback(p=>{a(p)},[a]),{value:d,onChange:o}=Ws({storeValue:t,defaultValue:"",onStoreUpdate:l,delay:ia});function x(p){o(p),s.isObjectEmpty(c.current)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!d&&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:x,value:d,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:i})]})}const da=300;function ua(){const t=s.useEditorStore(c=>c.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=st("python"),{value:r,onChange:i}=Ws({storeValue:t,defaultValue:s.PYTHON_DEFAULT_CODE,onStoreUpdate:n,delay:da});return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:i,value:r,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:a})}function tt({sql:t,showCardDetails:n=!1,className:a}){const[r,i]=k.useState(!1),c=s.useEditorStore(N=>N.card),l=s.useEditorStore(N=>N.frame),d=s.useEditorStore(N=>N.isDevMode),o=s.useDashboardStore(N=>N.selectedSheetId),x=s.useDashboardStore(N=>{var b;return(b=N.dashboard)==null?void 0:b.id}),{switchEditorMode:p,setRunSql:m}=s.useEditorActions(),u=()=>{p("dev",{sqlToLoad:t}),setTimeout(()=>{m(!0)},100)};return e.jsxs("div",{className:s.cn("flex min-h-0 flex-1 flex-col",a),children:[!d&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsxs(s.Button,{onClick:u,variant:"secondary",size:"sm",children:[e.jsx(Js,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),n&&e.jsxs(s.Button,{onClick:()=>i(!r),variant:"outline",size:"sm",children:[e.jsx(s.Info,{className:"mr-2 h-4 w-4"}),"Card Details"]})]}),r&&n&&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:()=>i(!1),children:e.jsx(ye.CircleX,{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:"font-mono text-xs",children:c.id||"N/A"})]}),e.jsx(s.CopyButton,{text:c.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:"font-mono text-xs",children:l.id||"N/A"})]}),e.jsx(s.CopyButton,{text:l.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:"font-mono text-xs",children:o||"N/A"})]}),e.jsx(s.CopyButton,{text:o||"",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:"font-mono text-xs",children:x||"N/A"})]}),e.jsx(s.CopyButton,{text:x||"",className:"h-6 w-6"})]})]})]})}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto text-xs leading-relaxed text-foreground/80",children: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"})]})})})]})}function ma(){var se,ne;const t=s.useQueryClient(),{isConsoleMode:n}=s.useDashboardPreferences(),[a,r]=k.useState(!1),i=s.useEditorStore(_=>_.frame),c=s.useEditorStore(_=>_.card);s.useEditorStore(_=>_.isShowingVisual),s.useEditorStore(_=>_.selectedConnectionId),s.useEditorStore(_=>_.tempQueryData),s.useEditorStore(_=>_.selectedDatabaseName),s.useEditorStore(_=>_.selectedDatamodelId),s.useEditorStore(_=>_.selectedSchemaName);const l=s.useEditorStore(_=>_.showAIDialog);s.useEditorStore(_=>_.selectedTableName),s.useEditorStore(_=>{var W;return(W=_==null?void 0:_.card)==null?void 0:W.sql}),s.useEditorStore(_=>{var W;return(W=_==null?void 0:_.card)==null?void 0:W.python});const{cardFilterValues:d}=s.useCardFilterValues((c==null?void 0:c.id)??""),o=s.useDashboardStore(_=>_.inlineFilterValuesMap[(c==null?void 0:c.id)??""]),x=k.useMemo(()=>s.findCustomVisualConfigCard(i,c),[i,c]),{manifest:p}=s.useCustomVisual(((se=x==null?void 0:x.customCardPreferences)==null?void 0:se.url)||""),m=k.useMemo(()=>{var _;return(_=p==null?void 0:p.visuals)==null?void 0:_.find(W=>{var le;return W.name===((le=x==null?void 0:x.customCardPreferences)==null?void 0:le.componentName)})},[p,(ne=x==null?void 0:x.customCardPreferences)==null?void 0:ne.componentName]),u=s.resolveMultiInputType(x,m),N=k.useMemo(()=>s.getCustomVisualInputCards({frame:i,configCard:x,isMultiInputVisual:u==="multiple"}),[i,x,u]),b=k.useMemo(()=>{const _=N.findIndex(W=>(W==null?void 0:W.id)===(c==null?void 0:c.id));return _<0?-1:s.getSlotIndexForCard(c,_)},[N,c]),h=k.useMemo(()=>!x||u!=="multiple"||b<0?c.type:s.getEffectiveCardTypeForSlot(c,b,m==null?void 0:m.slots)??c.type,[x,u,b,c,m==null?void 0:m.slots]),y=k.useMemo(()=>h!==c.type?{...c,type:h}:c,[c,h]),T=k.useRef(!0),{setCardCustomCfg:C,setQueryResultColumns:B,setCardSql:O,setTempQueryData:L,setPythonStdOut:g,setCardPreferences:w,setCardType:E,setCardPython:f,setShowAIDialog:M,setCard:j,updateCardInFrame:I}=s.useEditorActions();s.useEditorStore(_=>_.onSave),s.useEditorStore(_=>_.onClose),s.useEditorStore(_=>_.actions.setSqlGen);const D=s.useEditorStore(_=>_.runSql),P=s.useEditorStore(_=>_.actions.setRunSql),v=s.useEditorStore(_=>_.actions.setIsSqlRunning),{data:A,isLoading:S,isFetching:R,isSuccess:F,isError:z,error:G,errorSql:V,queryKey:U,refetch:Q,errorMessage:J}=s.useDashboardCardQuery(y);k.useEffect(()=>{if(A&&(A.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),g((A==null?void 0:A.output)||""),A.records.length>0)){const{dimensionKeys:_}=s.getKeys(A.records);B(_)}},[A,B,g]),k.useEffect(()=>{(S||R)&&v(!0),(z||F)&&v(!1),z&&(B([]),g(""))},[S,R,A,g,z,F,v,B,G]),k.useEffect(()=>{D&&(t.getQueryData(U)||Q(),P(!1))},[D,Q,P,U,t]);const Z=k.useRef(Q);Z.current=Q,k.useEffect(()=>{if(T.current){T.current=!1;return}Z.current()},[o]);function q(){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(ca,{})}),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(ua,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function Y(){var _,W,le,he,$,H;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:S||R,onClick:()=>{Q()},className:"h-8 shrink-0",size:"sm",children:[S||R?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"]}),(A==null?void 0:A.sql)&&!J&&e.jsxs(s.HoverCard,{openDelay:300,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-4 w-4 shrink-0 cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.HoverCardContent,{align:"start",className:"w-[500px]",children:e.jsx(tt,{sql:A.sql})})]}),e.jsx(ye.EditorClearButton,{}),e.jsxs(s.Toggle,{pressed:a,onPressedChange:ae=>r(ae),className:"h-8",size:"sm",variant:"outline",children:[e.jsx(oa,{className:"mr-2 size-4 text-foreground/70"}),"Python"]}),!l&&e.jsxs("button",{disabled:l,onClick:()=>{M(!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:((W=(_=c.preferences)==null?void 0:_.tablePrefs)==null?void 0:W.enableDevModePagination)??!1,onCheckedChange:ae=>{var ie;w({...c.preferences,tablePrefs:{...(ie=c.preferences)==null?void 0:ie.tablePrefs,enableDevModePagination:ae}})}}),e.jsx(s.Label,{htmlFor:"pagination",className:"cursor-pointer text-sm",children:"Paginate"}),((he=(le=c.preferences)==null?void 0:le.tablePrefs)==null?void 0:he.enableDevModePagination)&&e.jsxs(s.Select,{value:String(((H=($=c.preferences)==null?void 0:$.tablePrefs)==null?void 0:H.pageSize)||50),onValueChange:ae=>{var je,ve,Ne;const ie=Number(ae),ge={...c,preferences:{...c.preferences,tablePrefs:{...(je=c.preferences)==null?void 0:je.tablePrefs,pageSize:ie}},paginationConfig:{page:1,pageSize:ie}};j(ge),I(ge),c.sql&&((Ne=(ve=c.preferences)==null?void 0:ve.tablePrefs)!=null&&Ne.enableDevModePagination)&&P(!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"})]})]})]}),d&&d.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:d.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(d,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:q()}),Y()]})}const xa=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:s.Grid3x3},{value:"detailTable",label:"Detail",icon:s.List}];function ha({className:t}){const n=s.useEditorStore(m=>m.card),a=s.useEditorStore(m=>m.frame),r=ye.useEffectiveEditorCardType(),{setCard:i,updateCardInFrame:c}=s.useEditorActions(),l=["table","aggregateTable","pivotTable","detailTable"].includes(r),d=s.hasValidCardConfig(n.config),o=s.isCustomVisualConfigCard(n,a.cards);if(!l||!d||o)return null;const x=m=>{if(o)return;const u=m,N=n.config??{},b=p(r,u,N),h={...n,type:u,config:b};i(h),c(h)},p=(m,u,N)=>{var h;if(u==="detailTable"){const y=O=>O==null?void 0:O.toLowerCase().replace(/\s+/g,"").trim(),T=(O,L)=>{const g=[y(O.label),y(O.qualifiedFieldName),y(O.name)].filter(Boolean),w=[y(L.label),y(L.qualifiedFieldName),y(L.name)].filter(Boolean);return g.some(E=>w.includes(E))},C=(N.groupByColumns||[]).map(O=>({...O,role:"detail"})),B=((h=N.sortByColumns)==null?void 0:h.filter(O=>C.some(L=>T(O,L))))??[];return{...N,detailTableBackup:{groupByColumns:N.groupByColumns,metricColumns:N.metricColumns,pivotByColumns:N.pivotByColumns,sortByColumns:N.sortByColumns,rowAggregates:N.rowAggregates,columnAggregates:N.columnAggregates,comparisonType:N.comparisonType},detailColumns:C,groupByColumns:[],metricColumns:[],pivotByColumns:[],sortByColumns:B,rowAggregates:[],columnAggregates:[],comparisonType:"none"}}let b=N;if(m==="detailTable")if(N.detailTableBackup)b={...N,...N.detailTableBackup,detailColumns:[],detailTableBackup:void 0};else{const y=(N.detailColumns||[]).map(T=>({...T,role:"groupby"}));b={...N,groupByColumns:y,detailColumns:[]}}return u==="aggregateTable"?{...b,pivotByColumns:[]}:b};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:r,onValueChange:x,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:xa.map(m=>{const u=m.icon,N=r===m.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:m.value,id:`table-type-${m.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${m.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all",N?"bg-muted text-foreground shadow-sm":"text-muted-foreground hover:bg-muted/50"),children:[e.jsx(u,{className:"h-3.5 w-3.5"}),m.label]})]},m.value)})})})}function pa({type:t,isLinked:n,className:a}){const r=s.useDashboardStore(u=>u.selectedFrameId),i=s.useManagementStore(u=>u.selectedVisual),c=s.useEditorStore(u=>u.frame);let l;if(t)l=t;else if(n!==void 0)l=n?"linked":"library";else if(!!!(c!=null&&c.visualId||i!=null&&i.id)&&r)l="local";else if(i&&!r)l="library";else if(c!=null&&c.visualId&&r)l="linked";else if(i!=null&&i.id&&r)l="library";else return null;if(l==="local")return null;const d={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."},x={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"},p={linked:"fill-purple-50 dark:fill-purple-950",library:"fill-blue-50 dark:fill-blue-950"},m={linked:e.jsx(Kt,{className:"h-3.5 w-3.5"}),library:e.jsx(qt,{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",d[l],a),children:m[l]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:s.cn("max-w-xs",x[l]),children:[e.jsx(s.TooltipArrow,{className:p[l]}),e.jsx("p",{children:o[l]})]})]})})}function ls({error:t,errorSql:n,errorTitle:a="Unable to load data",onOpenInEditor:r,onDebugWithAssistant:i,onSendFeedback:c,showFeedbackButton:l=!0,className:d}){const[o,x]=k.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-border bg-muted/40 p-4",d),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-amber-500/10 dark:bg-amber-500/20",children:e.jsx(s.TriangleAlert,{className:"h-4 w-4 text-amber-600 dark:text-amber-500"})}),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-foreground",children:a}),e.jsxs("div",{className:"relative rounded-md border border-border bg-background p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 z-10 h-6 w-6"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"break-all font-mono text-xs text-muted-foreground",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n&&e.jsx(s.Collapsible,{open:o,onOpenChange:x,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:o?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),r&&n&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:r,children:[e.jsx(Js,{className:"mr-1.5 h-3.5 w-3.5"}),"Open in Editor"]}),l&&c&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:c,children:[e.jsx(s.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]}),i&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:i,children:[e.jsx(zt,{className:"mr-1.5 h-3.5 w-3.5"}),"Debug with Assistant"]})]}),n&&e.jsx(s.Collapsible,{open:o,onOpenChange:x,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:"Query"}),e.jsx(s.CopyButton,{text:n,className:"h-6 w-6"})]}),e.jsx("div",{className:"max-h-80 overflow-auto rounded-md border border-border bg-background p-2",children:e.jsx(s.CodeHighlighter,{code:n,language:"sql"})})]})})})]})]})})}function at(t,n){const a=s.useEditorStore(x=>x.card),r=s.useEditorStore(x=>x.isDevMode),{switchEditorMode:i,setRunSql:c,runAssistant:l}=s.useEditorActions();return{isDevMode:r,handleOpenInEditor:r?void 0:()=>{const x=n||a.sql||a.python||"";i("dev",{sqlToLoad:x}),setTimeout(()=>{c(!0)},100)},handleDebugWithAssistant:r?()=>{const x=`Can you help me debug this query?
167
+ ON ${M}`}),g};if(u.length<2)return null;const T=l.joins.length>0&&e.jsx(s.TooltipContent,{side:"bottom",className:"ml-4 max-w-md overflow-hidden p-0",children:e.jsx(ra,{joins:l.joins,baseEntityId:l.baseEntity.name,availableDataSources:u,generateSQLPreview:y})});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(),m(!0)},children:[e.jsx(s.Link,{className:"h-3 w-3"}),l.joins.length]}):e.jsxs(s.Button,{onClick:()=>m(!0),variant:"outline",className:"w-full bg-muted/50",children:[e.jsx(s.Link,{className:"mr-2 h-3.5 w-3.5"}),l.joins.length===0?"Configure Joins":l.joins.length===1?"Join":"Joins",l.joins.length>0&&e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full border bg-muted-foreground px-1.5 text-xs font-medium text-background",children:l.joins.length}),(i==null?void 0:i.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"]})]})}),T]})}),e.jsx(Xs,{open:p,onOpenChange:m,joinPlan:l,availableDataSources:u,onSave:N,onCancel:h,onRemove:b,children:e.jsx("div",{})})]})}function la({open:t,onOpenChange:n}){const[a,r]=I.useState([]),{updateDataSource:i}=s.useEditorActions(),c=s.useDashboardStore(b=>b.dashboard.aiContext),l=(c==null?void 0:c.selectedEntities)||[];I.useEffect(()=>{t&&r([])},[t]);const d=b=>{r(h=>h.some(T=>T.name===b.name&&T.type===b.type)?h.filter(T=>!(T.name===b.name&&T.type===b.type)):[...h,b])},o=()=>{r([...l])},x=()=>{r([])},p=()=>{if(a.length===0)return;const b=a[0],h=b.connectionId||"",y=b.connectionType||"",C=a.some(O=>O.type==="dataset")?"semanticDomain":"database";i({connectionId:h,connectionType:y,mode:C,selectedEntities:a}),n(!1)},m=b=>"label"in b&&b.label?b.label:b.name,u=b=>{if("description"in b&&b.description)return b.description;const h=[];return b.database&&h.push(b.database),b.schema&&h.push(b.schema),b.name&&h.push(b.name),h.join(".")},N=b=>a.some(h=>h.name===b.name&&h.type===b.type);return l.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===l.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:x,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[a.length," of ",l.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:l.map((b,h)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",N(b)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:N(b),onCheckedChange:()=>d(b)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:s.getEntityIcon(b.type)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:m(b)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:u(b)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:b.type})]},`${b.type}-${b.name}-${h}`))})})]}),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:p,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function As({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,i)=>{const c=s.getEntityDetails(r),l=c.find(o=>o.label==="Description"&&o.value),d=c.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)}),l&&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:l.value})]}),d.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:d.map((o,x)=>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})]},x))})]},`remaining-${r.type}-${r.name}-${i}`)})})]})})}function Zs(t,n){const[a,r]=I.useState(()=>{const i=localStorage.getItem(t);return i?JSON.parse(i):n});return I.useEffect(()=>{localStorage.setItem(t,JSON.stringify(a))},[a,t]),[a,r]}function et({isVisible:t}){var h,y;const n=s.useEditorStore(T=>T.isDevMode);s.useSyncLegacyEditorState();const[a,r]=I.useState(!1),[i,c]=I.useState(!1),[l,d]=Zs("semaphor:data-source-collapsed",!1),o=s.useEditorStore(T=>T.card.dataSource),x=s.useEditorStore(T=>{var C,B;return(B=(C=T.card)==null?void 0:C.config)==null?void 0:B.joinPlan}),{updateDataSource:p}=s.useEditorActions(),m=((h=o==null?void 0:o.selectedEntities)==null?void 0:h.length)||0,u=((y=x==null?void 0:x.joins)==null?void 0:y.length)||0,b={...{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:[m===0&&u===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-4",l?"pb-0":"pb-3"),onClick:()=>d(!l),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Data Source"}),l&&e.jsxs("div",{className:"flex items-center gap-1.5",onClick:T=>T.stopPropagation(),children:[m>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"}),m]})}),e.jsx(As,{entities:b.selectedEntities,title:`${m} selected ${m===1?"entity":"entities"}`})]})}),u>0&&!n&&e.jsx(ks,{variant:"badge"})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:T=>{T.stopPropagation(),d(!l)},children:l?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden transition-all duration-200 ease-in-out",l?"max-h-0 opacity-0":"max-h-96 opacity-100"),children:[e.jsx("div",{className:"px-6",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"}),m===1?"Dataset":"Datasets",e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full border bg-muted-foreground px-1.5 text-xs font-medium text-background",children:m})]})}),e.jsx(As,{entities:b.selectedEntities,title:`${m} selected ${m===1?"entity":"entities"}`})]})})}),!n&&m>1&&e.jsx("div",{className:"mt-3 px-6",children:e.jsx(ks,{})})]})]}),e.jsx(s.FieldsSection,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(o==null?void 0:o.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:b}),e.jsx(la,{open:i,onOpenChange:c})]})}function oa(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 st(t){const{theme:n}=s.useTheme(),a=s.useDashboardStore(h=>h.theme),r=s.useEditorStore(h=>h.frame),i=s.useEditorStore(h=>h.card),c=s.useEditorStore(h=>h.activeTabCardId),l=s.Le(),{refetch:d}=s.useDashboardCardQuery(i),{updateCardTab:o,setRunSql:x}=s.useEditorActions(),p=I.useRef(void 0),m=I.useRef({}),u=r.cards.find(h=>h.id===c),N=I.useCallback(()=>{let h="";return t==="python"&&(h=(u==null?void 0:u.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(h=(u==null?void 0:u.sql)||""),h},[t,u]);I.useEffect(()=>{if(c&&i.id&&i.id!==c){if(p.current&&l){const h=p.current.getModel();h&&(m.current[i.id]=h);let y=m.current[c];if(!y){const T=N();y=l.editor.createModel(T,t),m.current[c]=y}p.current.setModel(y)}o(c,i),x(!0)}},[c,i,o,l,x,t,N]),I.useEffect(()=>{if(!l)return;const h=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",y=a==="system"?h:a;l.editor.defineTheme("default",{base:y==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":y==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),l.editor.setTheme("default")},[n,a,l]),I.useEffect(()=>{const h=p.current;h&&l&&i&&h.addCommand(l.KeyMod.Shift|l.KeyCode.Enter,function(){return d(),!1})},[l,d,i]);function b(h,y){if(p.current=h,!m.current[i.id]){const T=h.getModel(),C=N();m.current[i.id]=T||(y==null?void 0:y.editor.createModel(C,t))||h.getModel()}h.setModel(m.current[i.id])}return{handleEditorDidMount:b}}const ia=300;function ca(){const t=s.useEditorStore(p=>p.card.sql),n=s.useEditorStore(p=>p.sqlGen),{setCardSql:a,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:i}=st("sql"),c=I.useRef(n);c.current=n;const l=I.useCallback(p=>{a(p)},[a]),{value:d,onChange:o}=Ws({storeValue:t,defaultValue:"",onStoreUpdate:l,delay:ia});function x(p){o(p),s.isObjectEmpty(c.current)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!d&&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:x,value:d,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:i})]})}const da=300;function ua(){const t=s.useEditorStore(c=>c.card.python),{setCardPython:n}=s.useEditorActions(),{handleEditorDidMount:a}=st("python"),{value:r,onChange:i}=Ws({storeValue:t,defaultValue:s.PYTHON_DEFAULT_CODE,onStoreUpdate:n,delay:da});return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:i,value:r,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:a})}function tt({sql:t,showCardDetails:n=!1,className:a}){const[r,i]=I.useState(!1),c=s.useEditorStore(N=>N.card),l=s.useEditorStore(N=>N.frame),d=s.useEditorStore(N=>N.isDevMode),o=s.useDashboardStore(N=>N.selectedSheetId),x=s.useDashboardStore(N=>{var b;return(b=N.dashboard)==null?void 0:b.id}),{switchEditorMode:p,setRunSql:m}=s.useEditorActions(),u=()=>{p("dev",{sqlToLoad:t}),setTimeout(()=>{m(!0)},100)};return e.jsxs("div",{className:s.cn("flex min-h-0 flex-1 flex-col",a),children:[!d&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsxs(s.Button,{onClick:u,variant:"secondary",size:"sm",children:[e.jsx(Js,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),n&&e.jsxs(s.Button,{onClick:()=>i(!r),variant:"outline",size:"sm",children:[e.jsx(s.Info,{className:"mr-2 h-4 w-4"}),"Card Details"]})]}),r&&n&&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:()=>i(!1),children:e.jsx(ye.CircleX,{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:"font-mono text-xs",children:c.id||"N/A"})]}),e.jsx(s.CopyButton,{text:c.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:"font-mono text-xs",children:l.id||"N/A"})]}),e.jsx(s.CopyButton,{text:l.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:"font-mono text-xs",children:o||"N/A"})]}),e.jsx(s.CopyButton,{text:o||"",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:"font-mono text-xs",children:x||"N/A"})]}),e.jsx(s.CopyButton,{text:x||"",className:"h-6 w-6"})]})]})]})}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto text-xs leading-relaxed text-foreground/80",children: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"})]})})})]})}function ma(){var se,ne;const t=s.useQueryClient(),{isConsoleMode:n}=s.useDashboardPreferences(),[a,r]=I.useState(!1),i=s.useEditorStore(_=>_.frame),c=s.useEditorStore(_=>_.card);s.useEditorStore(_=>_.isShowingVisual),s.useEditorStore(_=>_.selectedConnectionId),s.useEditorStore(_=>_.tempQueryData),s.useEditorStore(_=>_.selectedDatabaseName),s.useEditorStore(_=>_.selectedDatamodelId),s.useEditorStore(_=>_.selectedSchemaName);const l=s.useEditorStore(_=>_.showAIDialog);s.useEditorStore(_=>_.selectedTableName),s.useEditorStore(_=>{var W;return(W=_==null?void 0:_.card)==null?void 0:W.sql}),s.useEditorStore(_=>{var W;return(W=_==null?void 0:_.card)==null?void 0:W.python});const{cardFilterValues:d}=s.useCardFilterValues((c==null?void 0:c.id)??""),o=s.useDashboardStore(_=>_.inlineFilterValuesMap[(c==null?void 0:c.id)??""]),x=I.useMemo(()=>s.findCustomVisualConfigCard(i,c),[i,c]),{manifest:p}=s.useCustomVisual(((se=x==null?void 0:x.customCardPreferences)==null?void 0:se.url)||""),m=I.useMemo(()=>{var _;return(_=p==null?void 0:p.visuals)==null?void 0:_.find(W=>{var le;return W.name===((le=x==null?void 0:x.customCardPreferences)==null?void 0:le.componentName)})},[p,(ne=x==null?void 0:x.customCardPreferences)==null?void 0:ne.componentName]),u=s.resolveMultiInputType(x,m),N=I.useMemo(()=>s.getCustomVisualInputCards({frame:i,configCard:x,isMultiInputVisual:u==="multiple"}),[i,x,u]),b=I.useMemo(()=>{const _=N.findIndex(W=>(W==null?void 0:W.id)===(c==null?void 0:c.id));return _<0?-1:s.getSlotIndexForCard(c,_)},[N,c]),h=I.useMemo(()=>!x||u!=="multiple"||b<0?c.type:s.getEffectiveCardTypeForSlot(c,b,m==null?void 0:m.slots)??c.type,[x,u,b,c,m==null?void 0:m.slots]),y=I.useMemo(()=>h!==c.type?{...c,type:h}:c,[c,h]),T=I.useRef(!0),{setCardCustomCfg:C,setQueryResultColumns:B,setCardSql:O,setTempQueryData:L,setPythonStdOut:g,setCardPreferences:w,setCardType:E,setCardPython:f,setShowAIDialog:M,setCard:j,updateCardInFrame:k}=s.useEditorActions();s.useEditorStore(_=>_.onSave),s.useEditorStore(_=>_.onClose),s.useEditorStore(_=>_.actions.setSqlGen);const D=s.useEditorStore(_=>_.runSql),P=s.useEditorStore(_=>_.actions.setRunSql),v=s.useEditorStore(_=>_.actions.setIsSqlRunning),{data:A,isLoading:S,isFetching:R,isSuccess:F,isError:z,error:G,errorSql:V,queryKey:U,refetch:Q,errorMessage:J}=s.useDashboardCardQuery(y);I.useEffect(()=>{if(A&&(A.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),g((A==null?void 0:A.output)||""),A.records.length>0)){const{dimensionKeys:_}=s.getKeys(A.records);B(_)}},[A,B,g]),I.useEffect(()=>{(S||R)&&v(!0),(z||F)&&v(!1),z&&(B([]),g(""))},[S,R,A,g,z,F,v,B,G]),I.useEffect(()=>{D&&(t.getQueryData(U)||Q(),P(!1))},[D,Q,P,U,t]);const Z=I.useRef(Q);Z.current=Q,I.useEffect(()=>{if(T.current){T.current=!1;return}Z.current()},[o]);function q(){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(ca,{})}),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(ua,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function Y(){var _,W,le,he,$,H;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:S||R,onClick:()=>{Q()},className:"h-8 shrink-0",size:"sm",children:[S||R?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"]}),(A==null?void 0:A.sql)&&!J&&e.jsxs(s.HoverCard,{openDelay:300,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-4 w-4 shrink-0 cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.HoverCardContent,{align:"start",className:"w-[500px]",children:e.jsx(tt,{sql:A.sql})})]}),e.jsx(ye.EditorClearButton,{}),e.jsxs(s.Toggle,{pressed:a,onPressedChange:ae=>r(ae),className:"h-8",size:"sm",variant:"outline",children:[e.jsx(oa,{className:"mr-2 size-4 text-foreground/70"}),"Python"]}),!l&&e.jsxs("button",{disabled:l,onClick:()=>{M(!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:((W=(_=c.preferences)==null?void 0:_.tablePrefs)==null?void 0:W.enableDevModePagination)??!1,onCheckedChange:ae=>{var ie;w({...c.preferences,tablePrefs:{...(ie=c.preferences)==null?void 0:ie.tablePrefs,enableDevModePagination:ae}})}}),e.jsx(s.Label,{htmlFor:"pagination",className:"cursor-pointer text-sm",children:"Paginate"}),((he=(le=c.preferences)==null?void 0:le.tablePrefs)==null?void 0:he.enableDevModePagination)&&e.jsxs(s.Select,{value:String(((H=($=c.preferences)==null?void 0:$.tablePrefs)==null?void 0:H.pageSize)||50),onValueChange:ae=>{var je,ve,Ne;const ie=Number(ae),ge={...c,preferences:{...c.preferences,tablePrefs:{...(je=c.preferences)==null?void 0:je.tablePrefs,pageSize:ie}},paginationConfig:{page:1,pageSize:ie}};j(ge),k(ge),c.sql&&((Ne=(ve=c.preferences)==null?void 0:ve.tablePrefs)!=null&&Ne.enableDevModePagination)&&P(!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"})]})]})]}),d&&d.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:d.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(d,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:q()}),Y()]})}const xa=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:s.Grid3x3},{value:"detailTable",label:"Detail",icon:s.List}];function ha({className:t}){const n=s.useEditorStore(m=>m.card),a=s.useEditorStore(m=>m.frame),r=ye.useEffectiveEditorCardType(),{setCard:i,updateCardInFrame:c}=s.useEditorActions(),l=["table","aggregateTable","pivotTable","detailTable"].includes(r),d=s.hasValidCardConfig(n.config),o=s.isCustomVisualConfigCard(n,a.cards);if(!l||!d||o)return null;const x=m=>{if(o)return;const u=m,N=n.config??{},b=p(r,u,N),h={...n,type:u,config:b};i(h),c(h)},p=(m,u,N)=>{var h;if(u==="detailTable"){const y=O=>O==null?void 0:O.toLowerCase().replace(/\s+/g,"").trim(),T=(O,L)=>{const g=[y(O.label),y(O.qualifiedFieldName),y(O.name)].filter(Boolean),w=[y(L.label),y(L.qualifiedFieldName),y(L.name)].filter(Boolean);return g.some(E=>w.includes(E))},C=(N.groupByColumns||[]).map(O=>({...O,role:"detail"})),B=((h=N.sortByColumns)==null?void 0:h.filter(O=>C.some(L=>T(O,L))))??[];return{...N,detailTableBackup:{groupByColumns:N.groupByColumns,metricColumns:N.metricColumns,pivotByColumns:N.pivotByColumns,sortByColumns:N.sortByColumns,rowAggregates:N.rowAggregates,columnAggregates:N.columnAggregates,comparisonType:N.comparisonType},detailColumns:C,groupByColumns:[],metricColumns:[],pivotByColumns:[],sortByColumns:B,rowAggregates:[],columnAggregates:[],comparisonType:"none"}}let b=N;if(m==="detailTable")if(N.detailTableBackup)b={...N,...N.detailTableBackup,detailColumns:[],detailTableBackup:void 0};else{const y=(N.detailColumns||[]).map(T=>({...T,role:"groupby"}));b={...N,groupByColumns:y,detailColumns:[]}}return u==="aggregateTable"?{...b,pivotByColumns:[]}:b};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:r,onValueChange:x,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:xa.map(m=>{const u=m.icon,N=r===m.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:m.value,id:`table-type-${m.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${m.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all",N?"bg-muted text-foreground shadow-sm":"text-muted-foreground hover:bg-muted/50"),children:[e.jsx(u,{className:"h-3.5 w-3.5"}),m.label]})]},m.value)})})})}function pa({type:t,isLinked:n,className:a}){const r=s.useDashboardStore(u=>u.selectedFrameId),i=s.useManagementStore(u=>u.selectedVisual),c=s.useEditorStore(u=>u.frame);let l;if(t)l=t;else if(n!==void 0)l=n?"linked":"library";else if(!!!(c!=null&&c.visualId||i!=null&&i.id)&&r)l="local";else if(i&&!r)l="library";else if(c!=null&&c.visualId&&r)l="linked";else if(i!=null&&i.id&&r)l="library";else return null;if(l==="local")return null;const d={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."},x={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"},p={linked:"fill-purple-50 dark:fill-purple-950",library:"fill-blue-50 dark:fill-blue-950"},m={linked:e.jsx(Kt,{className:"h-3.5 w-3.5"}),library:e.jsx(qt,{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",d[l],a),children:m[l]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:s.cn("max-w-xs",x[l]),children:[e.jsx(s.TooltipArrow,{className:p[l]}),e.jsx("p",{children:o[l]})]})]})})}function ls({error:t,errorSql:n,errorTitle:a="Unable to load data",onOpenInEditor:r,onDebugWithAssistant:i,onSendFeedback:c,showFeedbackButton:l=!0,className:d}){const[o,x]=I.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-border bg-muted/40 p-4",d),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-amber-500/10 dark:bg-amber-500/20",children:e.jsx(s.TriangleAlert,{className:"h-4 w-4 text-amber-600 dark:text-amber-500"})}),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-foreground",children:a}),e.jsxs("div",{className:"relative rounded-md border border-border bg-background p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 z-10 h-6 w-6"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"break-all font-mono text-xs text-muted-foreground",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n&&e.jsx(s.Collapsible,{open:o,onOpenChange:x,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:o?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),r&&n&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:r,children:[e.jsx(Js,{className:"mr-1.5 h-3.5 w-3.5"}),"Open in Editor"]}),l&&c&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:c,children:[e.jsx(s.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]}),i&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:i,children:[e.jsx(zt,{className:"mr-1.5 h-3.5 w-3.5"}),"Debug with Assistant"]})]}),n&&e.jsx(s.Collapsible,{open:o,onOpenChange:x,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:"Query"}),e.jsx(s.CopyButton,{text:n,className:"h-6 w-6"})]}),e.jsx("div",{className:"max-h-80 overflow-auto rounded-md border border-border bg-background p-2",children:e.jsx(s.CodeHighlighter,{code:n,language:"sql"})})]})})})]})]})})}function at(t,n){const a=s.useEditorStore(x=>x.card),r=s.useEditorStore(x=>x.isDevMode),{switchEditorMode:i,setRunSql:c,runAssistant:l}=s.useEditorActions();return{isDevMode:r,handleOpenInEditor:r?void 0:()=>{const x=n||a.sql||a.python||"";i("dev",{sqlToLoad:x}),setTimeout(()=>{c(!0)},100)},handleDebugWithAssistant:r?()=>{const x=`Can you help me debug this query?
168
168
 
169
169
  Error:
170
170
 
@@ -174,6 +174,6 @@ ${w.joinType} JOIN ${E.name}
174
174
 
175
175
  ${n||a.sql||a.python}
176
176
 
177
- `;l(x)}:void 0}}function nt({className:t,...n}){var ne,_,W,le,he;const a=s.useEditorStore($=>$.card),r=((ne=a.customCardPreferences)==null?void 0:ne.showCardHeader)??!0,i=((W=(_=a.preferences)==null?void 0:_.displayOptions)==null?void 0:W.showInlineFilterBar)??!0,c=s.useEditorStore($=>$.frame),l=s.useDashboardStore($=>$.dashboard.filters),d=s.useDashboardStore($=>$.selectedSheetId),[o,x]=k.useState(!1),{currentUser:p}=s.useCurrentUserInfo(),{tokenProps:m}=k.useContext(s.SemaphorContext),u=s.useEditorStore($=>$.actions.setRunSql),{updateFilter:N}=s.useDashboardActions(),b=l==null?void 0:l.find($=>$.id===c.filterId),h=k.useMemo(()=>s.findCustomVisualConfigCard(c,a),[c,a]),{manifest:y}=s.useCustomVisual(((le=h==null?void 0:h.customCardPreferences)==null?void 0:le.url)||""),T=k.useMemo(()=>{var $;return($=y==null?void 0:y.visuals)==null?void 0:$.find(H=>{var ae;return H.name===((ae=h==null?void 0:h.customCardPreferences)==null?void 0:ae.componentName)})},[y,(he=h==null?void 0:h.customCardPreferences)==null?void 0:he.componentName]),C=s.resolveMultiInputType(h,T),B=k.useMemo(()=>s.getCustomVisualInputCards({frame:c,configCard:h,isMultiInputVisual:C==="multiple"}),[c,h,C]),O=k.useMemo(()=>{const $=B.findIndex(H=>(H==null?void 0:H.id)===(a==null?void 0:a.id));return $<0?-1:s.getSlotIndexForCard(a,$)},[B,a]),L=k.useMemo(()=>!h||C!=="multiple"||O<0?a.type:s.getEffectiveCardTypeForSlot(a,O,T==null?void 0:T.slots)??a.type,[h,C,O,a,T==null?void 0:T.slots]),g=L??a.type,w=k.useMemo(()=>g===a.type?a:{...a,type:g},[a,g]),E=k.useMemo(()=>L!==a.type?{...a,type:L}:a,[a,L]),{data:f,isLoading:M,isFetching:j,errorMessage:I,errorSql:D,pagination:P}=s.useDashboardCardQuery(E),{handleOpenInEditor:v,handleDebugWithAssistant:A}=at(I,D||a.sql||a.python),S=k.useMemo(()=>(f==null?void 0:f.records)||[],[f==null?void 0:f.records]),{setCard:R,updateCardInFrame:F}=s.useEditorActions(),{data:z}=s.useTopoJson(w),G=k.useMemo(()=>{var $;return g!=="pivotTable"||!(($=f==null?void 0:f.records)!=null&&$.length)?null:{records:f.records,columnSubtotalMeta:f.columnSubtotalMeta,subtotalColumns:f.subtotalColumns||[],pivotSchema:f.pivotSchema||[],groupByColumns:f.groupByColumns}},[g,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]),V=s.usePivotTableConfig(w,G),U=()=>{x(!0)},Q=k.useMemo(()=>{const $=typeof window<"u"?window.location.href:"",H=typeof navigator<"u"?navigator.userAgent:"",ae=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:s.FeedbackCategory.QUERY_GENERATION,user:p,tokenContext:m,systemState:{cardConfig:a.config,dataSource:a.dataSource,dashboardFilters:l,errorMessage:I||void 0,errorSql:D||a.sql||a.python,generatedSql:D||a.sql},metadata:{url:$,userAgent:H,timestamp:new Date().toISOString(),viewport:ae}}},[p,m,a,l,I,D]),J=($,H)=>{var ie,ge;const ae={...a,paginationConfig:{page:$+1,pageSize:H}};R(ae),F(ae),a.sql&&((ge=(ie=a.preferences)==null?void 0:ie.tablePrefs)!=null&&ge.enableDevModePagination)&&u(!0)},Z=$=>{var ie,ge,je,ve,Ne;const H=s.sortStateToSortByColumns($,(ie=a.config)==null?void 0:ie.metricColumns,(ge=a.config)==null?void 0:ge.groupByColumns,(je=a.config)==null?void 0:je.detailColumns),ae={...a,config:{...a.config||{},sortByColumns:H}};R(ae),F(ae),a.sql&&((Ne=(ve=a.preferences)==null?void 0:ve.tablePrefs)!=null&&Ne.enableDevModePagination)&&u(!0)},q=k.useMemo(()=>!w.id||!(f!=null&&f.records)?null:s.createChartConfig({card:w,data:f==null?void 0:f.records,cardType:g,queryConfig:w.queryConfig,customCfg:w.customCfg,preferences:w.preferences,topoJson:z}),[w.id,f==null?void 0:f.records,g,w.customCfg,w.preferences,z]);function Y($){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(s.EditorCustomVisual,{card:$})})}function se(){var $;if(f!=null&&f.records&&(f==null?void 0:f.records.length)===0&&!M&&!j)return I?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ls,{error:I,errorSql:D||a.sql||a.python,onOpenInEditor:v,onDebugWithAssistant:A,onSendFeedback:U,showFeedbackButton:!0})}):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((M||j)&&(!(f!=null&&f.records)||f.records.length===0))return g==="table"||g==="detailTable"?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(!w.id)return null;if(g==="custom")return Y(a);if(!["table","pivotTable","aggregateTable","detailTable","custom"].includes(g)&&q)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:M||j?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:q})});if(g==="table"||g==="detailTable")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:w,data:S,comparisonMetadata:($=f==null?void 0:f.metadata)==null?void 0:$.comparisonMetadata,paginationMetadata:P,onPaginationChange:J,onSortChange:Z,isLoading:M||j})});if(g==="pivotTable"&&V)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:w,data:V.data,options:V.options,onAggregationChange:H=>{const ae=s.handleAggregationChange(H,a.config),ie={...a,config:ae};R(ie),F(ie)},onAggregationLabelChange:H=>{const ae=s.handleAggregationLabelChange(H,a.config),ie={...a,config:ae};R(ie),F(ie)}})});if(g==="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:w,data:(f==null?void 0:f.records)||[],groupByColumns:f==null?void 0:f.groupByColumns,pivotSchema:f==null?void 0:f.pivotSchema,paginationMetadata:P,onPaginationChange:J,onAggregationChange:H=>{const ae=s.handleAggregationChange(H,a.config),ie={...a,config:ae};R(ie),F(ie)},isLoading:M||j})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[(M||j)&&(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:$=>R({...a,title:$}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(pa,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(ha,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:(a.description||"").trim(),onSave:$=>R({...a,description:$.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),b&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:b.title||b.column,onSave:$=>N({...b,title:$}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:b})]})]}),i&&a.inlineFilters&&a.inlineFilters.length>0&&e.jsx("div",{className:"px-6 pb-3",children:e.jsx(s.InlineFilterBar,{card:a,sheetId:d||""})}),e.jsxs(s.CardContent,{className:"flex min-h-0 grow flex-col",children:[e.jsx("div",{className:"min-h-0 flex-1 grow basis-0",children:se()}),s.isCardSummaryVisibleOnCard(w)&&e.jsx("div",{className:"pt-3",children:e.jsx(s.CardSummary,{card:w,mode:"editor"})})]}),e.jsx(s.FeedbackDialog,{open:o,onOpenChange:x,feedbackData:Q,showDebugInfo:!0})]})}const Qe=({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}),fa=()=>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."})]})]}),ga=({customCode:t,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:i})=>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(Qe,{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(Qe,{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(Qe,{language:"javascript",value:t,onChange:i})})]}),ja=({error:t,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:i})=>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:i,variant:"outline",children:"Close"})]});function ba(){const[t,n]=k.useState(!1),[a,r]=k.useState(""),[i,c]=k.useState(""),[l,d]=k.useState(""),[o,x]=k.useState(""),p=s.useEditorStore(w=>w.card),m=ye.useEffectiveEditorCardType(),u=s.useEditorStore(w=>w.card.customCfg),N=u?JSON.stringify(u,null,2):"",b=k.useMemo(()=>m!==p.type?{...p,type:m}:p,[p,m]),{data:h}=s.useDashboardCardQuery(b),{data:y}=s.useTopoJson(p),{setCardCustomCfg:T,setCustomVisualCode:C}=s.useEditorActions(),B=w=>{var E,f;return JSON.stringify({...w,data:{...w.data,datasets:(f=(E=w.data)==null?void 0:E.datasets)==null?void 0:f.map(M=>({...M,data:[]}))}},null,2)},O=()=>{var E,f;if(!((E=h==null?void 0:h.records)!=null&&E.length))return;const w=s.createChartConfig({card:p,data:h.records,cardType:p.type,queryConfig:p.queryConfig,preferences:p.preferences,topoJson:y});if(w){r(B(w)),d(((f=p.preferences)==null?void 0:f.customVisualCode)||"");const M=s.merge(w,u);c(B(M))}},L=()=>{try{if(l&&C(l),i){const w=JSON.parse(i),E=s.getObjectDiff(JSON.parse(a),w);T(E),x("")}}catch{x("Invalid JSON configuration")}},g=Object.keys(u||{}).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:O,className:g?"":"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(fa,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(nt,{className:"w-1/2 rounded shadow-none"})}),e.jsx(ga,{customCode:l,cardCustomCfgString:N,mergedConfig:i,onConfigChange:w=>c(w??""),onCodeChange:w=>d(w??"")})]}),e.jsx(ja,{error:o,hasCardCustomConfig:!!u,onReset:()=>{c(a),T(null)},onApply:L,onClose:()=>n(!1)})]})]})}function ya({isStarred:t,onClick:n,className:a}){const r=i=>{i.stopPropagation(),i.preventDefault(),n(i)};return e.jsx("button",{type:"button",onClick:r,className:s.cn("flex items-center justify-center rounded-sm p-0.5 transition-all","hover:bg-muted/80",a),"aria-label":t?"Remove from favorites":"Add to favorites",children:e.jsx(s.Star,{className:s.cn("h-3.5 w-3.5 transition-colors",t?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-foreground")})})}function Ds({chartType:t,chartName:n,isCustom:a=!1,pluginName:r,isStarred:i,showStar:c=!0,onSelect:l,onToggleStar:d}){return e.jsxs("button",{onClick:l,className:s.cn("group relative 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:[c&&e.jsx("div",{className:s.cn("absolute left-1 top-1 transition-opacity",i?"opacity-100":"opacity-0 group-hover:opacity-100"),children:e.jsx(ya,{isStarred:i,onClick:()=>d()})}),a&&r&&e.jsx("div",{className:"absolute right-1 top-1",children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center justify-center",children:e.jsx(s.Info,{className:"h-3 w-3 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"top",className:"text-xs",children:r})]})}),e.jsx(s.ChartIcon,{chartType:t,chartName:n,isCustom:a,className:"h-6 w-6"}),e.jsx("span",{title:n,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:n})]})}const Ls=[{id:"table",name:"Table"},{id:"bar",name:"Bar Chart"},{id:"line",name:"Line Chart"},{id:"area",name:"Area Chart"},{id:"combo",name:"Combo Chart"},{id:"stackedBar",name:"Stacked Bar"},{id:"stackedArea",name:"Stacked Area"},{id:"stackedLine",name:"Stacked Line"},{id:"scatter",name:"Scatter"},{id:"bubble",name:"Bubble"},{id:"pie",name:"Pie Chart"},{id:"doughnut",name:"Doughnut"},{id:"funnel",name:"Funnel"},{id:"radar",name:"Radar"},{id:"polarArea",name:"Polar Area"},{id:"tornado",name:"Tornado"},{id:"range",name:"Range"},{id:"bullet",name:"Bullet Chart"},{id:"treemap",name:"Treemap"},{id:"kpi",name:"KPI"},{id:"text",name:"Text"},{id:"map",name:"Map"}];function va({onChartSelect:t,onClose:n}){const[a,r]=k.useState(""),{starredCharts:i,isStarred:c,toggleStar:l}=s.useStarredChartsStore(),{data:d=[],isLoading:o}=s.useCustomVisualsQuery(),{setCardType:x,setCardPreferences:p,setIsDevMode:m}=s.useEditorStore(f=>f.actions),u=s.useEditorStore(f=>f.card),{setCardCustomCfg:N,setCustomCardPreferences:b,setQueryConfig:h,replaceFrameCards:y,clearModeDrafts:T,initializeModeDrafts:C}=s.useEditorActions(),B=k.useMemo(()=>{if(!a)return Ls;const f=a.toLowerCase();return Ls.filter(M=>M.name.toLowerCase().includes(f))},[a]),O=k.useMemo(()=>{const f=d.filter(j=>j.componentType==="chart");if(!a)return f;const M=a.toLowerCase();return f.filter(j=>j.name.toLowerCase().includes(M))},[d,a]),L=f=>{N(null),p({}),x(f),["custom","text","map"].includes(f)&&(m(!0),h(void 0)),t==null||t(f),n==null||n()},g=f=>{N(null),p({}),h(void 0);const M=s.resolveMultiInputTypeFromVisual(f);if(M==="multiple"&&f.slots&&f.slots.length>0){T();const I=s.createCardsFromSlots(f.slots,f,u);y(I),I[0]&&C(I[0]),n==null||n();return}else x("custom"),b({type:"component",visualType:M,url:f.url,componentName:f.name,icon:f.icon,pluginChartType:f.chartType,minInputs:f.minInputs,maxInputs:f.maxInputs});t==null||t("custom",f),n==null||n()},w=f=>{const M={type:"default",id:f.id,name:f.name};l(M)},E=f=>{const M={type:"custom",id:f.name,url:f.url,icon:f.icon,name:f.name};l(M)};return e.jsxs("div",{className:"flex flex-col",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$1,{placeholder:"Search charts...",value:a,onChange:f=>r(f.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:[B.length>0&&e.jsxs("div",{className:"mb-3",children:[e.jsx("span",{className:"mb-2 block text-xs font-medium text-muted-foreground",children:"Default Charts"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:B.map(f=>e.jsx(Ds,{chartType:f.id,chartName:f.name,isCustom:!1,isStarred:c("default",f.id),onSelect:()=>L(f.id),onToggleStar:()=>w(f)},f.id))})]}),O.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsxs("div",{children:[e.jsx("span",{className:"mb-2 block text-xs font-medium text-muted-foreground",children:"Custom Charts"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:O.map((f,M)=>e.jsx(Ds,{chartName:f.name,isCustom:!0,pluginName:f.pluginName,isStarred:c("custom",f.name),onSelect:()=>g(f),onToggleStar:()=>E(f)},`${f.url}-${f.name}-${M}`))})]})]}),o&&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 charts..."})]}),B.length===0&&O.length===0&&!o&&e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No charts found"})]})]})}function Na({selectedChart:t,onChartChange:n}){var g,w,E,f;const a=s.useEditorStore(M=>M.card),r=s.useEditorStore(M=>M.frame),i=s.useEditorStore(M=>M.isDevMode),{replaceFrameCards:c,clearModeDrafts:l,initializeModeDrafts:d,setIsDevMode:o}=s.useEditorActions(),x=k.useMemo(()=>s.findCustomVisualConfigCard(r,a),[r,a]),{manifest:p}=s.useCustomVisual(((g=x==null?void 0:x.customCardPreferences)==null?void 0:g.url)||""),m=k.useMemo(()=>{var M;return(M=p==null?void 0:p.visuals)==null?void 0:M.find(j=>{var I;return j.name===((I=x==null?void 0:x.customCardPreferences)==null?void 0:I.componentName)})},[p,(w=x==null?void 0:x.customCardPreferences)==null?void 0:w.componentName]),u=s.resolveMultiInputType(x,m)==="multiple",N=ye.useEffectiveEditorCardType(),b=u?N:t??a.type,h=(E=a==null?void 0:a.customCardPreferences)==null?void 0:E.componentName,y=(f=x==null?void 0:x.customCardPreferences)==null?void 0:f.componentName,T=u&&!!y,C=k.useMemo(()=>{const M=s.chartTypes.find(j=>j.id===b);return M?M.label:b==="custom"?h||"Custom Visual":"Select chart type"},[b,h]),B=k.useMemo(()=>{const M=s.chartTypes.find(j=>j.id===b);if(M){const j=M.icon;return e.jsx(j,{className:"h-4 w-4"})}if(b==="custom"&&h){const j=s.getAutoDetectedChartIcon(h);return j||e.jsx(s.ChartIcon,{chartName:h,isCustom:!0,className:"h-4 w-4"})}return e.jsx(Wt,{className:"h-4 w-4"})},[b,h]);return{displayChartType:b,displayLabel:C,displayIcon:B,showBadge:T,badgeLabel:y,isMultiInputContext:u,handleChartSelect:M=>{n==null||n(M)},handleClearCustomVisual:M=>{if(M.stopPropagation(),u){const I={...a,sql:"",python:"",config:void 0,queryConfig:void 0,customCfg:void 0,preferences:{}},P=s.useEditorStore.getState().frame.cards.map(v=>v.id===I.id?I:v);c(P),l(),d(I),i&&o(!0);return}const j={...a,type:"bar",sql:"",python:"",config:void 0,queryConfig:void 0,customCfg:void 0,preferences:{},customCardPreferences:void 0,title:"Chart",tabTitle:"Chart",description:void 0,info:void 0};c([j]),l(),d(j),i&&o(!0),n==null||n("bar")}}}function os({selectedChart:t,onChartChange:n,variant:a="ghost",className:r}){const[i,c]=k.useState(!1),{displayLabel:l,displayIcon:d,showBadge:o,badgeLabel:x,handleChartSelect:p,handleClearCustomVisual:m}=Na({selectedChart:t,onChartChange:n});return e.jsxs("div",{className:s.cn("relative w-full",r),children:[e.jsxs(s.Popover,{open:i,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:a,role:"combobox","aria-expanded":i,className:"w-full justify-between gap-2",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[d,e.jsx("span",{className:"truncate",children:l})]}),e.jsx(s.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[360px] p-3",align:"start",onOpenAutoFocus:u=>u.preventDefault(),children:e.jsx(va,{onChartSelect:u=>p(u),onClose:()=>c(!1)})})]}),o&&e.jsxs("div",{className:"absolute right-10 top-1/2 z-10 flex max-w-[140px] -translate-y-1/2 items-center gap-1 rounded-full border bg-background py-0.5 pl-2 pr-1 text-[10px] text-muted-foreground shadow-sm",title:x,children:[e.jsx(s.Layers,{className:"h-2.5 w-2.5 shrink-0"}),e.jsx("span",{className:"truncate",children:x}),e.jsx("button",{onClick:m,className:"rounded-full p-0.5 hover:bg-muted",title:"Clear custom visual",children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]})]})}function Ca(){const t=s.useEditorStore(o=>{var x,p;return(p=(x=o.card.preferences)==null?void 0:x.chartOptions)==null?void 0:p.indexAxis}),n=s.useEditorStore(o=>o.card.type),{setChartOrientation:a,setCardPreferences:r}=s.useEditorStore(o=>o.actions),i=o=>{if(a(o),n!=="bullet")return;const x=o==="y"?"horizontal":"vertical",p=s.useEditorStore.getState().card.preferences,m={...p||{},bulletConfig:{...(p==null?void 0:p.bulletConfig)||{},orientation:x}};r(m)};function c(){const o=t??"x",x=()=>{i(o==="x"?"y":"x")};return e.jsx(s.IconButton,{onClick:x,tooltip:"Chart Orientation",children:o==="x"?e.jsx(Ye,{className:"size-4"}):e.jsx(Je,{className:"size-4"})})}function l(){const o=()=>{i(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(Ye,{className:"size-4"}):e.jsx(Je,{className:"size-4"})})}function d(){const o=t??"y",x=()=>{i(o==="y"?"x":"y")};return e.jsx(s.IconButton,{onClick:x,tooltip:"Chart Orientation",children:o==="y"?e.jsx(Je,{className:"size-4"}):e.jsx(Ye,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?l():n==="bullet"?d():c()})}function Sa({className:t}){var N,b,h,y,T,C,B,O,L,g;const n=s.useEditorStore(w=>w.card),{setCardPreferences:a,updateCardInFrame:r,setCard:i}=s.useEditorActions(),[c,l]=k.useState(!1),d=((b=(N=n.preferences)==null?void 0:N.displayOptions)==null?void 0:b.showFilterInfo)??!0,o=((y=(h=n.preferences)==null?void 0:h.displayOptions)==null?void 0:y.showCardToolbar)??!0,x=((C=(T=n.preferences)==null?void 0:T.displayOptions)==null?void 0:C.showChrome)??!0,p=((O=(B=n.preferences)==null?void 0:B.displayOptions)==null?void 0:O.allowScroll)??!0,m=((g=(L=n.preferences)==null?void 0:L.displayOptions)==null?void 0:g.showInlineFilterBar)??!0,u=(w,E)=>{var j;const f={...n.preferences,displayOptions:{...(j=n.preferences)==null?void 0:j.displayOptions,[w]:E}};a(f);const M={...n,preferences:f};i(M),r(M)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:c,onOpenChange:l,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(Qs,{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:d,onCheckedChange:w=>{u("showFilterInfo",w)},onSelect:w=>w.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:w=>{u("showCardToolbar",w)},onSelect:w=>w.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:x,onCheckedChange:w=>{u("showChrome",w)},onSelect:w=>w.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:p,onCheckedChange:w=>{u("allowScroll",w)},onSelect:w=>w.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:m,onCheckedChange:w=>{u("showInlineFilterBar",w)},onSelect:w=>w.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 wa(){const[t,n]=k.useState(!1),a=s.useEditorStore(m=>m.card),r=s.useEditorStore(m=>m.selectedConnectionId),{setCard:i}=s.useEditorActions(),c=s.useDashboardStore(m=>m.actions.removeCardInlineFilterValue),l=(a==null?void 0:a.inlineFilters)||[];function d(m){var g,w,E,f,M;const u=((E=(w=(g=a==null?void 0:a.dataSource)==null?void 0:g.selectedEntities)==null?void 0:w[0])==null?void 0:E.database)||"",N=m.qualifiedFieldName||m.name;if(l.find(j=>j.column===N))return;const h=m.qualifiedFieldName?m.qualifiedFieldName.split(".").slice(0,-1).join("."):m.qualifiedEntityName||m.entityName,T=s.fmt(m.name),C=s.buildFilterFieldMeta(m),B=s.buildFilterSemanticContext(a==null?void 0:a.dataSource,{connectionId:r||((f=a==null?void 0:a.dataSource)==null?void 0:f.connectionId),connectionType:(M=a==null?void 0:a.dataSource)==null?void 0:M.connectionType}),O=s.isCalculatedFilterField(C),L={id:s.v4(),column:N,title:m.label||m.name,dataType:m.dataType,table:m.entityName||"",database:u,connectionId:r||"",operation:"in",sql:O?"":s.getDefaultFilterSql(m.dataType,h,T),fieldMeta:C,semanticContext:B,width:250};i({...a,inlineFilters:[...l,L]})}function o(m){const u=l.filter(N=>N.id!==m);i({...a,inlineFilters:u}),c(a.id,m)}function x(m,u){const N=l.map(b=>b.id===m?{...b,...u}:b);i({...a,inlineFilters:N})}return["bar","line","pie","doughnut","table","detailTable","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":l.length>0}),children:[e.jsx(Ut,{className:"h-4 w-4"}),l.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:l.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:d,inlineFilters:l})})})}),l.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:l.map(m=>e.jsx(Ta,{filter:m,onUpdate:u=>x(m.id,u),onRemove:()=>o(m.id)},m.id))})]})]})})]})}):null}function Ta({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 rt(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var l,d;return(d=(l=c.card)==null?void 0:l.preferences)==null?void 0:d.chartOptions}),a=s.getChartGridStyle(n),{setChartGrid:r}=s.useEditorActions();function i(){const c=["xy","none","x","y"],d=(c.indexOf(a)+1)%c.length;r(c[d])}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(Ca,{})}),!["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:i,children:[(a==="xy"||!a)&&e.jsx(s.Grid3x3,{className:"size-4"}),a==="x"&&e.jsx(Hs,{className:"size-4"}),a==="y"&&e.jsx(rs,{className:"size-4"}),a==="none"&&e.jsx(s.Square,{className:"size-4"})]}),e.jsx(wa,{}),e.jsx(Sa,{})]})}function Ea({isPreviewMode:t,onPreviewToggle:n,configCard:a}){var P,v,A,S,R;const r=s.useEditorStore(F=>F.frame),i=s.useEditorStore(F=>F.card),{setFrame:c,setActiveTabCardId:l,setCard:d,updateCardInFrame:o,clearModeDrafts:x,initializeModeDrafts:p}=s.useEditorActions(),{manifest:m}=s.useCustomVisual(((P=a==null?void 0:a.customCardPreferences)==null?void 0:P.url)||""),u=(v=m==null?void 0:m.visuals)==null?void 0:v.find(F=>{var z;return F.name===((z=a==null?void 0:a.customCardPreferences)==null?void 0:z.componentName)}),b=s.resolveMultiInputType(a,u)==="multiple",h=(u==null?void 0:u.minInputs)??((A=a==null?void 0:a.customCardPreferences)==null?void 0:A.minInputs)??1,y=(u==null?void 0:u.maxInputs)??((S=a==null?void 0:a.customCardPreferences)==null?void 0:S.maxInputs),T=k.useMemo(()=>s.getCustomVisualInputCards({frame:r,configCard:a,isMultiInputVisual:b}),[r,a,b]),C=b?T.filter(Boolean).length:r.cards.length,B=y?C<y:!0,O=C>Math.max(h||1,1),L=!!((R=a==null?void 0:a.customCardPreferences)!=null&&R.dataInputCardIds),g=(F,z)=>{F.dataTransfer.setData("tabIndex",z.toString())},w=F=>{F.preventDefault()},E=(F,z)=>{const G=F.dataTransfer.getData("tabIndex");if(G===z.toString())return;const V=Array.from(r.cards),[U]=V.splice(parseInt(G),1);V.splice(z,0,U),c({...r,cards:V})};function f(F){const z=(a==null?void 0:a.id)===F;if(!(L&&z?r.cards.length>1:O))return;let V=r.cards.filter(Z=>Z.id!==F);b&&!L&&(V=s.reindexSlotCards(V));const U=V[0],Q={...r,cards:V,activeCardId:U.id},J=F===i.id;J&&x(),c(Q),l(U.id),d(U),J&&p(U)}function M(F,z){if(!B)return;const G={...r,cards:[...r.cards,z],activeCardId:F.id};c(G),l(z.id)}function j(){if(b&&(a==null?void 0:a.id)===i.id){I(i);return}const F={...i,id:s.v4(),title:`${i.title} Copy`,tabTitle:`${i.tabTitle||i.title} Copy`,customCardPreferences:i.customCardPreferences?{...i.customCardPreferences,slotIndex:b?Math.max(-1,...T.map((z,G)=>s.getSlotIndexForCard(z,G)))+1:i.customCardPreferences.slotIndex}:void 0};M(i,F)}function I(F){var J;if(!B)return;let z=b?"table":"bar",G="Title",V="";const U=b?Math.max(-1,...T.map((Z,q)=>s.getSlotIndexForCard(Z,q)))+1:C;if(b&&((J=u==null?void 0:u.slots)!=null&&J.length)){const Z=s.getSlotDefinitionForIndex(u.slots,U);Z&&(z=s.getSlotExpectedChartType(Z),G=Z.label||`Tab ${U+1}`,V=Z.description||"")}const Q={dataSource:F.dataSource,connectionId:F.connectionId,lastSelectedDatabase:F.lastSelectedDatabase,lastSelectedSchema:F.lastSelectedSchema,lastSelectedTable:F.lastSelectedTable,lastSelectedDatamodelId:F.lastSelectedDatamodelId,id:s.v4(),title:G,tabTitle:G,description:V,preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:z,sql:"",data:[],mode:"explorer",...b&&{customCardPreferences:{slotIndex:U}}};M(F,Q)}function D(F,z){return F.cards.length===1&&(z.displayTab===!0||z.displayTab===void 0)||F.activeCardId!==z.id&&(z.displayTab===!0||z.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const G=z.displayTab===void 0?!1:!z.displayTab;d({...z,displayTab:G}),o({...z,displayTab:G})},children:z.displayTab===!0||z.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(s.EyeOff,{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:[r.cards.map((F,z)=>{var J,Z;const G=b?s.getSlotIndexForCard(F,z):-1,V=b&&((J=u==null?void 0:u.slots)!=null&&J.length)&&G>=0?s.getSlotDefinitionForIndex(u.slots,G):null,U=V?(Array.isArray(V.expectedType)?V.expectedType[0]:V.expectedType)||"table":F.type,Q=b&&((Z=u==null?void 0:u.slots)==null?void 0:Z.length)&&u.slots.every(q=>typeof q.position=="number"||typeof q.position=="string"&&!q.position.includes("+"));return e.jsxs(s.TabsTrigger,{draggable:!b,onDragStart:b?void 0:q=>g(q,z),onDragOver:b?void 0:w,onDrop:b?void 0:q=>E(q,z),className:"",value:F.id,children:[b&&V?e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:s.getChartIconByType(U,"size-3.5")}),e.jsx("span",{children:V.label||`Tab ${G+1}`})]})}),e.jsx(s.TooltipContent,{side:"bottom",className:"w-64 p-3 text-left",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium",children:V.label}),V.description&&e.jsx("p",{className:"whitespace-normal break-words text-xs text-muted-foreground",children:V.description}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[V.expectedType&&e.jsx("span",{className:"inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground",children:Array.isArray(V.expectedType)?V.expectedType.join(" / "):V.expectedType}),V.required&&e.jsx("span",{className:"inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground",children:"Required"})]})]})})]})}):e.jsxs(e.Fragment,{children:[D(r,F),e.jsx(s.Editable,{enabled:r.activeCardId===F.id,text:F.tabTitle||F.title,onSave:q=>{d({...i,tabTitle:q}),o({...i,tabTitle:q})},children:F.tabTitle||F.title},F.id)]}),r.activeCardId===F.id&&!Q&&e.jsx(s.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:q=>{q.stopPropagation(),j()}}),r.activeCardId===F.id&&(L&&(a==null?void 0:a.id)===F.id?r.cards.length>1:O)&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>f(F.id)})]},F.id)}),e.jsx(s.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>I(i),disabled:!B,children:e.jsx(s.Plus,{className:"h-4 w-4"})}),b&&e.jsxs(s.Toggle,{pressed:t,onPressedChange:n,size:"sm",className:"ml-2 h-8 gap-1 px-2 data-[state=on]:bg-background data-[state=on]:text-foreground","aria-label":"Toggle preview",children:[t?e.jsx(s.EyeOff,{className:"h-4 w-4"}):e.jsx(s.Eye,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Preview"})]})]})})}function ns(){var ge,je,ve,Ne,ke;const t=s.useEditorStore(X=>X.frame),n=s.useEditorStore(X=>X.card),[a,r]=k.useState(!1),i=k.useMemo(()=>s.findCustomVisualConfigCard(t,n),[t,n]),c=s.useEditorStore(X=>X.isSqlRunning);s.useEditorStore(X=>X.isDevMode);const{setFrame:l,setActiveTabCardId:d,setCard:o,setRunSql:x,mergeDraftsIntoCard:p,clearModeDrafts:m,initializeModeDrafts:u}=s.useEditorActions(),[N,b]=k.useState({}),[h,y]=k.useState(()=>new Set),{theme:T}=s.useTheme(),C=s.useDashboardStore(X=>X.themeStyle),{authToken:B}=s.useSemaphorContext(),O=s.getTokenParams(B==null?void 0:B.accessToken),L={mode:T||"system",colors:((je=(ge=C==null?void 0:C.chart)==null?void 0:ge.dataset)==null?void 0:je.backgroundColor)||[]},{getCard:g,manifest:w,isLoading:E}=s.useCustomVisual(((ve=i==null?void 0:i.customCardPreferences)==null?void 0:ve.url)||""),f=(Ne=i==null?void 0:i.customCardPreferences)==null?void 0:Ne.componentName,M=f?g(f):null,j=(ke=w==null?void 0:w.visuals)==null?void 0:ke.find(X=>X.name===f),I=s.resolveMultiInputType(i,j),D=a&&I==="multiple"&&!!i,P=k.useMemo(()=>s.getCustomVisualInputCards({frame:t,configCard:i,isMultiInputVisual:!0}).map(oe=>(oe==null?void 0:oe.id)===n.id?n:oe),[t,i,n]),v=k.useMemo(()=>s.buildSlotOrderedCards(P),[P]),A=k.useMemo(()=>{const X=P.findIndex(oe=>(oe==null?void 0:oe.id)===n.id);return X<0?-1:s.getSlotIndexForCard(n,X)},[P,n]),S=k.useMemo(()=>!i||I!=="multiple"||A<0?n.type:s.getEffectiveCardTypeForSlot(n,A,j==null?void 0:j.slots)??n.type,[i,I,A,n,j==null?void 0:j.slots]),R=k.useMemo(()=>D?{...n,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:S!==n.type?{...n,type:S}:n,[n,S,D]),{data:F,isLoading:z,isFetching:G,isError:V}=s.useDashboardCardQuery(R),U=k.useCallback((X,oe)=>{const ue=s.normalizeMultiInputPayload(oe);b(xe=>({...xe,[X]:ue}))},[]),Q=k.useCallback((X,oe)=>{y(ue=>{const xe=new Set(ue);return oe?xe.add(X):xe.delete(X),xe})},[]),J=h.size>0,Z=s.useInteractionStore(X=>X.interactionStates),q=s.useDashboardStore(X=>{var oe;return(oe=X.dashboard)==null?void 0:oe.id}),Y=s.useDashboardStore(X=>X.dashboard.filters),se=s.useDashboardStore(X=>X.filterValues),ne=s.useDashboardStore(X=>X.selectedSheetId),_=s.useDashboardStore(X=>X.inlineFilterValuesMap[(i==null?void 0:i.id)||""]),W=k.useMemo(()=>i?s.buildInlineFilterNodes({card:i,sheetId:ne||"",inlineFilterValues:_}):[],[i,ne,_]),{cardFilters:le,cardFilterValues:he}=k.useMemo(()=>i?s.calculateContextAwareFilters({card:i,interactionStates:Z,currentDashboardId:q,filters:Y,filterValues:se,selectedSheetId:ne}):{cardFilters:[],cardFilterValues:[]},[i,Z,q,Y,se,ne]);function $(X){const oe=t.cards.find(ue=>ue.id===X);oe&&(p(),H(X),d(X),m(),u(oe))}function H(X){const oe=s.useEditorStore.getState().card,ue=s.useEditorStore.getState().frame,xe={...ue,cards:ue.cards.map(Ce=>Ce.id===oe.id?oe:Ce),activeCardId:X};l(xe);const we=xe.cards.find(Ce=>Ce.id===X);we.sql&&x(!0),o(we)}function ae(){if(E)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading manifest"})});if(!M)return e.jsx("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"Select a component to preview the multi-input visual."});const oe=v.map((ue,xe)=>s.getEffectiveCardTypeForSlot(ue,xe,j==null?void 0:j.slots));return e.jsxs("div",{className:"relative flex h-full flex-col px-6",children:[P.map((ue,xe)=>{if(!ue)return null;const we=s.getSlotIndexForCard(ue,xe),Ce=s.getEffectiveCardTypeForSlot(ue,we,j==null?void 0:j.slots);return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:Q,onDataChange:U,card:ue,effectiveCardType:Ce},`${ue.id}-${we}`)}),J&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading preview"})}),e.jsx("div",{className:s.cn("flex h-full min-h-0 flex-1 flex-col gap-2",J&&"opacity-50"),children:e.jsx(k.Suspense,{fallback:e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted"})}),children:e.jsx(M,{editing:!0,...s.buildMultiInputCustomVisualProps({configCard:i,slotOrderedCards:v,slotTypes:oe,multiInputData:N,params:O,theme:L,filters:le,filterValues:[...he||[],..._||[]],inlineFilters:W})})})})]})}function ie(){var X;return D?ae():n.type==="kpi"?z||G?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.jsxs("div",{className:"w-1/2 space-y-3",children:[e.jsx("div",{className:"rounded-md border border-border",children:e.jsx(s.KPICard,{card:n,data:F==null?void 0:F.records,isPending:z||G,isError:V,comparisonMetadata:(X=F==null?void 0:F.metadata)==null?void 0:X.comparisonMetadata})}),s.isCardSummaryVisibleOnCard(n)&&e.jsx(s.CardSummary,{card:n,mode:"editor"})]})}):n.type==="text"?z||G?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:c,card:n,data:F==null?void 0:F.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(nt,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:$,value:t.activeCardId,className:"flex grow flex-col gap-2",children:[D?e.jsx("div",{className:"mt-0 grow",children:ie()}):t.cards.map(X=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:X.id,children:ie()},X.id)),e.jsx(Ea,{isPreviewMode:D,onPreviewToggle:r,configCard:i})]})}function Ms({children:t}){var R;const n=s.useEditorStore(F=>F.frame),a=s.useEditorStore(F=>F.card),r=s.useEditorStore(F=>F.isDevMode),i=s.useEditorStore(F=>F.isShowingVisual),c=s.useDashboardStore(F=>F.isVisualEditing),l=s.useEditorStore(F=>F.pythonStdOut),d=s.useEditorStore(F=>F.actions.setRunSql),o=ye.useEffectiveEditorCardType(),{setFrame:x,setCard:p,setActiveTabCardId:m,runAssistant:u,setCardPreferences:N,mergeDraftsIntoCard:b,clearModeDrafts:h,initializeModeDrafts:y}=s.useEditorActions(),T=k.useMemo(()=>o!==a.type?{...a,type:o}:a,[a,o]),{data:C,isLoading:B,isFetching:O,errorMessage:L,errorSql:g,refetch:w,pagination:E}=s.useDashboardCardQuery(T),{handleDebugWithAssistant:f}=at(L,g),M=k.useMemo(()=>(C==null?void 0:C.records)||[],[C==null?void 0:C.records]),[j,I]=k.useState(!1);k.useEffect(()=>{O||I(!1)},[O]);function D(F,z){var U,Q;const G={...a,paginationConfig:{page:F+1,pageSize:z}};p(G);const V={...n,cards:n.cards.map(J=>J.id===a.id?G:J)};x(V),a.sql&&((Q=(U=a.preferences)==null?void 0:U.tablePrefs)!=null&&Q.enableDevModePagination)&&d(!0)}function P(F){var U,Q,J,Z,q;const z=s.sortStateToSortByColumns(F,(U=a.config)==null?void 0:U.metricColumns,(Q=a.config)==null?void 0:Q.groupByColumns,(J=a.config)==null?void 0:J.detailColumns),G={...a,config:{...a.config||{},sortByColumns:z}};p(G);const V={...n,cards:n.cards.map(Y=>Y.id===a.id?G:Y)};x(V),a.sql&&((q=(Z=a.preferences)==null?void 0:Z.tablePrefs)!=null&&q.enableDevModePagination)&&d(!0)}function v(){const F=JSON.stringify(C==null?void 0:C.records,null,2),z=new Blob([F],{type:"application/json"}),G=URL.createObjectURL(z),V=document.createElement("a");V.href=G,V.download=`${a.title}.json`,V.click()}function A(){const z=[Object.keys(C==null?void 0:C.records.reduce((Q,J)=>({...Q,...J}),{})).join(","),...((C==null?void 0:C.records)||[]).map(Q=>Object.values(Q).join(","))].join(`
178
- `),G=new Blob([z],{type:"text/csv"}),V=URL.createObjectURL(G),U=document.createElement("a");U.href=V,U.download=`${a.title}.csv`,U.click()}function S(){const F=`Can you get the documentation for ${a.type} chart?`;u(F)}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:[i&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx("div",{className:"w-[260px]",children:e.jsx(os,{variant:"outline"})}),c&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:S,children:e.jsx(Rt,{className:"size-4"})}),!["table","detailTable","custom"].includes(a.type)&&c&&e.jsx(ba,{})]}),!i&&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:A,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:v,children:e.jsx(Pt,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(C==null?void 0:C.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:B||O,onClick:()=>{I(!0),w()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":j})})}),e.jsx(rt,{})]}),r&&e.jsx(Ia,{})]}),i?e.jsx(ns,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[l&&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:l&&e.jsx(ka,{})}),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":l}),children:[(C==null?void 0:C.records)&&(C==null?void 0:C.records.length)>0&&e.jsx(s.TableVisual,{card:a,data:M,comparisonMetadata:(R=C==null?void 0:C.metadata)==null?void 0:R.comparisonMetadata,paginationMetadata:E,onPaginationChange:D,onSortChange:P,isLoading:B||O}),L&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ls,{error:L,errorSql:g||a.sql||a.python,onDebugWithAssistant:f,showFeedbackButton:!1})})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function ka(){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 Ia(){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 Se({value:t,onCommit:n,type:a="text",placeholder:r,className:i}){const[c,l]=k.useState(t),d=k.useRef(!1);k.useEffect(()=>{l(t)},[t]);const o=()=>{if(d.current){d.current=!1;return}c!==t&&n(c)},x=p=>{if(p.key==="Enter"){p.currentTarget.blur();return}p.key==="Escape"&&(d.current=!0,l(t),p.currentTarget.blur())};return e.jsx(s.Input,{type:a,placeholder:r,value:c,onChange:p=>l(p.target.value),onBlur:o,onKeyDown:x,className:i})}function De({defaultValue:t,label:n,options:a,value:r,onValueChange:i,className:c,icon:l,showPlaceholderLabel:d=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:i,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",c),children:e.jsxs("div",{className:"flex items-center gap-2",children:[l&&e.jsx("span",{children:l}),d&&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))]})})]})}function Aa(t,n){return s.getSlotDefinitionForIndex(t,n)||null}function Be(t){if(typeof t=="number")return`Tab ${t+1}`;const n=t.match(/^(\d+)-(\d+)$/);if(n){const[,r,i]=n;return`Tabs ${Number(r)+1}-${Number(i)+1}`}const a=t.match(/^(\d+)\+$/);return a?`Tabs ${Number(a[1])+1}+`:`Tab ${t}`}function Da(t){return t?Array.isArray(t)?t:[t]:[]}function We(t){var r,i;if(!t)return!1;if(t.type==="text")return!!((r=t.description)!=null&&r.trim());const n=!!((i=t.sql)!=null&&i.trim()),a=s.hasValidCardConfig(t.config);return n||a}function La({slots:t,cards:n,minInputs:a}){const r=[],i=n.filter(Boolean).length;return a&&i<a&&r.push({type:"too-few-inputs",message:`This visual requires at least ${a} tab${a===1?"":"s"}.`}),!t||t.length===0||(t.forEach(c=>{if(!c.required)return;if(typeof c.position=="number"){const o=n[c.position];We(o)||r.push({type:"missing-required",message:`${Be(c.position)} ("${c.label}") is required but has no data configured.`});return}const l=c.position.match(/^(\d+)-(\d+)$/);if(l){const[,o,x]=l.map(Number);for(let p=o;p<=x;p+=1){const m=n[p];if(!We(m)){r.push({type:"missing-required",message:`${Be(p)} ("${c.label}") is required but has no data configured.`});break}}return}const d=c.position.match(/^(\d+)\+$/);if(d){const o=Number(d[1]);if(n.length<=o){r.push({type:"missing-required",message:`${Be(o)} ("${c.label}") is required but has no data configured.`});return}for(let x=o;x<n.length;x+=1){const p=n[x];if(!We(p)){r.push({type:"missing-required",message:`${Be(x)} ("${c.label}") is required but has no data configured.`});break}}}}),n.forEach((c,l)=>{if(!c)return;const d=Aa(t,l);if(!d||!d.expectedType)return;const o=Da(d.expectedType);o.length!==0&&(o.includes(c.type)||r.push({type:"wrong-type",message:`${Be(l)} ("${d.label}") expects ${o.join(", ")}, but is configured as ${c.type}.`}))})),r}const Ma={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 lt(){var I,D,P;const t=s.useEditorStore(v=>v.card.customCardPreferences),{data:n}=s.usePluginQuery(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(v=>v.card),i=s.useEditorStore(v=>v.frame),{setCustomCardPreferences:c}=s.useEditorActions(),l=k.useMemo(()=>s.findCustomVisualConfigCard(i,r),[i,r]),d=l==null?void 0:l.customCardPreferences,{components:o,manifest:x}=s.useCustomVisual((d==null?void 0:d.url)||(t==null?void 0:t.url)||""),p=(I=x==null?void 0:x.visuals)==null?void 0:I.find(v=>v.name===((d==null?void 0:d.componentName)||(t==null?void 0:t.componentName))),u=s.resolveMultiInputType(l||r,p)==="multiple",N=!!l&&l.id===r.id,b=(p==null?void 0:p.minInputs)??((D=l==null?void 0:l.customCardPreferences)==null?void 0:D.minInputs),h=(p==null?void 0:p.maxInputs)??((P=l==null?void 0:l.customCardPreferences)==null?void 0:P.maxInputs),y=k.useMemo(()=>s.getCustomVisualInputCards({frame:i,configCard:l||r,isMultiInputVisual:u}),[i,l,r,u]),T=k.useMemo(()=>s.buildSlotOrderedCards(y),[y]),C=k.useMemo(()=>T.map((v,A)=>{if(!v)return null;const S=s.getSlotIndexForCard(v,A),R=s.getEffectiveCardTypeForSlot(v,S,p==null?void 0:p.slots);return{...v,type:R??v.type}}),[T,p==null?void 0:p.slots]),B=k.useMemo(()=>La({slots:p==null?void 0:p.slots,cards:C,minInputs:b}),[p==null?void 0:p.slots,C,b]),O=k.useMemo(()=>{const v=y.findIndex(A=>(A==null?void 0:A.id)===r.id);return v<0?-1:s.getSlotIndexForCard(r,v)},[y,r]);function L(v){if(typeof v=="number")return`Tab ${v+1}`;const A=v.match(/^(\d+)-(\d+)$/);if(A){const[,R,F]=A;return`Tabs ${Number(R)+1}-${Number(F)+1}`}const S=v.match(/^(\d+)\+$/);return S?`Tabs ${Number(S[1])+1}+`:`Tab ${v}`}function g(v){return v?(Array.isArray(v)?v:[v]).join(", "):null}function w(v,A,S=[],R="",F,z,G){const V=E({key:A,defaultValue:R,settingsValue:z,sourceCard:G});return v==="input"?e.jsx(Se,{className:`h-8 w-full ${s.removeRing}`,value:String(V??""),onCommit:U=>{f({key:A,value:U,settingsField:F,settingsValue:z,sourceCard:G})}},A):v==="select"?e.jsx(De,{className:"h-8 w-full",label:"",options:S,value:String(V!==void 0?V:R??""),onValueChange:U=>{f({key:A,value:U,settingsField:F,settingsValue:z,sourceCard:G})}}):null}function E({key:v,defaultValue:A,settingsValue:S,sourceCard:R}){const F=S==null?void 0:S[v];return F!==void 0?F:v==="title"&&(R==null?void 0:R.title)!==void 0?R.title:v==="description"&&(R==null?void 0:R.description)!==void 0?R.description:A}function f({key:v,value:A,settingsField:S,settingsValue:R,sourceCard:F}){const z={...R||{}},G=v==="title"&&(F==null?void 0:F.title)!==void 0,V=v==="description"&&(F==null?void 0:F.description)!==void 0;G&&A===String((F==null?void 0:F.title)??"")||V&&A===String((F==null?void 0:F.description)??"")?delete z[v]:z[v]=A,c({...t||{},[S]:z})}function M({settingsSchema:v,settingsField:A,settingsValue:S,sourceCard:R,headerLabel:F}){const z=Object.entries(v||{});return e.jsxs("div",{className:"space-y-3",children:[F&&e.jsx(s.Label,{children:F}),z.map(([G,V])=>{var U;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:V.title}),((U=V.docs)==null?void 0:U.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:V.docs.description})})]})})]}),w(V.ui,G,V.options,V.defaultValue,A,S,R)]},G)})]})}function j(){return e.jsxs(e.Fragment,{children:[u&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Slot Guide"}),e.jsx("div",{className:"space-y-3 rounded-md border border-border bg-muted/40 px-3 py-2 text-xs",children:p!=null&&p.slots&&p.slots.length>0?e.jsx("div",{className:"space-y-3",children:p.slots.map((v,A)=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-foreground",children:[e.jsx("span",{className:"font-medium",children:L(v.position)}),e.jsx("span",{className:"text-muted-foreground",children:"•"}),e.jsx("span",{className:"font-medium",children:v.label})]}),v.description&&e.jsx("p",{className:"text-muted-foreground",children:v.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-muted-foreground",children:[g(v.expectedType)&&e.jsxs("span",{children:["Expected: ",g(v.expectedType)]}),v.required&&e.jsx("span",{children:"Required"})]})]},`${v.label}-${A}`))}):e.jsxs("div",{className:"space-y-1 text-muted-foreground",children:[e.jsx("p",{children:"This visual renders all tabs in a flexible layout. Add as many tabs as needed."}),(b||h)&&e.jsxs("p",{children:[b?`Min ${b} tabs`:"",b&&h?" • ":"",h?`Max ${h} tabs`:""]})]})})]}),u&&B.length>0&&e.jsx(s.Alert,{className:"border-yellow-500/40 bg-yellow-500/10 text-yellow-900 dark:text-yellow-100",children:e.jsx(s.AlertDescription,{children:e.jsx("ul",{className:"list-disc space-y-1 pl-4 text-xs",children:B.map((v,A)=>e.jsx("li",{children:v.message},`${v.type}-${A}`))})})}),p&&!u&&p.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:M({settingsSchema:p.settings,settingsField:"settings",settingsValue:t==null?void 0:t.settings,sourceCard:r})})}),p&&u&&(p.settings||p.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[N&&p.settings&&e.jsx("div",{className:"px-2",children:M({settingsSchema:p.settings,settingsField:"settings",settingsValue:t==null?void 0:t.settings,sourceCard:l||r,headerLabel:"Global Settings"})}),p.slotSettings&&e.jsx("div",{className:"px-2",children:M({settingsSchema:p.slotSettings,settingsField:"slotSettings",settingsValue:t==null?void 0:t.slotSettings,sourceCard:r,headerLabel:(()=>{const v=r.tabTitle||r.title,A=O>=0?O:0,S=N?"Slot 0":`Slot ${A}`;return v?`${S}: ${v} Settings`:`${S} Settings`})()})})]})]})}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:[(!u||N)&&e.jsx(De,{icon:e.jsx(_s,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(d==null?void 0:d.url)||"",onValueChange:v=>c({...t||{url:"",componentName:""},url:v})}),u&&!N&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Switch to the config tab to change the plugin or component."})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&(!u||N)&&e.jsx(e.Fragment,{children:o&&e.jsx(De,{icon:e.jsx(Bt,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(o==null?void 0:o.map(v=>({value:v.name,label:v.name})))||[],value:t.componentName||"",onValueChange:v=>{var R;const A=(R=x==null?void 0:x.visuals)==null?void 0:R.find(F=>F.name===v),S=o==null?void 0:o.find(F=>F.name===v);c({...t,componentName:v,visualType:(A==null?void 0:A.visualType)||(S==null?void 0:S.type)||"single",minInputs:A==null?void 0:A.minInputs,maxInputs:A==null?void 0:A.maxInputs,pluginChartType:A==null?void 0:A.chartType})}})})]})})]}),((d==null?void 0:d.componentName)||(t==null?void 0:t.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:(p==null?void 0:p.name)||"Settings"}),(p==null?void 0:p.docs)&&e.jsxs(s.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,onClick:v=>v.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:[p.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:p.docs.description}),p.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:Ma,children:p.docs.dataSchema})})]}),(()=>{var A;const v=(A=p.docs)==null?void 0:A.useCases;return!v||v.length===0?null: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:v.map((S,R)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:S})]},R))})]})})()]})})]})]})}),e.jsx(s.AccordionContent,{children:j()})]})]})}function Oa({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(l,d,o){const x=[...t];x[l]={...x[l],[d]:o},n(x)}function i(l){const d=[...t];d.splice(l,1),n(d)}function c(){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:c,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((l,d)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:o=>r(d,"start",o.target.value),value:l.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:l.end,onChange:o=>r(d,"end",o.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:o=>r(d,"color",o.target.value),value:l.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:()=>i(d),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},d))]})}function Fa(){var p,m,u,N,b;const t=s.useEditorStore(h=>h.card.preferences),n=s.useEditorStore(h=>h.actions.setCardPreferences),a=s.useEditorStore(h=>h.card),r=s.hasValidCardConfig(a.config),i=s.useEditorStore(h=>h.actions.setNumberFormat);s.useEditorStore(h=>{var y,T;return(T=(y=h.card.preferences)==null?void 0:y.formatNumber)==null?void 0:T.decimalPlaces});const c=s.useEditorStore(h=>{var y,T;return(T=(y=h.card.preferences)==null?void 0:y.formatNumber)==null?void 0:T.locale}),l=s.useEditorStore(h=>{var y,T;return(T=(y=h.card.preferences)==null?void 0:y.formatNumber)==null?void 0:T.currency});s.useEditorStore(h=>h.actions.setFilterOnClickField);const d=s.useEditorStore(h=>{var y,T;return(T=(y=h.card.preferences)==null?void 0:y.formatNumber)==null?void 0:T.colorRanges})||[],o=s.useEditorStore(h=>h.actions.setColorRanges),x=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(h=>h.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((p=t==null?void 0:t.formatNumber)!=null&&p.enabled),onCheckedChange:h=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:h}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((m=t==null?void 0:t.formatNumber)==null?void 0:m.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:c||"none",onValueChange:h=>{var y,T,C;return i(((y=t==null?void 0:t.formatNumber)==null?void 0:y.decimalPlaces)||0,((T=t==null?void 0:t.formatNumber)==null?void 0:T.currency)||"",h,((C=t==null?void 0:t.formatNumber)==null?void 0:C.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(h=>e.jsx(s.SelectItem,{value:h.locale,children:h.locale},h.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:l||"none",onValueChange:h=>{var y,T,C;console.log("currency",h),i(((y=t==null?void 0:t.formatNumber)==null?void 0:y.decimalPlaces)||0,h==="none"?"":h,((T=t==null?void 0:t.formatNumber)==null?void 0:T.locale)||"",((C=t==null?void 0:t.formatNumber)==null?void 0:C.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"),x.map(h=>e.jsx(s.SelectItem,{value:h,children:h},h))]})})]})]})]}),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:((N=(u=t==null?void 0:t.formatNumber)==null?void 0:u.decimalPlaces)==null?void 0:N.toString())||"0",onValueChange:h=>{var y,T,C;return i(Number(h),((y=t==null?void 0:t.formatNumber)==null?void 0:y.currency)||"",((T=t==null?void 0:t.formatNumber)==null?void 0:T.locale)||"",((C=t==null?void 0:t.formatNumber)==null?void 0:C.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(h=>e.jsx(s.SelectItem,{value:h,children:h},h))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((b=t==null?void 0:t.formatNumber)==null?void 0:b.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:h=>{var y,T,C;return i(((y=t==null?void 0:t.formatNumber)==null?void 0:y.decimalPlaces)||0,((T=t==null?void 0:t.formatNumber)==null?void 0:T.currency)||"",((C=t==null?void 0:t.formatNumber)==null?void 0:C.locale)||"",h.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(Oa,{colorRanges:d,setColorRanges:o})]})]})}const Ra={combo:{label:"Combo Chart",query:"SELECT x-axis, metric-1, metric-2, ... FROM table",fields:[{name:"x-axis",type:"category",description:"dimension"},{name:"metric-1, metric-2",type:"number",description:"can be bar, line, or area"}],description:"Combo charts allow mixing bar and line series with optional dual Y-axis for metrics with different scales.",docsUrl:"https://docs.semaphor.cloud/docs/charts/combo"},area:{label:"Area Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date, city"},{name:"Y-axis",type:"number",description:"e.g., sales, population"}],description:"Area charts display quantitative data with filled areas under the line.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bar-line-area"},stackedArea:{label:"Stacked Area Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date, city"},{name:"Y-axis",type:"number",description:"e.g., sales, population"}],description:"Stacked area charts show how multiple series contribute to a total over time.",docsUrl:"https://docs.semaphor.cloud/docs/charts/stacked"},bar:{label:"Bar Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., city, product"},{name:"Y-axis",type:"number",description:"e.g., sales, count"}],description:"Bar charts compare values across categories using horizontal or vertical bars.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bar-line-area"},line:{label:"Line Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date, month"},{name:"Y-axis",type:"number",description:"e.g., revenue, count"}],description:"Line charts show trends over time or continuous data.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bar-line-area"},stackedBar:{label:"Stacked Bar Chart",query:"SELECT x-axis, stack-by, y-axis FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., month"},{name:"Stack-by",type:"category",description:"e.g., product type"},{name:"Y-axis",type:"number",description:"e.g., sales"}],description:"Stacked bar charts show how parts contribute to a whole across categories.",docsUrl:"https://docs.semaphor.cloud/docs/charts/stacked"},stackedLine:{label:"Stacked Line Chart",query:"SELECT x-axis, stack-by, y-axis FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date"},{name:"Stack-by",type:"category",description:"e.g., region"},{name:"Y-axis",type:"number",description:"e.g., revenue"}],description:"Stacked line charts show cumulative trends over time.",docsUrl:"https://docs.semaphor.cloud/docs/charts/stacked"},pie:{label:"Pie Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., product, region"},{name:"Measure",type:"number",description:"e.g., sales, count"}],description:"Pie charts show proportions of a whole.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},doughnut:{label:"Doughnut Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., product, region"},{name:"Measure",type:"number",description:"e.g., sales, count"}],description:"Doughnut charts show proportions with a hollow center.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},polarArea:{label:"Polar Area Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., skill, metric"},{name:"Measure",type:"number",description:"e.g., score, value"}],description:"Polar area charts compare values using sectors of equal angle but varying radius.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},radar:{label:"Radar Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., attribute, skill"},{name:"Measure",type:"number",description:"e.g., score, rating"}],description:"Radar charts display multivariate data on axes starting from the same point.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},funnel:{label:"Funnel Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., stage name"},{name:"Measure",type:"number",description:"e.g., count, value"}],description:"Funnel charts visualize progressive reduction of data through stages.",docsUrl:"https://docs.semaphor.cloud/docs/charts/funnel"},bubble:{label:"Bubble Chart",query:"SELECT label, [group], x-axis, y-axis, radius FROM table",fields:[{name:"Label",type:"category",description:"e.g., city"},{name:"Group",type:"category",description:"e.g., region",optional:!0},{name:"X-axis",type:"number",description:"e.g., population"},{name:"Y-axis",type:"number",description:"e.g., income"},{name:"Radius",type:"number",description:"e.g., area"}],description:"Bubble charts display three dimensions of data using position and size.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bubble"},scatter:{label:"Scatter Chart",query:"SELECT label, [group], x-axis, y-axis FROM table",fields:[{name:"Label",type:"category",description:"e.g., item name"},{name:"Group",type:"category",description:"e.g., type",optional:!0},{name:"X-axis",type:"number",description:"e.g., price"},{name:"Y-axis",type:"number",description:"e.g., quantity"}],description:"Scatter charts show relationships between two numeric variables.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bubble"},tornado:{label:"Tornado Chart",query:"SELECT dimension, cohort, metric FROM table",fields:[{name:"Dimension",type:"category",description:"e.g., age group"},{name:"Cohort",type:"category",description:"e.g., gender"},{name:"Metric",type:"number",description:"e.g., population"}],description:"Tornado charts compare two groups across categories using back-to-back bars.",docsUrl:"https://docs.semaphor.cloud/docs/charts/tornado"},pyramid:{label:"Pyramid Chart",query:"SELECT dimension, cohort, metric FROM table",fields:[{name:"Dimension",type:"category",description:"e.g., age group"},{name:"Cohort",type:"category",description:"e.g., gender"},{name:"Metric",type:"number",description:"e.g., population"}],description:"Population pyramids show age and gender distribution.",docsUrl:"https://docs.semaphor.cloud/docs/charts/tornado"},range:{label:"Range Chart",query:"SELECT y-axis, label, range-from, range-to, range-value FROM table",fields:[{name:"Y-axis",type:"category",description:"e.g., category"},{name:"Label",type:"category",description:"e.g., range name"},{name:"Range-from",type:"number",description:"start value"},{name:"Range-to",type:"number",description:"end value"},{name:"Range-value",type:"number",description:"e.g., midpoint"}],description:"Range charts display data ranges with start and end values.",docsUrl:"https://docs.semaphor.cloud/docs/charts/range"},heatmap:{label:"Heatmap",query:"SELECT x-axis, y-axis, value FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., day"},{name:"Y-axis",type:"category",description:"e.g., hour"},{name:"Value",type:"number",description:"e.g., count, intensity"}],description:"Heatmaps visualize data density using color intensity.",docsUrl:"https://docs.semaphor.cloud/docs/charts/heatmap"},bullet:{label:"Bullet Chart",query:"SELECT label, actual, target, [ranges] FROM table",fields:[{name:"Label",type:"category",description:"e.g., metric name"},{name:"Actual",type:"number",description:"current value"},{name:"Target",type:"number",description:"goal value"},{name:"Ranges",type:"number",description:"threshold values",optional:!0}],description:"Bullet charts compare actual performance against targets.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bullet"},text:{label:"Text Visual",query:"SELECT text FROM table LIMIT 1",fields:[{name:"Text",type:"string",description:"content to display"}],description:"Text visuals display dynamic text content from your data.",docsUrl:"https://docs.semaphor.cloud/docs/charts/text"},kpi:{label:"KPI",query:"SELECT current, previous FROM table",fields:[{name:"Current",type:"number",description:"current value"},{name:"Previous",type:"number",description:"comparison value"}],description:"KPI visuals display key performance indicators with comparison values.",docsUrl:"https://docs.semaphor.cloud/docs/charts/kpi"},map:{label:"Map Chart",query:"SELECT country, value FROM table",fields:[{name:"Country/Region",type:"category",description:"geographic identifier"},{name:"Value",type:"number",description:"e.g., population, sales"}],description:"Map charts visualize geographic data using color intensity.",docsUrl:"https://docs.semaphor.cloud/docs/charts/map"},table:{label:"Table",query:"SELECT column1, column2, ... FROM table",fields:[{name:"Columns",type:"category",description:"any data columns"}],description:"Tables display data in rows and columns.",docsUrl:"https://docs.semaphor.cloud/docs/charts/table"},detailTable:{label:"Detail Table",query:"SELECT column1, column2, ... FROM table ORDER BY column1 DESC",fields:[{name:"Columns",type:"category",description:"columns to display (no aggregation)"}],description:"Detail tables display raw records without aggregation. Ideal for event logs, transaction history, and audit trails.",docsUrl:"https://docs.semaphor.cloud/docs/charts/detail-table"}};function is(t){return Ra[t]}function Ba({chartType:t,showDocsLink:n=!0}){const a=is(t);return a?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Query Format"}),e.jsx("code",{className:"block rounded-md bg-muted/50 px-3 py-2 font-mono text-xs text-foreground",children:a.query})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Fields"}),e.jsx("div",{className:"rounded-md border",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Field"}),e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Type"}),e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Description"})]})}),e.jsx("tbody",{children:a.fields.map((r,i)=>e.jsxs("tr",{className:i<a.fields.length-1?"border-b":"",children:[e.jsxs("td",{className:"px-2.5 py-1.5 font-medium text-foreground",children:[r.name,r.optional&&e.jsx("span",{className:"ml-1 text-muted-foreground",children:"?"})]}),e.jsx("td",{className:"px-2.5 py-1.5 font-mono text-muted-foreground",children:r.type}),e.jsx("td",{className:"px-2.5 py-1.5 text-muted-foreground",children:r.description||"—"})]},r.name))})]})})]}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:a.description}),n&&a.docsUrl&&e.jsxs("a",{href:a.docsUrl,target:"_blank",rel:"noopener noreferrer",onClick:r=>r.stopPropagation(),className:"inline-flex items-center gap-1.5 text-xs font-medium text-primary hover:underline",children:["View documentation",e.jsx(s.ExternalLink,{className:"h-3 w-3"})]})]}):null}function Pa({chartType:t}){return is(t)?e.jsxs(s.HoverCard,{openDelay:200,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded bg-muted px-2 py-0.5 font-mono text-[10px] font-semibold uppercase tracking-wider text-muted-foreground transition-colors hover:bg-muted/80 hover:text-foreground",children:"SQL"})}),e.jsx(s.HoverCardContent,{className:"w-80 p-4",side:"left",align:"start",sideOffset:8,children:e.jsx(Ba,{chartType:t})})]}):null}function $e({chartType:t,suffix:n="Configuration"}){const a=is(t),r=(a==null?void 0:a.label)||t;return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-sm font-medium",children:[r," ",n]}),e.jsx(Pa,{chartType:t})]})}function Va(){return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx($e,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(Fa,{})})]})}function Os({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})]})}function ot(){const[t,n]=k.useState([]),a=s.useEditorStore(x=>x.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:i}=s.useEditorStore(x=>x.actions),c=s.useEditorStore(x=>x.queryResultColumns);s.useEditorStore(x=>{var p;return(p=x.card.preferences)==null?void 0:p.filterOnClickColumnIndex}),k.useEffect(()=>{c&&n(new Array(c.length).fill(!1))},[c]);function l(x,p){var m,u;p?a!=null&&a.onClickFilter&&((m=a==null?void 0:a.onClickFilter)==null?void 0:m.length)>0?i({...a,onClickFilter:[...a.onClickFilter,{columnIndex:x,expression:""}]}):i({...a,onClickFilter:[{columnIndex:x,expression:""}]}):(i({...a,onClickFilter:(u=a==null?void 0:a.onClickFilter)==null?void 0:u.filter(N=>N.columnIndex!==x)}),n(N=>{const b=[...N];return b[x]=!1,b}))}function d(x,p){var u;const m=(u=a==null?void 0:a.onClickFilter)==null?void 0:u.map(N=>N.columnIndex===x?{...N,expression:p.target.value}:N);i({...a,onClickFilter:m})}function o(x){var p,m,u,N;if(t!=null&&t[x]||(m=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(b=>b.columnIndex===x))!=null&&m.expression)return e.jsx(s.Input,{value:(N=(u=a==null?void 0:a.onClickFilter)==null?void 0:u.find(b=>b.columnIndex===x))==null?void 0:N.expression,onChange:b=>d(x,b),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:c==null?void 0:c.map((x,p)=>{var m,u;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:!!((m=a==null?void 0:a.onClickFilter)!=null&&m.find(N=>N.columnIndex===p)),onCheckedChange:N=>l(p,N)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:x}),e.jsx("div",{className:"flex items-center gap-2",children:((u=a==null?void 0:a.onClickFilter)==null?void 0:u.find(N=>N.columnIndex===p))&&e.jsx(s.Pencil,{onClick:()=>{n(N=>{const b=[...N];return b[p]=!N[p],b})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),o(p)]})},x)})})}const za=[{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"}],$a=["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"],qa=$a.map(t=>({label:t,value:t}));function Ka(){var o,x,p,m,u,N,b,h,y,T,C,B,O,L,g,w,E,f;const t=s.useEditorStore(M=>M.card),n=(x=(o=t==null?void 0:t.preferences)==null?void 0:o.mapVisualOptions)==null?void 0:x.topoJsonUrl,[a,r]=k.useState(((m=(p=t==null?void 0:t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:m.customTopoJsonUrl)||""),{setCardPreferences:i}=s.useEditorActions(),{data:c}=s.useTopoJson(t),l=Object.keys((c==null?void 0:c.objects)||{}).map(M=>({label:M,value:M}))||[],d=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx($e,{chartType:"map"}),e.jsx(Os,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(De,{className:"h-9",options:d,onValueChange:M=>{console.log("value",M),i({...t.preferences,mapVisualOptions:{topoJsonUrl:M}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:M=>{r(M.target.value)},onBlur:()=>{var M;console.log("onBlur",a),i({...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"}),c&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(De,{className:"h-9",options:l,value:((N=(u=t.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:N.objectKey)||"",label:"Map Object",onValueChange:M=>{var j;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,objectKey:M}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(De,{className:"h-9",options:za,value:((h=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:h.projection)||"",label:"Projection",onValueChange:M=>{var j;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,projection:M}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(De,{className:"h-9",options:qa,value:((T=(y=t.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:T.colorScale)||"",label:"Select Color Scale",onValueChange:M=>{var j;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,colorScale:M}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Os,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((B=(C=t.preferences)==null?void 0:C.mapVisualOptions)==null?void 0:B.projectionScale)||1,onChange:M=>{var j;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,projectionScale:Number(M.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((g=(L=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:L.projectionOffset)==null?void 0:g[0])||0,onChange:M=>{var j,I,D,P;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,projectionOffset:[Number(M.target.value),((P=(D=(I=t.preferences)==null?void 0:I.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:P[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((f=(E=(w=t.preferences)==null?void 0:w.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:f[1])||0,onChange:M=>{var j,I,D,P;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,projectionOffset:[((P=(D=(I=t.preferences)==null?void 0:I.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:P[0])||0,Number(M.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(ot,{})]})}function it({color:t,onColorChange:n,onClose:a}){const[r,i]=k.useState(0),[c,l]=k.useState(100),[d,o]=k.useState(50),[x,p]=k.useState(t);k.useEffect(()=>{const y=Fs(t);if(y){const T=Rs(y.r,y.g,y.b);i(T.h),l(T.s),o(T.l),p(t)}},[t]);const m=y=>{i(y),N(y,c,d)},u=y=>{const T=y.currentTarget.getBoundingClientRect(),C=Math.max(0,Math.min(1,(y.clientX-T.left)/T.width)),B=Math.max(0,Math.min(1,(y.clientY-T.top)/T.height)),O=C*100,L=(1-B)*100;l(O),o(L),N(r,O,L)},N=(y,T,C)=>{const B=Ua(y,T,C),O=Ga(B.r,B.g,B.b);p(O)},b=y=>{if(p(y),/^#[0-9A-Fa-f]{6}$/.test(y)){const T=Fs(y);if(T){const C=Rs(T.r,T.g,T.b);i(C.h),l(C.s),o(C.l)}}},h=()=>{/^#[0-9A-Fa-f]{6}$/.test(x)&&(n(x),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:u,onMouseMove:y=>{y.buttons===1&&u(y)},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:`${c}%`,top:`${100-d}%`,backgroundColor:x}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:y=>m(Number(y.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,{value:x,onChange:y=>b(y.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:x}}),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:h,children:"OK"})]})]})}function Fs(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 Ga(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function Rs(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),i=Math.min(t,n,a);let c=0,l=0;const d=(r+i)/2;if(r!==i){const o=r-i;switch(l=d>.5?o/(2-r-i):o/(r+i),r){case t:c=((n-a)/o+(n<a?6:0))/6;break;case n:c=((a-t)/o+2)/6;break;case a:c=((t-n)/o+4)/6;break}}return{h:Math.round(c*360),s:Math.round(l*100),l:Math.round(d*100)}}function Ua(t,n,a){t/=360,n/=100,a/=100;let r,i,c;if(n===0)r=i=c=a;else{const l=(x,p,m)=>(m<0&&(m+=1),m>1&&(m-=1),m<.16666666666666666?x+(p-x)*6*m:m<.5?p:m<.6666666666666666?x+(p-x)*(.6666666666666666-m)*6:x),d=a<.5?a*(1+n):a+n-a*n,o=2*a-d;r=l(o,d,t+1/3),i=l(o,d,t),c=l(o,d,t-1/3)}return{r:Math.round(r*255),g:Math.round(i*255),b:Math.round(c*255)}}const Bs=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],_a=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Le({value:t,onChange:n,label:a}){const[r,i]=k.useState(!1),[c,l]=k.useState(!1),d=()=>{const o=Bs.find(x=>x.value===t);return o?o.color:t.startsWith("#")?t:Bs[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:i,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:d()},"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:_a.map(o=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",d()===o?"border-gray-900":"border-transparent"),style:{backgroundColor:o},onClick:()=>{n(o),i(!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:()=>{l(!0),i(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),c&&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:()=>l(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(it,{color:d(),onColorChange:o=>{n(o),l(!1)},onClose:()=>l(!1)})})]})]})}const Ha=["auto","number","currency","percent","scientific","date"],Ja=[{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"}],Ya=[{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"}],Qa=t=>t.charAt(0).toUpperCase()+t.slice(1);function qe({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const i=t.type||"auto",c=(d,o)=>{n({...t,[d]:o})},l=()=>i==="currency"?2:i==="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:i,onValueChange:d=>c("type",d),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ha.map(d=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:d==="auto"?"Auto (Default)":Qa(d)},d))})]})]}),i!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(i)&&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,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??l(),onChange:d=>c("decimalPlaces",parseInt(d.target.value)||0),className:"h-8 text-xs"})})]}),i==="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:d=>c("currency",d),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ja.map(d=>e.jsx(s.SelectItem,{value:d.value,className:"text-xs",children:d.label},d.value))})]})]}),["number","currency"].includes(i)&&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:d=>c("useSuffix",d)})]}),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:d=>c("locale",d),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ya.map(d=>e.jsx(s.SelectItem,{value:d.value,className:"text-xs",children:d.label},d.value))})]})]}),i==="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,{placeholder:"e.g., $",value:t.prefix||"",onChange:d=>c("prefix",d.target.value),className:"h-8 text-xs"})})]}),i==="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,{placeholder:"e.g., units",value:t.suffix||"",onChange:d=>c("suffix",d.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(i)&&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:d=>c("negativeInParentheses",d)})]}),i==="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,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:d=>c("multiplyBy",d.target.value?parseFloat(d.target.value):void 0),className:"h-8 text-xs"})})]}),i==="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,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:d=>c("dateFormat",d.target.value),className:"h-8 text-xs"})})]})]})]})}function Wa(){const t=s.useDashboardStore(d=>d.dashboard.filters),n=s.useEditorStore(d=>d.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useColumns(),{assignFilter:i}=s.useAssignFilter();function c(d){const o=i(d,"frame");a({...n,filterId:o})}const l=t==null?void 0:t.find(d=>d.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(Xa,{onSelect:c,columns:r}),l&&e.jsx(s.FilterHeader,{filter:l})]})}function Xa({columns:t,onSelect:n}){var l;const[a,r]=as.useState(!1),[i,c]=as.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:[i?((l=t.find(d=>d.name===i))==null?void 0:l.label)||i:"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 column found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(d=>e.jsxs(s.CommandItem,{value:d.name,onSelect:o=>{const x=o===i?"":o;c(x),r(!1),x&&n(d)},children:[d.label||d.name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",i===d.name?"opacity-100":"opacity-0")})]},d.id))})]})]})})]})}const Za=[{value:"difference",label:"Difference"},{value:"change",label:"Change (%)"},{value:"change_difference",label:"Change + Difference"},{value:"ratio",label:"Ratio"}],en=[{value:"arrow_badge",label:"Arrow + Badge"},{value:"arrow",label:"Arrow Only"},{value:"badge",label:"Badge Only"},{value:"none",label:"None"}];function sn({cardType:t="table"}){var p,m,u,N,b;const n=s.useEditorStore(h=>h.card),a=s.useEditorStore(h=>{var y;return(y=h.card)==null?void 0:y.preferences}),r=s.useEditorStore(h=>h.actions.setCardPreferences),c=(((p=n.config)==null?void 0:p.metricColumns)||[]).some(h=>h.comparisonType&&h.comparisonType!=="none"),l=((m=a==null?void 0:a.tableVisualOptions)==null?void 0:m.metricComparison)||{},d=h=>{r({...a,tableVisualOptions:{...a==null?void 0:a.tableVisualOptions,metricComparison:{...l,...h}}})},o={increase:((u=l.colors)==null?void 0:u.increase)||"green",decrease:((N=l.colors)==null?void 0:N.decrease)||"red",neutral:((b=l.colors)==null?void 0:b.neutral)||"neutral"},x=h=>{r({...a,allowDownload:h})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsxs(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:[c&&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(Ys,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison Settings"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated As"}),e.jsxs(s.Select,{value:l.calculatedAs||"change_difference",onValueChange:h=>d({calculatedAs:h}),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Za.map(h=>e.jsx(s.SelectItem,{value:h.value,className:"text-xs",children:h.label},h.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Number Format"}),e.jsx(qe,{formatOptions:l.formatOptions||{},onFormatOptionsChange:h=>d({formatOptions:h}),showTitle:!1})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator Style"}),e.jsxs(s.Select,{value:l.indicatorStyle||"arrow_badge",onValueChange:h=>d({indicatorStyle:h}),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:en.map(h=>e.jsx(s.SelectItem,{value:h.value,className:"text-xs",children:h.label},h.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Colors"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Le,{value:o.increase,onChange:h=>d({colors:{...o,increase:h}}),label:"Increase"}),e.jsx(Le,{value:o.decrease,onChange:h=>d({colors:{...o,decrease:h}}),label:"Decrease"}),e.jsx(Le,{value:o.neutral,onChange:h=>d({colors:{...o,neutral:h}}),label:"No Change"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Lower is Better"}),e.jsx(s.Checkbox,{checked:l.lowerIsBetter||!1,onCheckedChange:h=>d({lowerIsBetter:!!h})})]})]})]}),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(ot,{}),e.jsx(Wa,{})]})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:x,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 tn(){var r;const t=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:n}=s.useEditorStore(i=>i.actions);function a(i){n({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:i==="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 an(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx($e,{chartType:"text"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Text Type"}),e.jsx(tn,{})]})]})}const nn=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function rn(){var L,g,w,E,f,M,j,I,D,P;const t=s.useEditorStore(v=>v.card),n=s.useEditorStore(v=>{var A;return(A=v.card)==null?void 0:A.preferences}),a=ye.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:i}=s.useEditorActions(),c=k.useMemo(()=>a!==t.type?{...t,type:a}:t,[t,a]),{data:l}=s.useDashboardCardQuery(c),[d,o]=k.useState({}),[x,p]=k.useState(null),[m,u]=k.useState(null),N=k.useMemo(()=>{var R,F,z,G,V,U,Q;if(!(l!=null&&l.records)||l.records.length===0)return[];const v=a==="stackedBar"||a==="stackedLine",A=a==="bar"||a==="line"||a==="horizontalBar"||a==="bullet"||a==="combo"||a==="area"||a==="stackedArea",S=((R=t==null?void 0:t.config)==null?void 0:R.pivotByColumns)&&t.config.pivotByColumns.length>0;if((v||A)&&S){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const J=new Set;return l.pivotSchema.forEach(Z=>{Z.alias&&J.add(Z.alias)}),Array.from(J)}if(l.records.length>0){const J=l.records[0],Z=Object.keys(J),q=new Set;(F=t==null?void 0:t.config)!=null&&F.groupByColumns&&t.config.groupByColumns.forEach(ne=>{q.add(ne.label||ne.name),q.add(ne.alias||ne.name)});const Y=new Set;return(z=t==null?void 0:t.config)!=null&&z.metricColumns&&t.config.metricColumns.forEach(ne=>{const _=ne.alias||ne.name;Y.add(_),Y.add(`${_}_count`),Y.add(`${_}_sum`),Y.add(`${_}_avg`),Y.add(`${_}_min`),Y.add(`${_}_max`);const W=ne.entityName||ne.qualifiedEntityName;W&&(Y.add(`${W}_${_}`),Y.add(`${W}_${_}_count`))}),Z.filter(ne=>!q.has(ne)&&!Y.has(ne))}}if((A||v)&&!S&&((V=(G=t==null?void 0:t.config)==null?void 0:G.metricColumns)!=null&&V.length))return t.config.metricColumns.map(J=>J.alias||J.label||J.name);if((Q=(U=t==null?void 0:t.config)==null?void 0:U.groupByColumns)!=null&&Q.length){const J=t.config.groupByColumns[0],Z=J.label||J.name,q=new Set;return l.records.forEach(Y=>{const se=Y[Z];se!=null&&q.add(String(se))}),Array.from(q)}return[]},[l,(L=t==null?void 0:t.config)==null?void 0:L.groupByColumns,(g=t==null?void 0:t.config)==null?void 0:g.pivotByColumns,(w=t==null?void 0:t.config)==null?void 0:w.metricColumns,t==null?void 0:t.type]),b=k.useMemo(()=>s.getDefaultChartColors(),[]);k.useEffect(()=>{const v={};N.forEach((A,S)=>{v[A]=s.getColorForValue(A,S,n==null?void 0:n.colorConfig)}),o(v)},[N,n==null?void 0:n.colorConfig,b]);const h=(v,A)=>{const S={...d,[v]:A};o(S);const R={...n||{},colorConfig:{segments:S}};r(R);const F={...t,preferences:R};i(F)},y=(v,A)=>{var V;const S=b[A%b.length],{[v]:R,...F}=((V=n==null?void 0:n.colorConfig)==null?void 0:V.segments)||{},z={...n||{},colorConfig:{segments:F}};r(z);const G={...t,preferences:z};i(G),o(U=>({...U,[v]:S}))};if(!N.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((f=(E=t==null?void 0:t.config)==null?void 0:E.groupByColumns)==null?void 0:f.length)||((j=(M=t==null?void 0:t.config)==null?void 0:M.pivotByColumns)==null?void 0:j.length):(D=(I=t==null?void 0:t.config)==null?void 0:I.groupByColumns)==null?void 0:D.length)||["table","kpi","text","custom","heatmap"].includes(a))return null;const B=()=>{const v={...n||{},colorConfig:{segments:{}}};r(v);const A={...t,preferences:v};i(A);const S={};N.forEach((R,F)=>{S[R]=s.getColorForValue(R,F,void 0)}),o(S)},O=Object.keys(((P=n==null?void 0:n.colorConfig)==null?void 0:P.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(Jt,{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:O&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:B,children:[e.jsx(ks,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:N.map((v,A)=>{const S=s.isDefaultColor(d[v],A),R=!S;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:x===v,onOpenChange:F=>p(F?v: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[v]}})}),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:b.slice(0,10).map((F,z)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",d[v]===F?"border-gray-900":"border-transparent"),style:{backgroundColor:F},onClick:()=>{h(v,F),p(null)},children:[z===A%b.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:F})]},`default-${z}`))})]}),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:nn.map((F,z)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",d[v]===F?"border-2 border-gray-900":F==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:F},onClick:()=>{h(v,F),p(null)},children:e.jsx("span",{className:"sr-only",children:F})},`preset-${z}`))})]}),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:()=>{u({value:v,color:d[v]}),p(null)},children:"Custom color"}),!S&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{y(v,A),p(null)},children:[e.jsx(ks,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:v}),R&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},v)})}),m&&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:()=>u(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(it,{color:m.color,onColorChange:v=>{h(m.value,v),u(null)},onClose:()=>u(null)})})]})]})})]})}function Te({value:t,onSave:n,placeholder:a="",type:r="text",className:i=""}){const[c,l]=k.useState(t??""),[d,o]=k.useState(!1);k.useEffect(()=>{l(t??"")},[t]);const x=()=>{n(c),o(!1)},p=()=>{l(t??""),o(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${i}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:d?c:t??"",onChange:m=>{l(m.target.value),o(!0)},onFocus:()=>o(!0),onClick:m=>m.stopPropagation(),className:"h-8 text-xs",onPointerDown:m=>m.stopPropagation(),onKeyDown:m=>{m.stopPropagation(),m.key==="Enter"&&d&&c!==t?x():m.key==="Escape"&&p()},"aria-label":a||"Edit field"}),d&&c!==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:x,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:p,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function Xe({axis:t,label:n,type:a,config:r,onChange:i,defaultTitle:c,hidePosition:l}){var N,b,h,y,T,C,B,O,L,g,w,E,f,M;const d=(j,I)=>{i({...r??{},[j]:I})},o=(j,I)=>{var A,S,R,F;const D=j==="enabled"&&I===!0,P=(A=r==null?void 0:r.name)==null?void 0:A.text,v=D&&!P&&c;i({...r??{},name:{...r==null?void 0:r.name,enabled:j==="enabled"?I:((S=r==null?void 0:r.name)==null?void 0:S.enabled)??!1,text:j==="text"?I:v?c:P,fontSize:j==="fontSize"?I:(R=r==null?void 0:r.name)==null?void 0:R.fontSize,fontWeight:j==="fontWeight"?I:(F=r==null?void 0:r.name)==null?void 0:F.fontWeight}})},x=(j,I)=>{var D,P;i({...r??{},labels:{enabled:j==="enabled"?I:((D=r==null?void 0:r.labels)==null?void 0:D.enabled)??!0,rotation:j==="rotation"?I:(P=r==null?void 0:r.labels)==null?void 0:P.rotation}})},p=(j,I)=>{i({...r??{},scale:{...r==null?void 0:r.scale,[j]:I===""?"auto":Number(I)}})},m=t==="x"?["auto","top","bottom"]:["auto","left","right"],u=["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:j=>d("enabled",j),onClick:j=>j.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 gap-2",children:[e.jsx(s.Checkbox,{id:`${t}-title-enabled`,checked:((N=r==null?void 0:r.name)==null?void 0:N.enabled)??!1,onCheckedChange:j=>o("enabled",j===!0)}),e.jsx(s.Label,{htmlFor:`${t}-title-enabled`,className:"text-xs font-medium cursor-pointer",children:"TITLE"})]}),((b=r==null?void 0:r.name)==null?void 0:b.enabled)&&e.jsxs("div",{className:"space-y-2 pl-6",children:[e.jsx(Te,{placeholder:`${n} title`,value:((h=r==null?void 0:r.name)==null?void 0:h.text)||"",onSave:j=>o("text",j),className:""}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Size"}),e.jsx("div",{className:"w-14",children:e.jsx(Te,{type:"number",placeholder:"12",value:String(((y=r==null?void 0:r.name)==null?void 0:y.fontSize)||12),onSave:j=>o("fontSize",Number(j)||12),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Weight"}),e.jsxs(s.Select,{value:((T=r==null?void 0:r.name)==null?void 0:T.fontWeight)||"normal",onValueChange:j=>o("fontWeight",j),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:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]})]})]})]}),!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:(r==null?void 0:r.position)||"auto",onValueChange:j=>d("position",j),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(j=>e.jsx(s.SelectItem,{value:j,className:"text-xs",children:j==="auto"?"Auto (Default)":s.titleCase(j)},j))})]})]}),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:((C=r==null?void 0:r.labels)==null?void 0:C.enabled)!==!1,onCheckedChange:j=>x("enabled",j)})]}),((B=r==null?void 0:r.labels)==null?void 0:B.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(((O=r==null?void 0:r.labels)==null?void 0:O.rotation)||"auto"),onValueChange:j=>x("rotation",j==="auto"?"auto":Number(j)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(j=>e.jsx(s.SelectItem,{value:j,className:"text-xs",children:j==="auto"?"Auto (Default)":`${j}°`},j))})]})]})]}),a==="value"&&e.jsx(qe,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:j=>i({...r,formatOptions:j}),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(Te,{type:"number",placeholder:"auto",value:((L=r==null?void 0:r.scale)==null?void 0:L.min)==="auto"||((g=r==null?void 0:r.scale)==null?void 0:g.min)===void 0?"":String(r.scale.min),onSave:j=>p("min",j),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(Te,{type:"number",placeholder:"auto",value:((w=r==null?void 0:r.scale)==null?void 0:w.max)==="auto"||((E=r==null?void 0:r.scale)==null?void 0:E.max)===void 0?"":String(r.scale.max),onSave:j=>p("max",j),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(Te,{type:"number",placeholder:"auto",value:((f=r==null?void 0:r.scale)==null?void 0:f.stepSize)==="auto"||((M=r==null?void 0:r.scale)==null?void 0:M.stepSize)===void 0?"":String(r.scale.stepSize),onSave:j=>p("stepSize",j),className:""})})]})]})]})]})]})}function Ze(t,n,a){var c,l,d;if(t==="x"){const o=(l=(c=n==null?void 0:n.config)==null?void 0:c.groupByColumns)==null?void 0:l[0];return(o==null?void 0:o.label)||(o==null?void 0:o.name)||""}const r=((d=n==null?void 0:n.config)==null?void 0:d.metricColumns)||[],i=(a==null?void 0:a.datasetOptions)||[];if(t==="y"){const o=r.filter((x,p)=>{const m=i.find(u=>u.idx===p);return!m||m.yAxisId!=="y2"});return o.length===1&&(o[0].label||o[0].name)||""}if(t==="y2"){const o=r.filter((x,p)=>{const m=i.find(u=>u.idx===p);return(m==null?void 0:m.yAxisId)==="y2"});return o.length===1&&(o[0].label||o[0].name)||""}return""}function ln(){const t=s.useEditorStore(o=>o.card),n=s.useEditorStore(o=>{var x;return(x=o.card)==null?void 0:x.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),i=ye.useEffectiveEditorCardType();if(!t||["tornado","pyramid","kpi","treemap"].includes(i))return null;const c=s.AxisConfigurator.getAxisInfo(i,n);if(!c.hasXAxis&&!c.hasYAxis)return null;const l=(o,x)=>{let p;o==="x"?p="xAxisConfig":o==="y"?p="yAxisConfig":p="secondaryYAxisConfig";const m={...n||{},[p]:x};a(m);const u={...t,preferences:m};r(u)},d=c.hasY2Axis&&i==="combo";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(Qs,{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:[c.hasXAxis&&e.jsx(Xe,{axis:"x",label:"X-Axis",type:c.xAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(i,"x"),n==null?void 0:n.xAxisConfig),onChange:o=>l("x",o),defaultTitle:Ze("x",t,n)}),c.hasYAxis&&e.jsx(Xe,{axis:"y",label:d?"Y-Axis (Left)":"Y-Axis",type:c.yAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(i,"y"),n==null?void 0:n.yAxisConfig),onChange:o=>l("y",o),defaultTitle:Ze("y",t,n)}),d&&e.jsx(Xe,{axis:"y2",label:"Y2-Axis (Right)",type:"value",config:s.mergeAxisConfig({enabled:!0,position:"right"},n==null?void 0:n.secondaryYAxisConfig),onChange:o=>l("y2",o),defaultTitle:Ze("y2",t,n),hidePosition:!0})]})})]})}function on(){const t=s.useEditorStore(m=>m.card),n=ye.useEffectiveEditorCardType(),a=s.useEditorStore(m=>{var u,N,b,h;return(h=(b=(N=(u=m.card)==null?void 0:u.preferences)==null?void 0:N.chartOptions)==null?void 0:b.plugins)==null?void 0:h.legend}),{setLegendOptions:r}=s.useEditorActions();if(!t||!s.chartSupportsLegend(n))return null;const i=s.getDefaultLegendConfig(n),c=(i==null?void 0:i.display)??!0,l=(i==null?void 0:i.position)??"top",d=(i==null?void 0:i.align)??"center",o=(m,u)=>{const N={...a,[m]:u};r(N)},x=["top","bottom","left","right"],p=["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($t,{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:(a==null?void 0:a.display)??c,onCheckedChange:m=>o("display",m)})]}),((a==null?void 0:a.display)??c)&&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:(a==null?void 0:a.position)||l,onValueChange:m=>o("position",m),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:x.map(m=>e.jsx(s.SelectItem,{value:m,className:"text-xs",children:s.titleCase(m)},m))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(a==null?void 0:a.align)||d,onValueChange:m=>o("align",m),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:p.map(m=>e.jsx(s.SelectItem,{value:m,className:"text-xs",children:s.titleCase(m)},m))})]})]})]})]})})]})}function cn(){var A,S,R,F,z,G,V,U,Q,J,Z;const t=s.useEditorStore(q=>q.card),n=ye.useEffectiveEditorCardType(),a=s.useEditorStore(q=>{var Y,se;return(se=(Y=q.card)==null?void 0:Y.preferences)==null?void 0:se.dataLabelsConfig}),r=s.useEditorStore(q=>{var Y;return(Y=q.card)==null?void 0:Y.preferences}),{setCardPreferences:i,updateCardInFrame:c}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(n))return null;const l=n==="bullet"?((A=r==null?void 0:r.bulletConfig)==null?void 0:A.orientation)??(((S=r==null?void 0:r.chartOptions)==null?void 0:S.indexAxis)==="x"?"vertical":"horizontal"):void 0,d=l!=null?l==="horizontal":((R=r==null?void 0:r.chartOptions)==null?void 0:R.indexAxis)==="y",o=n==="stackedBar"||n==="stackedLine",x=n==="pie"||n==="doughnut"||n==="polarArea"||n==="funnel",p=!x,m=n==="bubble"||n==="scatter",u=(z=(F=r==null?void 0:r.chartOptions)==null?void 0:F.plugins)==null?void 0:z.datalabels,N=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),b=s.getDefaultDataLabelsConfig(n,t.preferences),h=a??b,y=(b==null?void 0:b.enabled)??N??!1,T=(a==null?void 0:a.enabled)!==void 0?a.enabled:y,C=(q,Y)=>{const _={...b??{},...a??{},[q]:Y};q==="enabled"&&(_.display=Y,Y&&m&&!_.position&&(_.position="bottom")),q==="position"&&m&&(_.position="bottom");const W={...t.preferences||{},dataLabelsConfig:_};i(W);const le={...t,preferences:W};c(le)},B=(q,Y)=>{const se=a??{},_={...b??{},...se,font:{...se.font||{},[q]:Y}},W={...t.preferences||{},dataLabelsConfig:_};i(W);const le={...t,preferences:W};c(le)},O=(q,Y)=>{const se=a??{},_={...b??{},...se,formatOptions:{...se.formatOptions||{},[q]:Y}},W={...t.preferences||{},dataLabelsConfig:_};i(W);const le={...t,preferences:W};c(le)},L=()=>{const q=n;return q==="stackedBar"||q==="stackedLine"||q==="pie"||q==="doughnut"?"center":d?"right":"top"},g=n!=="treemap"&&n!=="heatmap",w=n!=="treemap",E=L();let f=[];if(g)if(m)f=["bottom"];else if(o||x)f=["center"];else{const q=d?["center","left","right"]:["center","top","bottom"];f=["auto",...n==="bullet"?q:q.filter(se=>se!==E),"custom"]}const M=()=>s.titleCase(E),j=["center","start","end"],I=["center","start","end","top","bottom"],D=p?["auto","number","currency","percent","none"]:["number","currency","percent","none"],P=[{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"}],v=[{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(sa,{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:T,onCheckedChange:q=>C("enabled",q)})]}),T&&e.jsxs(e.Fragment,{children:[g&&!o&&!x&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:m?(h==null?void 0:h.position)||"bottom":(h==null?void 0:h.position)||"auto",onValueChange:q=>C("position",q),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map(q=>e.jsx(s.SelectItem,{value:q,className:"text-xs",children:q==="auto"?M():q==="custom"?"Custom (Advanced)":s.titleCase(q)},q))})]})]}),o&&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:(a==null?void 0:a.showTotal)??!1,onCheckedChange:q=>C("showTotal",q)})]}),(h==null?void 0:h.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:(h==null?void 0:h.anchor)||"center",onValueChange:q=>C("anchor",q),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:j.map(q=>e.jsx(s.SelectItem,{value:q,className:"text-xs",children:s.titleCase(q)},q))})]})]}),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((h==null?void 0:h.align)||"center"),onValueChange:q=>C("align",q),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:I.map(q=>e.jsx(s.SelectItem,{value:q,className:"text-xs",children:s.titleCase(q)},q))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(h==null?void 0:h.format)||(p?"auto":"none"),onValueChange:q=>C("format",q),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:D.map(q=>e.jsx(s.SelectItem,{value:q,className:"text-xs",children:q==="auto"&&p?"Auto (Use Axis)":q==="none"?"None (Raw Value)":s.titleCase(q)},q))})]})]}),(h==null?void 0:h.format)&&!["auto","none"].includes(h.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(h.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(Te,{type:"number",placeholder:"0",value:String(((G=h==null?void 0:h.formatOptions)==null?void 0:G.decimalPlaces)??(h.format==="currency"?2:h.format==="percent"?1:0)),onSave:q=>O("decimalPlaces",Number(q)),className:""})})]}),h.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:((V=h==null?void 0:h.formatOptions)==null?void 0:V.currency)||"USD",onValueChange:q=>O("currency",q),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:P.map(q=>e.jsx(s.SelectItem,{value:q.value,className:"text-xs",children:q.label},q.value))})]})]}),["number","currency"].includes(h.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:((U=h==null?void 0:h.formatOptions)==null?void 0:U.useSuffix)??!1,onCheckedChange:q=>O("useSuffix",q)})]}),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:((Q=h==null?void 0:h.formatOptions)==null?void 0:Q.locale)||"en-US",onValueChange:q=>O("locale",q),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:v.map(q=>e.jsx(s.SelectItem,{value:q.value,className:"text-xs",children:q.label},q.value))})]})]})]}),w&&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(Te,{type:"number",placeholder:"12",value:String(((J=h==null?void 0:h.font)==null?void 0:J.size)||12),onSave:q=>B("size",Number(q)),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:((Z=h==null?void 0:h.font)==null?void 0:Z.weight)||"normal",onValueChange:q=>B("weight",q),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:(h==null?void 0:h.color)==="auto"||!(h!=null&&h.color)?"auto":"custom",onValueChange:q=>{q==="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(Te,{type:"number",placeholder:"0",value:String((h==null?void 0:h.rotation)||0),onSave:q=>C("rotation",Number(q)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const Ps={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%
179
- 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 dn(){var u,N,b,h,y,T,C,B,O,L;const t=s.useEditorStore(g=>g.card),{setCardPreferences:n}=s.useEditorActions(),a=ye.useEffectiveEditorCardType(),r=((u=t.config)==null?void 0:u.metricColumns)||[],i=((N=t.config)==null?void 0:N.groupByColumns)||[],c=r.length===2&&i.length===0,l=r.some(g=>g.comparisonType&&g.comparisonType!=="none");if(!(a==="kpi"&&(c||l)))return null;const o=((h=(b=t.preferences)==null?void 0:b.kpiVisualOptions)==null?void 0:h.metricComparison)||{},x=g=>{var E;const w={...t.preferences,kpiVisualOptions:{...(E=t.preferences)==null?void 0:E.kpiVisualOptions,metricComparison:{...o,...g}}};n(w)},p=l||o.enabled,m=r.some(g=>g.comparisonType==="previous_period"||g.comparisonType==="same_period_last_year"||g.comparisonType==="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(Ys,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[c&&r.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:o.enabled||!1,onCheckedChange:g=>x({enabled:g,...g&&!o.calculationType?{calculationType:"difference"}:{}})})]}),p&&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 g=o.calculationType||"difference",w=Ps[g];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:w==null?void 0:w.label}),e.jsx("p",{children:w==null?void 0:w.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:w==null?void 0:w.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",w==null?void 0:w.example]})]})})()})]})]}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:g=>x({calculationType:g}),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(Ps).map(([g,w])=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:w.label},g))})]})]}),e.jsx(qe,{formatOptions:o.formatOptions||{},onFormatOptionsChange:g=>x({formatOptions:g}),showTitle:!0,title:"COMPARISON FORMAT"}),(m||c)&&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"}),c&&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:o.position||"right",onValueChange:g=>x({position:g}),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:o.showArrow!==!1,onCheckedChange:g=>x({showArrow:g})}),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:o.showColor!==!1,onCheckedChange:g=>x({showColor:g})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Le,{value:((y=o.colorConfig)==null?void 0:y.increase)||"green",onChange:g=>x({colorConfig:{...o.colorConfig,increase:g}}),label:"Primary > Secondary"}),e.jsx(Le,{value:((T=o.colorConfig)==null?void 0:T.decrease)||"red",onChange:g=>x({colorConfig:{...o.colorConfig,decrease:g}}),label:"Primary < Secondary"}),e.jsx(Le,{value:((C=o.colorConfig)==null?void 0:C.noChange)||"neutral",onChange:g=>x({colorConfig:{...o.colorConfig,noChange:g}}),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:o.conditionalLabel||!1,onCheckedChange:g=>x({conditionalLabel:g})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.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,{id:"label-increase",type:"text",value:((B=o.conditionalLabels)==null?void 0:B.increase)??"Increase",onChange:g=>x({conditionalLabels:{...o.conditionalLabels,increase:g.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,{id:"label-decrease",type:"text",value:((O=o.conditionalLabels)==null?void 0:O.decrease)??"Decrease",onChange:g=>x({conditionalLabels:{...o.conditionalLabels,decrease:g.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,{id:"label-no-change",type:"text",value:((L=o.conditionalLabels)==null?void 0:L.noChange)??"No change",onChange:g=>x({conditionalLabels:{...o.conditionalLabels,noChange:g.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,{id:"label-name",type:"text",value:o.labelName??"",onChange:g=>x({labelName:g.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function un(){var c,l;const t=s.useEditorStore(d=>d.card),{setCardPreferences:n}=s.useEditorActions();if(ye.useEffectiveEditorCardType()!=="kpi")return null;const r=((l=(c=t.preferences)==null?void 0:c.kpiVisualOptions)==null?void 0:l.formatOptions)||{},i=d=>{var x;const o={...t.preferences,kpiVisualOptions:{...(x=t.preferences)==null?void 0:x.kpiVisualOptions,formatOptions:d}};n(o)};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(qe,{formatOptions:r,onFormatOptionsChange:i,showTitle:!1})})]})}function mn(){var c;const t=s.useEditorStore(l=>{var d;return(d=l.card)==null?void 0:d.type}),n=s.useEditorStore(l=>{var d;return(d=l.card)==null?void 0:d.preferences}),{setCardPreferences:a}=s.useEditorActions();if(t!=="treemap")return null;const r=((c=n==null?void 0:n.chartOptions)==null?void 0:c.treemapColorMode)??"branch",i=l=>{const d={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,treemapColorMode:l}};a(d)};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:l=>i(l??"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."})]})]})]})})]})}const xn=Object.keys(s.HEATMAP_PRESET_PALETTES);function hn(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var N;return(N=u.card)==null?void 0:N.preferences}),{setCardPreferences:a}=s.useEditorActions(),r=(t==null?void 0:t.type)==="heatmap",i=(n==null?void 0:n.heatmapConfig)||{},c=i.colorPalette??"green",l=i.legendPosition??"bottom",d=k.useMemo(()=>i.colorRange&&i.colorRange[0]&&i.colorRange[1]?[i.colorRange[0],i.colorRange[1]]:[...s.DEFAULT_HEATMAP_CUSTOM_RANGE],[i.colorRange]),o=u=>{const N={...i,...u};N.colorPalette!=="custom"?delete N.colorRange:(!N.colorRange||!N.colorRange[0]||!N.colorRange[1])&&(N.colorRange=[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]),a({...n||{},heatmapConfig:N})},x=u=>{o({colorPalette:u,colorRange:u==="custom"?i.colorRange??[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},p=(u,N)=>{const b=[...d];b[u]=N,o({colorPalette:"custom",colorRange:b})},m=u=>{o({legendPosition:u})};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:c,onValueChange:u=>x(u??"blue"),className:"space-y-3",children:[xn.map(u=>{const N=s.HEATMAP_PRESET_PALETTES[u];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-${u}`,value:u}),e.jsxs(s.Label,{htmlFor:`heatmap-${u}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:N.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${N.start}, ${N.end})`}})]})]},u)}),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"})]}),c==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(Le,{value:d[0],onChange:u=>p(0,u),label:"Start color"}),e.jsx(Le,{value:d[1],onChange:u=>p(1,u),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:l,onValueChange:u=>m(u??"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(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:u[0].toUpperCase()+u.slice(1)},u))})]})]})]})]}):null}const Vs=["poor","satisfactory","good"];function zs(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 pn(){var D,P;const t=s.useEditorStore(v=>v.card.preferences),n=s.useEditorStore(v=>v.card),a=s.useEditorStore(v=>v.isDevMode),{setCardPreferences:r,setChartOrientation:i}=s.useEditorActions(),c=k.useMemo(()=>(t==null?void 0:t.bulletConfig)||{},[t==null?void 0:t.bulletConfig]),d=s.hasValidCardConfig(n==null?void 0:n.config)&&!a,[o,x]=k.useState(c.showRanges??!1),[p,m]=k.useState(c.rangesArePercentages??!1),u=c.disableAutoComparative?!1:c.comparativeMetricKey!==void 0||!d,[N,b]=k.useState(u);k.useEffect(()=>{x(c.showRanges??!1)},[c.showRanges]),k.useEffect(()=>{m(c.rangesArePercentages??!1)},[c.rangesArePercentages]);const h=c.targetValue===void 0?"":String(c.targetValue);k.useEffect(()=>{const v=c.disableAutoComparative?!1:c.comparativeMetricKey!==void 0||!d;b(v)},[c.disableAutoComparative,c.comparativeMetricKey,d]);const y=k.useMemo(()=>{var v,A;return((A=(v=n==null?void 0:n.config)==null?void 0:v.metricColumns)==null?void 0:A.map(S=>{const R=S.label||S.name||S.alias||"";return{value:R,label:R}}))||[]},[(D=n==null?void 0:n.config)==null?void 0:D.metricColumns]);k.useEffect(()=>{var V,U;if(!t||y.length===0)return;const v={};let A=!1;const S=(V=y[1])==null?void 0:V.value;!c.targetMetricKey&&S&&(v.targetMetricKey=S,A=!0);const R=(U=y[2])==null?void 0:U.value;!c.comparativeMetricKey&&!c.disableAutoComparative&&R&&(v.comparativeMetricKey=R,A=!0);const F=y.slice(3),z={...c.rangeKeys||{}};let G=!1;if(Vs.forEach((Q,J)=>{!z[Q]&&F[J]&&(z[Q]=F[J].value,G=!0)}),G&&(v.rangeKeys=z,A=!0,c.showRanges===void 0&&(v.showRanges=!0)),A){const Q=zs({...c,...v});r({...t,bulletConfig:Q})}},[y,c,t,r]);const T=v=>{const A=zs({...c,...v});r({...t,bulletConfig:A})},C=(v,A)=>{const S={...c.rangeKeys||{},[v]:A.trim()};A.trim()||delete S[v],T({rangeKeys:Object.keys(S).length>0?S:void 0})},B=(v,A)=>{const S=A===""?void 0:Number(A),R={...c.ranges||{}};S===void 0||Number.isNaN(S)?delete R[v]:R[v]=S,T({ranges:Object.keys(R).length?R:void 0})},O=v=>{if(v===""){T({targetValue:void 0});return}const A=Number(v);T({targetValue:Number.isNaN(A)?void 0:A})},L=(v,A)=>{const S=A.trim(),R={...c.rangeLabels||{}};S?R[v]=S:delete R[v],T({rangeLabels:Object.keys(R).length>0?R:void 0})},g=v=>{x(v),T({showRanges:v})},w=v=>{m(v),T({rangesArePercentages:v})},E=c.orientation||(((P=t==null?void 0:t.chartOptions)==null?void 0:P.indexAxis)==="y"?"horizontal":"vertical"),f=v=>{T({orientation:v}),i(v==="horizontal"?"y":"x")},M=[{value:"__none",label:"None"},...y.map(v=>({value:v.value,label:v.label}))],j=M,I=v=>{if(b(v),!v){T({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!d){T({disableAutoComparative:!1});return}if(c.comparativeMetricKey)T({disableAutoComparative:!1});else{const A=y.find(S=>S.value!==c.targetMetricKey);T({comparativeMetricKey:A==null?void 0:A.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:E,onValueChange:v=>f(v),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"})]})]})]}),d&&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:c.targetMetricKey||"__none",onValueChange:v=>T({targetMetricKey:v==="__none"?void 0:v}),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"}),y.map(v=>e.jsx(s.SelectItem,{value:v.value,className:"text-xs",children:v.label},v.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),d?e.jsxs(s.Select,{value:c.comparativeMetricKey||"__none",onValueChange:v=>T({comparativeMetricKey:v==="__none"?void 0:v,disableAutoComparative:v==="__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(v=>e.jsx(s.SelectItem,{value:v.value,className:"text-xs",children:v.label},v.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:N,onCheckedChange:v=>I(v)})]}),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(Se,{type:"number",className:"h-8 text-xs",value:h,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:g})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:p,disabled:!o,onChange:v=>w(v.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:Vs.map(v=>{var A,S,R,F,z;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:[v," LABEL"]}),e.jsx(Se,{placeholder:`Display label (${v})`,value:((A=c.rangeLabels)==null?void 0:A[v])||"",onCommit:G=>L(v,G),className:"h-8 text-xs"})]}),d?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[v," COLUMN"]}),e.jsxs(s.Select,{value:((S=c.rangeKeys)==null?void 0:S[v])||"__none",onValueChange:G=>{G==="__none"?C(v,""):C(v,G)},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select column"})}),e.jsx(s.SelectContent,{children:j.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:[v," COLUMN KEY"]}),e.jsx(Se,{placeholder:"Column key",value:((R=c.rangeKeys)==null?void 0:R[v])||"",onCommit:G=>C(v,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:[v," VALUE"]}),e.jsx(Se,{type:"number",placeholder:p?"0.80":"Static value",value:((F=c.ranges)==null?void 0:F[v])===void 0?"":String((z=c.ranges)==null?void 0:z[v]),onCommit:G=>B(v,G),className:"h-8 text-xs"})]})]},v)})})]})]})]})}function $s(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 fn(){var L,g,w,E,f,M,j,I,D,P,v,A;const t=s.useEditorStore(S=>S.card.preferences),n=s.useEditorStore(S=>S.card),a=ye.useEffectiveEditorCardType(),r=s.useEditorStore(S=>S.isDevMode),{setCardPreferences:i,updateCardInFrame:c}=s.useEditorActions(),l=a==="bubble",d=a==="scatter",o=k.useMemo(()=>(t==null?void 0:t.bubbleScatterConfig)||{},[t==null?void 0:t.bubbleScatterConfig]),p=s.hasValidCardConfig(n==null?void 0:n.config)&&!r,m=k.useMemo(()=>{var S,R;return((R=(S=n==null?void 0:n.config)==null?void 0:S.metricColumns)==null?void 0:R.map(F=>{const z=F.label||F.name||F.alias||"";return{value:z,label:z}}))||[]},[(L=n==null?void 0:n.config)==null?void 0:L.metricColumns]),u=k.useMemo(()=>{var S,R;return((R=(S=n==null?void 0:n.config)==null?void 0:S.groupByColumns)==null?void 0:R.map(F=>{const z=F.label||F.name||F.alias||"";return{value:z,label:z}}))||[]},[(g=n==null?void 0:n.config)==null?void 0:g.groupByColumns]),N=k.useMemo(()=>o.enableGrouping!==void 0?o.enableGrouping:!r&&u.length>=2,[o.enableGrouping,r,u.length]),[b,h]=k.useState(N);k.useEffect(()=>{h(N)},[N]);const y=S=>{const R={...t||{},bubbleScatterConfig:S};i(R),n&&c({...n,preferences:R})},T=S=>{i(S),n&&c({...n,preferences:S})};k.useEffect(()=>{if(!t||m.length===0)return;const S={};let R=!1;if(!o.xMetricKey&&m[0]&&(S.xMetricKey=m[0].value,R=!0),!o.yMetricKey&&m[1]&&(S.yMetricKey=m[1].value,R=!0),l&&!o.radiusMetricKey&&m[2]&&(S.radiusMetricKey=m[2].value,R=!0),!o.labelKey&&u[0]&&(S.labelKey=u[0].value,R=!0),N&&!o.groupKey&&u[1]&&(S.groupKey=u[1].value,S.enableGrouping=!0,R=!0),R){const F=$s({...o,...S});y(F)}},[m,u,o,t,i,l,N]);const C=S=>{const R=$s({...o,...S});y(R)},B=S=>{h(S),C({enableGrouping:S,groupKey:S?o.groupKey:void 0})};if(!l&&!d)return null;const O=l?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:[l?"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"}),p?e.jsxs(s.Select,{value:o.labelKey||"",onValueChange:S=>C({labelKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select label column"})}),e.jsx(s.SelectContent,{children:u.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for labels",value:o.labelKey||"",onCommit:S=>C({labelKey:S})})]}),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:b,onCheckedChange:B})]}),b&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Group By"}),p?e.jsxs(s.Select,{value:o.groupKey||"",onValueChange:S=>C({groupKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select group column"})}),e.jsx(s.SelectContent,{children:u.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:o.groupKey||"",onCommit:S=>C({groupKey:S})})]})]}),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"}),p?e.jsxs(s.Select,{value:o.xMetricKey||"",onValueChange:S=>C({xMetricKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select X metric"})}),e.jsx(s.SelectContent,{children:m.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:o.xMetricKey||"",onCommit:S=>C({xMetricKey:S})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Axis"}),p?e.jsxs(s.Select,{value:o.yMetricKey||"",onValueChange:S=>C({yMetricKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(s.SelectContent,{children:m.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:o.yMetricKey||"",onCommit:S=>C({yMetricKey:S})})]}),l&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Radius"}),p?e.jsxs(s.Select,{value:o.radiusMetricKey||"",onValueChange:S=>C({radiusMetricKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(s.SelectContent,{children:m.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for radius",value:o.radiusMetricKey||"",onCommit:S=>C({radiusMetricKey:S})})]})]}),l&&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:S=>C({radiusScale:S}),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(Se,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((w=o.minRadius)==null?void 0:w.toString())||"",onCommit:S=>C({minRadius:S?Number(S):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Max Radius"}),e.jsx(Se,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((E=o.maxRadius)==null?void 0:E.toString())||"",onCommit:S=>C({maxRadius:S?Number(S):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:([S])=>C({fixedRadius:S}),min:3,max:30,step:1,className:"py-2"})]})]}),d&&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:([S])=>C({fixedRadius:S}),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=(f=t==null?void 0:t.xAxisConfig)==null?void 0:f.name)==null?void 0:M.enabled)??!1,onCheckedChange:S=>{var z,G,V,U;const R=o.xMetricKey||"X Axis",F=o.yMetricKey||"Y Axis";T({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{enabled:S,text:((G=(z=t==null?void 0:t.xAxisConfig)==null?void 0:z.name)==null?void 0:G.text)||R}},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{enabled:S,text:((U=(V=t==null?void 0:t.yAxisConfig)==null?void 0:V.name)==null?void 0:U.text)||F}}})}})]}),((I=(j=t==null?void 0:t.xAxisConfig)==null?void 0:j.name)==null?void 0:I.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(Se,{className:"h-8 text-xs",placeholder:o.xMetricKey||"X Axis",value:((P=(D=t==null?void 0:t.xAxisConfig)==null?void 0:D.name)==null?void 0:P.text)||"",onCommit:S=>{var R;T({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{...(R=t==null?void 0:t.xAxisConfig)==null?void 0:R.name,enabled:!0,text:S||o.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Title"}),e.jsx(Se,{className:"h-8 text-xs",placeholder:o.yMetricKey||"Y Axis",value:((A=(v=t==null?void 0:t.yAxisConfig)==null?void 0:v.name)==null?void 0:A.text)||"",onCommit:S=>{var R;T({...t??{},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{...(R=t==null?void 0:t.yAxisConfig)==null?void 0:R.name,enabled:!0,text:S||o.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const gn=[{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 jn(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var N;return(N=u.card)==null?void 0:N.preferences}),{setCardPreferences:a}=s.useEditorActions(),r=(t==null?void 0:t.type)==="funnel",i=(n==null?void 0:n.funnelConfig)||{},c=i.percentMode??"percentOfTotal",l=i.shrinkFraction??1,d=i.labelThreshold??0,o=u=>{const N={...i,...u};a({...n||{},funnelConfig:N})},x=u=>{o({percentMode:u})},p=u=>{o({shrinkFraction:u[0]})},m=u=>{o({labelThreshold:u[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:c,onValueChange:u=>x(u),className:"space-y-2",children:gn.map(u=>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-${u.value}`,value:u.value,className:"mt-0.5"}),e.jsxs(s.Label,{htmlFor:`funnel-${u.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})]},u.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:[l],onValueChange:p,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(l*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:[d],onValueChange:m,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:d===0?"Showing all labels":`Hide labels below ${d}%`})]})]})]}):null}function Ke(){const t=s.useEditorStore(c=>c.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(c=>!s.METADATA_KEYS.includes(c));let i=r;if(["stackedBar","stackedLine"].includes(t.type)){const c=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:l}=s.getKeys(c);i=l.slice(1)}return{transformedMetricKeys:i,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}const bn=[{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"}],yn=[{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)"}],vn=["center","start","end"],Nn=["center","start","end","top","bottom"];function Ge({config:t,onChange:n,isHorizontal:a=!1,showAutoFormat:r=!0,positionOptions:i,showAppearance:c=!0}){var b,h,y,T,C,B;const l=i??(a?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),d=r?["auto","number","currency","percent","none"]:["number","currency","percent","none"],o=(O,L)=>{const g={...t,[O]:L};n(g)},x=(O,L)=>{const g={...t,font:{...(t==null?void 0:t.font)||{},[O]:L}};n(g)},p=(O,L)=>{const g={...t,formatOptions:{...(t==null?void 0:t.formatOptions)||{},[O]:L}};n(g)},m=()=>a?"Right":"Top",u=t||{},N=u.format||(r?"auto":"number");return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:u.position||"auto",onValueChange:O=>o("position",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:l.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:O==="auto"?m():O==="custom"?"Custom (Advanced)":s.titleCase(O)},O))})]})]}),u.position==="custom"&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Anchor"}),e.jsxs(s.Select,{value:u.anchor||"center",onValueChange:O=>o("anchor",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:vn.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:s.titleCase(O)},O))})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Align"}),e.jsxs(s.Select,{value:String(u.align||"center"),onValueChange:O=>o("align",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Nn.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:s.titleCase(O)},O))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Format"}),e.jsxs(s.Select,{value:N,onValueChange:O=>o("format",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:O==="auto"&&r?"Auto (Use Axis)":O==="none"?"None (Raw Value)":s.titleCase(O)},O))})]})]}),!["auto","none"].includes(N)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[["number","currency","percent"].includes(N)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Decimals"}),e.jsx("div",{className:"w-16",children:e.jsx(Te,{type:"number",placeholder:"0",value:String(((b=u.formatOptions)==null?void 0:b.decimalPlaces)??(N==="currency"?2:N==="percent"?1:0)),onSave:O=>p("decimalPlaces",Number(O)),className:""})})]}),N==="currency"&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Currency"}),e.jsxs(s.Select,{value:((h=u.formatOptions)==null?void 0:h.currency)||"USD",onValueChange:O=>p("currency",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:bn.map(O=>e.jsx(s.SelectItem,{value:O.value,className:"text-xs",children:O.label},O.value))})]})]}),["number","currency"].includes(N)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((y=u.formatOptions)==null?void 0:y.useSuffix)??!1,onCheckedChange:O=>p("useSuffix",O)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Locale"}),e.jsxs(s.Select,{value:((T=u.formatOptions)==null?void 0:T.locale)||"en-US",onValueChange:O=>p("locale",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:yn.map(O=>e.jsx(s.SelectItem,{value:O.value,className:"text-xs",children:O.label},O.value))})]})]})]}),c&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Appearance"}),e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Size"}),e.jsx("div",{className:"w-16",children:e.jsx(Te,{type:"number",placeholder:"12",value:String(((C=u.font)==null?void 0:C.size)||12),onSave:O=>x("size",Number(O)),className:""})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Weight"}),e.jsxs(s.Select,{value:((B=u.font)==null?void 0:B.weight)||"normal",onValueChange:O=>x("weight",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-24 text-xs",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 justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Color"}),e.jsxs(s.Select,{value:u.color==="auto"||!u.color?"auto":"custom",onValueChange:O=>{O==="auto"&&o("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Rotation"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-12",children:e.jsx(Te,{type:"number",placeholder:"0",value:String(u.rotation||0),onSave:O=>o("rotation",Number(O)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const Cn=[{type:"bar",icon:s.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:s.ChartLine,label:"Line"}],Sn=[0,1,2,3,4,5,6,8,10],wn=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],Tn=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function En(){return s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type})!=="combo"?null:e.jsxs(s.AccordionItem,{value:"combo-series",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.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(kn,{})})]})}function kn(){const{transformedMetricKeys:t}=Ke();return t.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:t.map((n,a)=>e.jsx(In,{metricKey:n,idx:a},n))})}function In({metricKey:t,idx:n}){var T;const[a,r]=k.useState(!1),i=s.useEditorStore(C=>{var B;return(B=C.card)==null?void 0:B.preferences}),c=s.useEditorStore(C=>{var B,O;return(O=(B=C.card)==null?void 0:B.preferences)==null?void 0:O.datasetOptions}),l=c==null?void 0:c.find(C=>C.idx===n),{setCardPreferences:d}=s.useEditorStore(C=>C.actions),o=(l==null?void 0:l.type)||"bar",x=(l==null?void 0:l.yAxisId)||"y",p=((T=l==null?void 0:l.dataLabels)==null?void 0:T.enabled)??!1,m=o==="line"?s.ChartLine:s.ChartColumnIncreasing;function u(C){const B={idx:n,type:o,yAxisId:x,dataLabels:l==null?void 0:l.dataLabels,...C};if(!l)d({...i||{},datasetOptions:[...c||[],B]});else{const O=c==null?void 0:c.map(L=>L.idx===n?{...L,...B}:L);d({...i||{},datasetOptions:O})}}function N(C){u({type:C})}function b(C){u({yAxisId:C})}function h(C){u({dataLabels:{...l==null?void 0:l.dataLabels,enabled:C}})}function y(C){u({dataLabels:C})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsxs("span",{className:s.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(m,{className:"h-3 w-3"}),o==="line"?"Line":"Bar"]}),e.jsx("span",{className:s.cn("rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:x==="y2"?"Y2":"Y1"})]})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"flex items-end gap-4",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Chart Type"}),e.jsx("div",{className:"flex gap-2",children:Cn.map(({type:C,icon:B,label:O})=>{const L=o===C;return e.jsxs("button",{onClick:()=>N(C),className:s.cn("flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs transition-colors",L?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:[e.jsx(B,{className:"h-4 w-4"}),e.jsx("span",{children:O})]},C)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Axis"}),e.jsxs(s.Select,{value:x,onValueChange:C=>b(C),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"y",className:"text-xs",children:"Y1 (Left)"}),e.jsx(s.SelectItem,{value:"y2",className:"text-xs",children:"Y2 (Right)"})]})]})]})]}),o==="line"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(s.Select,{value:(l==null?void 0:l.lineStyle)||"solid",onValueChange:C=>u({lineStyle:C}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Tn.map(({value:C,label:B})=>e.jsx(s.SelectItem,{value:C,className:"text-xs",children:B},C))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(s.Select,{value:String((l==null?void 0:l.pointRadius)??3),onValueChange:C=>u({pointRadius:Number(C)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Sn.map(C=>e.jsx(s.SelectItem,{value:String(C),className:"text-xs",children:C===0?"None":C},C))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(s.Select,{value:(l==null?void 0:l.pointStyle)||"circle",onValueChange:C=>u({pointStyle:C}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:wn.map(({value:C,label:B})=>e.jsx(s.SelectItem,{value:C,className:"text-xs",children:B},C))})]})]})]})]}),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 text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:p,onCheckedChange:h})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Ge,{config:l==null?void 0:l.dataLabels,onChange:y,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const es=[{value:"origin",label:"Origin (X-axis)",description:"Fill to the X-axis (y=0)"},{value:"start",label:"Start (Top)",description:"Fill to the top of chart area"},{value:"end",label:"End (Bottom)",description:"Fill to the bottom of chart area"},{value:"-1",label:"Previous Series",description:"Fill to the series below"},{value:"+1",label:"Next Series",description:"Fill to the series above"},{value:"false",label:"No Fill (Line)",description:"Show as line without fill"}],An=[0,1,2,3,4,5,6,8,10],Dn=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],Ln=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Mn(t){return t==null?"origin":t===!1?"false":t}function On(){const t=s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type});return t!=="area"&&t!=="stackedArea"?null:e.jsxs(s.AccordionItem,{value:"area-series",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.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(Fn,{})})]})}function Fn(){const{transformedMetricKeys:t}=Ke();return t.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:t.map((n,a)=>e.jsx(Rn,{metricKey:n,idx:a},n))})}function Rn({metricKey:t,idx:n}){var h;const[a,r]=k.useState(!1),i=s.useEditorStore(y=>{var T;return(T=y.card)==null?void 0:T.preferences}),c=s.useEditorStore(y=>{var T,C;return(C=(T=y.card)==null?void 0:T.preferences)==null?void 0:C.datasetOptions}),l=c==null?void 0:c.find(y=>y.idx===n),{setCardPreferences:d}=s.useEditorStore(y=>y.actions),o=Mn(l==null?void 0:l.fill),x=((h=l==null?void 0:l.dataLabels)==null?void 0:h.enabled)??!1,p=es.find(y=>y.value===o)||es[0];function m(y){const T={idx:n,fill:o,dataLabels:l==null?void 0:l.dataLabels,...y};if(!l)d({...i||{},datasetOptions:[...c||[],T]});else{const C=c==null?void 0:c.map(B=>B.idx===n?{...B,...T}:B);d({...i||{},datasetOptions:C})}}function u(y){m({fill:y==="false"?!1:y})}function N(y){m({dataLabels:{...l==null?void 0:l.dataLabels,enabled:y}})}function b(y){m({dataLabels:y})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:s.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(s.ChartArea,{className:"h-3 w-3"}),p.label.split(" ")[0]]})})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Fill Target"}),e.jsxs(s.Select,{value:o,onValueChange:y=>u(y),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:es.map(y=>e.jsx(s.SelectItem,{value:y.value,className:"text-xs",children:e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{children:y.label})})},y.value))})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(s.Select,{value:(l==null?void 0:l.lineStyle)||"solid",onValueChange:y=>m({lineStyle:y}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ln.map(({value:y,label:T})=>e.jsx(s.SelectItem,{value:y,className:"text-xs",children:T},y))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(s.Select,{value:String((l==null?void 0:l.pointRadius)??3),onValueChange:y=>m({pointRadius:Number(y)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:An.map(y=>e.jsx(s.SelectItem,{value:String(y),className:"text-xs",children:y===0?"None":y},y))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(s.Select,{value:(l==null?void 0:l.pointStyle)||"circle",onValueChange:y=>m({pointStyle:y}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Dn.map(({value:y,label:T})=>e.jsx(s.SelectItem,{value:y,className:"text-xs",children:T},y))})]})]})]})]}),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 text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:x,onCheckedChange:N})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Ge,{config:l==null?void 0:l.dataLabels,onChange:b,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Bn=[0,1,2,3,4,5,6,8,10],Pn=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],ss=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Vn(){return s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type})!=="line"?null:e.jsxs(s.AccordionItem,{value:"line-series",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.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(zn,{})})]})}function zn(){const{transformedMetricKeys:t}=Ke();return t.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:t.map((n,a)=>e.jsx($n,{metricKey:n,idx:a},n))})}function $n({metricKey:t,idx:n}){var y;const[a,r]=k.useState(!1),i=s.useEditorStore(T=>{var C;return(C=T.card)==null?void 0:C.preferences}),c=s.useEditorStore(T=>{var C,B;return(B=(C=T.card)==null?void 0:C.preferences)==null?void 0:B.datasetOptions}),l=c==null?void 0:c.find(T=>T.idx===n),{setCardPreferences:d}=s.useEditorStore(T=>T.actions),o=(l==null?void 0:l.lineStyle)||"solid",x=(l==null?void 0:l.pointRadius)??3,p=(l==null?void 0:l.pointStyle)||"circle",m=((y=l==null?void 0:l.dataLabels)==null?void 0:y.enabled)??!1,u=ss.find(T=>T.value===o)||ss[0];function N(T){const C={idx:n,lineStyle:o,pointRadius:x,pointStyle:p,dataLabels:l==null?void 0:l.dataLabels,...T};if(!l)d({...i||{},datasetOptions:[...c||[],C]});else{const B=c==null?void 0:c.map(O=>O.idx===n?{...O,...C}:O);d({...i||{},datasetOptions:B})}}function b(T){N({dataLabels:{...l==null?void 0:l.dataLabels,enabled:T}})}function h(T){N({dataLabels:T})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:s.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(s.TrendingUp,{className:"h-3 w-3"}),u.label.split(" ")[0]]})})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(s.Select,{value:o,onValueChange:T=>N({lineStyle:T}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:ss.map(({value:T,label:C})=>e.jsx(s.SelectItem,{value:T,className:"text-xs",children:C},T))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(s.Select,{value:String(x),onValueChange:T=>N({pointRadius:Number(T)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Bn.map(T=>e.jsx(s.SelectItem,{value:String(T),className:"text-xs",children:T===0?"None":T},T))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(s.Select,{value:p,onValueChange:T=>N({pointStyle:T}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Pn.map(({value:T,label:C})=>e.jsx(s.SelectItem,{value:T,className:"text-xs",children:C},T))})]})]})]})]}),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 text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:m,onCheckedChange:b})]}),m&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Ge,{config:l==null?void 0:l.dataLabels,onChange:h,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const qn=[0,2,4,6,8,10,12,16,20];function Kn(){const t=s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type});return!t||!["bar","horizontalBar","stackedBar"].includes(t)?null:e.jsxs(s.AccordionItem,{value:"bar-series",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.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(Gn,{})})]})}function Gn(){const{transformedMetricKeys:t}=Ke();return t.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:t.map((n,a)=>e.jsx(Un,{metricKey:n,idx:a},n))})}function Un({metricKey:t,idx:n}){var b;const[a,r]=k.useState(!1),i=s.useEditorStore(h=>{var y;return(y=h.card)==null?void 0:y.type}),c=s.useEditorStore(h=>{var y;return(y=h.card)==null?void 0:y.preferences}),l=s.useEditorStore(h=>{var y,T;return(T=(y=h.card)==null?void 0:y.preferences)==null?void 0:T.datasetOptions}),d=l==null?void 0:l.find(h=>h.idx===n),{setCardPreferences:o}=s.useEditorStore(h=>h.actions),x=(d==null?void 0:d.borderRadius)??0,p=((b=d==null?void 0:d.dataLabels)==null?void 0:b.enabled)??!1;function m(h){const y={idx:n,borderRadius:x,dataLabels:d==null?void 0:d.dataLabels,...h};if(!d)o({...c||{},datasetOptions:[...l||[],y]});else{const T=l==null?void 0:l.map(C=>C.idx===n?{...C,...y}:C);o({...c||{},datasetOptions:T})}}function u(h){m({dataLabels:{...d==null?void 0:d.dataLabels,enabled:h}})}function N(h){m({dataLabels:h})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:x>0&&e.jsxs("span",{className:s.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(s.ChartColumn,{className:"h-3 w-3"}),"r:",x]})})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Bar Style"}),e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Corner Radius"}),e.jsxs(s.Select,{value:String(x),onValueChange:h=>m({borderRadius:Number(h)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:qn.map(h=>e.jsx(s.SelectItem,{value:String(h),className:"text-xs",children:h===0?"None":`${h}px`},h))})]})]})})]}),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 text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:p,onCheckedChange:u})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Ge,{config:d==null?void 0:d.dataLabels,onChange:N,isHorizontal:i==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const _n=[0,1,2,3,4,5,6,8,10],Hn=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],Jn=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Yn(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var o;return(o=d.card)==null?void 0:o.preferences}),a=ye.useEffectiveEditorCardType(),r=n==null?void 0:n.lineStyleConfig,{setCardPreferences:i,updateCardInFrame:c}=s.useEditorActions();if(!t||!["line","area","stackedArea"].includes(a))return null;const l=(d,o)=>{const x={...n||{},lineStyleConfig:{...r,[d]:o}};i(x),c({...t,preferences:x})};return e.jsxs(s.AccordionItem,{value:"line-style",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(Xt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Line Style"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all series. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Line Pattern"}),e.jsxs(s.Select,{value:(r==null?void 0:r.lineStyle)||"solid",onValueChange:d=>l("lineStyle",d),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Jn.map(({value:d,label:o})=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Point Size"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.pointRadius)??3),onValueChange:d=>l("pointRadius",Number(d)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:_n.map(d=>e.jsx(s.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":d},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Point Shape"}),e.jsxs(s.Select,{value:(r==null?void 0:r.pointStyle)||"circle",onValueChange:d=>l("pointStyle",d),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Hn.map(({value:d,label:o})=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]})]})})]})}const Qn=[0,2,4,6,8,10,12,16,20],Wn=[{value:"0.5",label:"50%"},{value:"0.6",label:"60%"},{value:"0.7",label:"70%"},{value:"0.8",label:"80%"},{value:"0.9",label:"90%"},{value:"1",label:"100%"}],Xn=[{value:"0.5",label:"50%"},{value:"0.6",label:"60%"},{value:"0.7",label:"70%"},{value:"0.8",label:"80%"},{value:"0.9",label:"90%"},{value:"1",label:"100%"}];function Zn(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var o;return(o=d.card)==null?void 0:o.preferences}),a=ye.useEffectiveEditorCardType(),r=n==null?void 0:n.barStyleConfig,{setCardPreferences:i,updateCardInFrame:c}=s.useEditorActions();if(!t||!["bar","horizontalBar","stackedBar"].includes(a))return null;const l=(d,o)=>{const x={...n||{},barStyleConfig:{...r,[d]:o}};i(x),c({...t,preferences:x})};return e.jsxs(s.AccordionItem,{value:"bar-style",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.ChartColumn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bar Style"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all bars. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Corner Radius"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.borderRadius)??0),onValueChange:d=>l("borderRadius",Number(d)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Qn.map(d=>e.jsx(s.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":`${d}px`},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Bar Width"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.barPercentage)??.9),onValueChange:d=>l("barPercentage",Number(d)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Wn.map(({value:d,label:o})=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Category Width"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.categoryPercentage)??.8),onValueChange:d=>l("categoryPercentage",Number(d)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Xn.map(({value:d,label:o})=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]})]})})]})}function er(){const t=s.useEditorStore(a=>{var r,i;return(i=(r=a==null?void 0:a.card)==null?void 0:r.preferences)==null?void 0:i.sortChart}),{setSortChart:n}=s.useEditorActions();return e.jsxs(s.AccordionItem,{value:"stacked-sort",children:[e.jsx(s.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.ArrowUpDown,{className:"h-4 w-4"}),"Sort"]})}),e.jsx(s.AccordionContent,{className:"space-y-4 px-1",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort Order"}),e.jsx(De,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"Ascending",value:"asc"},{label:"Descending",value:"desc"}],value:t||"none",onValueChange:a=>{n(a)}})]})})]})}const sr=["kpi"],qs={none:"None",previous_period:"Previous Period",same_period_last_year:"Same Period Last Year",start_vs_end:"Start vs End",target:"Target"},ts=2;function Re(t){return typeof t=="string"?t.trim().toLowerCase():((t==null?void 0:t.id)||(t==null?void 0:t.qualifiedFieldName)||(t==null?void 0:t.name)||(t==null?void 0:t.label)||"").trim().toLowerCase()}function tr(t){if(!(t!=null&&t.name)||!(t!=null&&t.dataType)||t.role==="metric")return!1;const n=s.getDataType(t.dataType);return["date","string","boolean"].includes(n)}function ar(t){return{...t,role:"groupby"}}function nr(){var C,B,O,L;const t=s.useEditorStore(g=>g.card),n=s.useEditorStore(g=>g.actions.updateCardConfig),a=ye.useEffectiveEditorCardType(),{scopedFields:r}=s.useScopedFields(),i=((C=t.config)==null?void 0:C.metricColumns)||[],c=((B=t.config)==null?void 0:B.summary)||{},l=c.breakdownDimensions||[],d=sr.includes(a),o=i.length>0,x=c.enabled===!0,p=d&&o,m=((O=t.config)==null?void 0:O.comparisonType)||((L=i.find(g=>g.comparisonType&&g.comparisonType!=="none"))==null?void 0:L.comparisonType)||"none",u=qs[m]||qs.none,N=Array.from(new Map(r.filter(tr).map(g=>[Re(g),ar(g)])).values()),b=new Set(N.map(g=>Re(g))),h=new Set(l.map(g=>Re(g)).filter(g=>g&&b.has(g)));if(!d)return null;const y=g=>{n(t.id,{summary:{...c,...g}})},T=(g,w)=>{const E=Re(g),f=N.filter(j=>h.has(Re(j))),M=w?h.has(E)?f:[...f,g].slice(0,ts):f.filter(j=>Re(j)!==E);y({breakdownDimensions:M})};return e.jsxs(s.AccordionItem,{value:"summary",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.FileText,{className:"h-4 w-4"}),e.jsx("span",{children:"Summary"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{htmlFor:"summary-enabled",className:"text-xs",children:"Enable Summary"}),!o&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Add at least one metric to enable summary."})]}),e.jsx(s.SmallSwitch,{id:"summary-enabled",checked:x,disabled:!p,onCheckedChange:g=>{if(!g){y({enabled:!1,showOnCard:!1,includeInDashboardSummary:!1});return}y({enabled:!0,showOnCard:c.showOnCard??!0,includeInDashboardSummary:c.includeInDashboardSummary??!0,anomalyEnabled:c.anomalyEnabled??!0})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Comparison"}),e.jsxs("p",{className:"rounded-md border border-border bg-muted/40 px-2 py-1.5 text-xs",children:["Using: ",u]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparison is configured from card/metric comparison settings."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"summary-show-on-card",className:"text-xs",children:"Show summary on card"}),e.jsx(s.SmallSwitch,{id:"summary-show-on-card",checked:c.showOnCard===!0,disabled:!x,onCheckedChange:g=>y({showOnCard:g})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"summary-include-rollup",className:"text-xs",children:"Include in dashboard summary"}),e.jsx(s.SmallSwitch,{id:"summary-include-rollup",checked:c.includeInDashboardSummary===!0,disabled:!x,onCheckedChange:g=>y({includeInDashboardSummary:g})})]}),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 uppercase text-muted-foreground",children:"Breakdown Dimensions"}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[l.length,"/",ts]})]}),N.length===0?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"No dimension fields available for breakdown."}):e.jsx("div",{className:"max-h-40 space-y-2 overflow-y-auto rounded-md border border-border p-2",children:N.map(g=>{const w=Re(g),E=h.has(w),f=h.size>=ts,M=!x||!E&&f;return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(s.Checkbox,{id:`summary-breakdown-${w}`,checked:E,disabled:M,onCheckedChange:j=>T(g,j===!0)}),e.jsx(s.Label,{htmlFor:`summary-breakdown-${w}`,className:"cursor-pointer text-xs",children:g.label||g.name})]},w)})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"summary-anomaly",className:"text-xs",children:"Detect anomalies"}),e.jsx(s.SmallSwitch,{id:"summary-anomaly",checked:c.anomalyEnabled!==!1,disabled:!x,onCheckedChange:g=>y({anomalyEnabled:g})})]})]})]})}function ct({mode:t}){const n=s.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type});return e.jsxs(e.Fragment,{children:[n==="combo"&&e.jsx(En,{}),(n==="area"||n==="stackedArea")&&e.jsx(On,{}),n==="line"&&e.jsx(Vn,{}),(n==="bar"||n==="horizontalBar"||n==="stackedBar")&&e.jsx(Kn,{}),e.jsx(Yn,{}),e.jsx(Zn,{}),e.jsx(mn,{}),t==="config"&&e.jsx(un,{}),t==="config"&&e.jsx(dn,{}),t==="config"&&e.jsx(nr,{}),e.jsx(hn,{}),n==="bullet"&&e.jsx(pn,{}),n==="funnel"&&e.jsx(jn,{}),(n==="bubble"||n==="scatter")&&e.jsx(fn,{}),(n==="stackedBar"||n==="stackedLine")&&e.jsx(er,{}),e.jsx(rn,{}),e.jsx(ln,{}),e.jsx(on,{}),e.jsx(cn,{})]})}function rr(){const t=s.useEditorStore(a=>a.card),n=t==null?void 0:t.type;return n?e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx($e,{chartType:n}),e.jsx(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:e.jsx(ct,{mode:"dev"})})]}):null}function lr(){const t=s.useEditorStore(a=>a.card.type);function n(){switch(t){case"kpi":return e.jsx(Va,{});case"table":return e.jsx(sn,{});case"map":return e.jsx(Ka,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(lt,{})});case"text":return e.jsx(an,{});default:return e.jsx(rr,{})}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function or(){const t=k.useRef(null),n=k.useRef(null),a=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog);return k.useEffect(()=>{var i,c,l,d;r?((i=t.current)==null||i.resize(0),(c=n.current)==null||c.resize(0)):((l=t.current)==null||l.resize(25),(d=n.current)==null||d.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(ma,{})}),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(lr,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Ms,{})})]}):e.jsx(Ms,{})})]})}function ir(t){var he;s.useAIInteractionStore($=>$.currentAIContext);const[n,a]=k.useState(""),[r,i]=k.useState(null),{authToken:c,tokenProps:l}=s.useSemaphorContext(),d=s.useEditorStore($=>{var H;return(H=$==null?void 0:$.card)==null?void 0:H.sql}),o=s.useEditorStore($=>$.isDevMode),x=s.useEditorStore($=>{var H;return(H=$==null?void 0:$.card)==null?void 0:H.python}),{setCardPython:p,setCardSql:m,setRunSql:u,switchCardType:N,setQueryConfig:b}=s.useEditorActions(),h=s.useEditorStore($=>$.currentAssitantScope)||[],y=s.useEditorStore($=>$.userInputForAI),T=s.useEditorStore($=>$.triggerAIRun),C=s.useEditorStore($=>$.card),B=s.useEditorStore($=>$.selectedDatabaseName),O=s.useEditorStore($=>$.selectedTableName),L=s.useEditorStore($=>$.selectedConnectionId),g=s.useEditorStore($=>$.selectedSchemaName),w=s.useDashboardStore($=>$.dashboard.aiScopeTables),{errorMessage:E,refetch:f,data:M}=s.useDashboardCardQuery(C),{setTriggerAIRun:j,setCurrentAssitantScope:I,setCardConfig:D}=s.useEditorActions(),{selectedDatamodelName:P,connectionType:v,selectedDatamodelId:A}=s.useEditorAside(),S=(he=s.useDashboardQuery().data)==null?void 0:he.assistantProfileId,{messages:R,setMessages:F,regenerate:z,error:G,sendMessage:V,status:U,addToolResult:Q,stop:J,clearError:Z}=s.useChat({transport:new s.DefaultChatTransport({api:`${l.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${c==null?void 0:c.accessToken}`}),body:()=>{const $=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:S,isDevMode:o,aiContext:$.currentAIContext,reasoningEffort:$.reasoningEffort,showReasoning:$.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:$,body:H})=>({body:{...H,messages:s.cleanupIncompleteMessages($)}})}),onError:$=>{var H;if($.name==="AbortError"||(H=$.message)!=null&&H.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",$)},onToolCall:q,onFinish({isAbort:$,isDisconnect:H,isError:ae}){a(""),console.log($?"[Editor Assistant] Stream aborted by user":H?"[Editor Assistant] Stream disconnected (network error)":ae?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});k.useEffect(()=>{T&&y&&(V({role:"user",parts:[{type:"text",text:y}]}),j(!1))},[T,y,V,j]);async function q({toolCall:$}){var H,ae,ie,ge,je,ve,Ne,ke,X,oe,ue,xe,we,Ce,Me,Oe;if(["createChartFromSql","createForecast"].includes($.toolName)){const te=((H=$.input)==null?void 0:H.sql)??((ae=$.args)==null?void 0:ae.sql),me=((ie=$.input)==null?void 0:ie.python)??((ge=$.args)==null?void 0:ge.python),pe=((je=$.input)==null?void 0:je.chartType)??((ve=$.args)==null?void 0:ve.chartType);N(pe),m(te),p(me),u(!0),Q({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if($.toolName==="getUserSql"){if(!d){Q({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",message:"No SQL found"}});return}Q({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",sql:d,python:x||""}})}else if($.toolName==="generateQueryConfig"){a("Generating query config...");const te=((Ne=$.input)==null?void 0:Ne.chartType)??((ke=$.args)==null?void 0:ke.chartType),me=((X=$.input)==null?void 0:X.queryConfig)??((oe=$.args)==null?void 0:oe.queryConfig);((ue=$.input)==null?void 0:ue.cardConfig)??((xe=$.args)==null||xe.cardConfig),N(te),D(me),m(void 0),p(void 0);const pe=await f();if((we=pe==null?void 0:pe.data)!=null&&we.error){Q({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",queryConfig:me,message:(Ce=pe==null?void 0:pe.data)==null?void 0:Ce.error.message}});return}if((Me=pe==null?void 0:pe.data)!=null&&Me.records){Q({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:me,message:"The data has been visualized"}});return}Q({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:me,message:"The data has been visualized",records:(Oe=pe==null?void 0:pe.data)==null?void 0:Oe.records}})}else a("Analyzing...")}function Y($){const H=s.removeFromScopeArray(h,$);se(H)}function se($){const H=s.sanitizeAIScope($);I(H),F(ae=>[...ae,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(H)}`}]}])}function ne(){const $={databaseName:B||"",schemaName:g||"",tableName:O||"",datamodelId:A||"",datamodelName:s.resolveDatamodelName(P),connectionId:L||"",connectionType:v||""},H=s.dedup([...h,$]);se(H)}function _(){const $={databaseName:B||"",schemaName:g||"",tableName:O||"",datamodelName:s.resolveDatamodelName(P),connectionId:L||"",connectionType:v||"",datamodelId:A||""};if(!s.isInAiScopeArray([...w||[],...h],$)||h.length===0){const ae=s.dedup([...w||[],...h,$]).filter(ie=>ie.connectionId===$.connectionId);se(ae)}}const W=!["ready","error"].includes(U),le=s.getErrorMessage(G);return{messages:R,setMessages:F,sendMessage:V,regenerate:z,isLoading:W,handleSetAIScope:_,handleAddCurrentTableToScope:ne,removeFromCurrentSelections:Y,currentAssitantScope:h,setCurrentAssitantScope:I,stop:J,status:U,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:le,clearError:Z}}const cr=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Ks({isFullscreen:t,onFullscreenChange:n,fullscreenContainer:a}){const r=k.useRef(null),[i,c]=k.useState(!1),[l,d]=k.useState(s.isDevEnv),[o,x]=k.useState(!1),[p,m]=k.useState(!1),[u,N]=k.useState(!1),b=t??u,h=s.useCurrentAIContext(),{setCurrentAIContext:y}=s.useAIActions(),{clearQueue:T}=s.useQueueActions(),{clearFileAttachments:C}=s.useFileActions(),B=s.useFileAttachments("editor"),O=s.useDashboardStore(te=>te.dashboard.aiContext),L=s.useEditorStore(te=>te.card.dataSource),g=s.useEditorStore(te=>te.actions.setCardSql),w=s.useEditorStore(te=>te.actions.setRunSql),E=s.useEditorStore(te=>te.showAIDialog),f=s.useDashboardStore(te=>te.handleOpenAssistantProfile),{setShowAIDialog:M,setCardPython:j}=s.useEditorActions(),{setDataSource:I}=s.useEditorActions(),{assistantProfile:D}=s.useAssistantProfile(),{messages:P,setMessages:v,sendMessage:A,isLoading:S,stop:R,status:F,llmUsage:z,errorMessage:G,clearError:V}=ir(),[U,Q]=k.useState(""),J=te=>{Q(te.target.value)},Z=te=>{te.preventDefault();const me=U.trim();if(!me&&B.length===0)return;const pe=[];me&&pe.push({type:"text",text:me}),B.forEach(Fe=>{Fe.data&&pe.push({type:"file",mediaType:Fe.type,filename:Fe.name,url:`data:${Fe.type};base64,${Fe.data}`})}),A({role:"user",parts:pe}),Q(""),C("editor"),H({force:!0})},{visibleMessages:q,hasMoreMessages:Y,totalMessageCount:se,loadMoreMessages:ne,resetMessageWindow:_}=s.useMessageWindow(P,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:W,isAtBottom:le,hasNewMessages:he,newMessageCount:$,scrollToBottom:H,handleScroll:ae,resetNewMessageCount:ie}=s.useAutoScroll(q,{threshold:50,behavior:"smooth",isStreaming:S});k.useEffect(()=>{var te;E&&((te=r.current)==null||te.focus(),y({selectedEntities:(L==null?void 0:L.selectedEntities)||[]}))},[E,L,y]),s.useAutoSubmitQueue({assistantType:"editor",status:F,isLoading:S,sendMessage:A});const{hasActiveTools:ge}=s.useActiveToolStatus(P),je=k.useCallback(te=>{n==null||n(te),t===void 0&&N(te)},[t,n]);k.useEffect(()=>{if(!b)return;function te(me){me.key==="Escape"&&je(!1)}return window.addEventListener("keydown",te),()=>{window.removeEventListener("keydown",te)}},[b,je]);const ve=k.useCallback(te=>{A({role:"user",parts:[{type:"text",text:te}]}),H({force:!0})},[A,H]),Ne=k.useCallback(async()=>{const te=JSON.stringify(P??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(te),s.ue.success("Conversation copied")}catch(me){console.error("Failed to copy conversation",me),s.ue.error("Unable to copy conversation")}},[P]),ke=k.useCallback(()=>{je(!b)},[b,je]);function X(te,me){me==="sql"?(g(te),w(!0)):me==="python"&&(j(te),w(!0))}function oe(){h.selectedEntities.length===0&&y({selectedEntities:(O==null?void 0:O.selectedEntities)||[]})}function ue(te){oe();const me={role:"user",parts:[{type:"text",text:te.title+" "+te.subtitle}]};A(me)}function xe(te){oe(),A({role:"user",parts:[{type:"text",text:te}]})}function we(){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:i,onCheckedChange:c,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:d,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:x,children:"System Message"})]})]})}function Ce(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Me=(U==null?void 0:U.length)===0&&(P==null?void 0:P.filter(te=>te.role==="user").length)===0,Oe=e.jsxs("div",{"data-role":"editor-assistant",className:s.cn("flex h-full w-full flex-col justify-between px-6 py-4",b&&"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:[Ce(),f&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:f,children:(D==null?void 0:D.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[we(),l&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Ne,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:b?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:ke,children:b?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:()=>{v([]),T("editor"),V(),_()},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:W,className:"mt-2 flex w-full grow basis-0",onScroll:ae,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:ne,className:"text-xs",children:["Load ",Math.min(5,se-q.length)," ","more messages (",se-q.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:q,showTools:l,handleRun:X,showSystemMessage:o,onQuickReply:ve,disableQuickReplies:S}),!ge&&e.jsx(s.AssistantStatus,{status:F,errorMessage:G})]})}),E&&!le&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{H({force:!0}),ie()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),he&&$>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:[Me&&!D&&e.jsx(s.Placeholders,{onClick:ue,placeholders:cr}),e.jsx("div",{children:Me&&D&&e.jsx(s.SeedQuestions,{seedQuestions:D.seedQuestions||[],handleSeedQuestionClick:xe})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:Q,stop:R,input:U,handleInputChange:J,handleSubmit:te=>{oe(),Z(te),H({force:!0})},isLoading:S,status:F,assistantType:"editor",onFocus:()=>{}})]}),z&&i&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",z.inputTokens," prompt tokens, ",z.outputTokens," ","completion tokens, ",z.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(L==null?void 0:L.selectedEntities)||[],open:p,onOpenChange:m,dataSource:L||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return b&&a?Lt.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:Oe})}),a):Oe}function dr(t,n,a){if(!n)return!1;const r=n.qualifiedFieldName,i=n.qualifiedEntityName,c=i&&n.name?`${i}.${n.name}`:r;return t.some(l=>{if(!(s.getDataType(l.dataType||"")==="date"))return!1;const o=s.getSelectedDateFilterColumn(l,a),x=o.split("."),p=x[x.length-1]||o,m=x.length>1?x.slice(0,-1).join("."):void 0,u=l.qualifiedTableName||m,N=u?`${u}.${p}`:void 0;return r?N?N===c||N.endsWith(`.${r}`):p===n.name:N?N===c:p===n.name})}const cs=({dataType:t})=>s.getFieldIconComponent(t);function ur({aliasTemplate:t,onAliasTemplateChange:n}){var o;const[a,r]=k.useState(t),[i,c]=k.useState(!1),l=(o=s.useEditorStore(x=>{var p;return(p=x.card.config)==null?void 0:p.pivotByColumns}))==null?void 0:o[0],d=l?`e.g. Min Sales in {{${l.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$1,{placeholder:d,value:i?a:t,onChange:x=>{r(x.target.value),c(!0)},onFocus:()=>c(!0),onPointerDown:x=>x.stopPropagation(),className:"h-8 text-xs",onKeyDown:x=>{x.key==="Enter"&&i&&a!==t?(n(a),c(!1)):x.key==="Escape"&&(r(t),c(!1))},"aria-label":"Edit alias template"}),i&&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),c(!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),c(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function mr({valueAliases:t,onValueAliasesChange:n}){const[a,r]=k.useState(null),[i,c]=k.useState(""),[l,d]=k.useState(""),o=()=>{n({...t,"":""})},x=m=>{const u={...t};delete u[m],n(u)},p=m=>{const u={...t};delete u[m],u[i]=l,n(u),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(([m,u],N)=>e.jsx("div",{className:"flex items-center gap-2",children:a===m?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:i,onChange:b=>c(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?p(m):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:l,onChange:b=>d(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?p(m):b.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:()=>p(m),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$1,{placeholder:"Value key",value:m,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),c(m),d(u)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:u,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),c(m),d(u)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>x(m),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},m+N)),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 xr({idx:t}){var d;const n=s.useEditorStore(o=>{var x;return(x=o.card)==null?void 0:x.preferences}),a=s.useEditorStore(o=>{var x;return(x=o.card.preferences)==null?void 0:x.datasetOptions}),r=s.useEditorStore(o=>o.actions.setCardPreferences),i=(d=n==null?void 0:n.chartOptions)==null?void 0:d.indexAxis,c=a==null?void 0:a.find(o=>o.idx===t);function l(o,x){(o==="end"||o==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const p={display:o!=="none",align:o,anchor:o,clamp:!0};if(!c)r({...n,datasetOptions:[...a||[],{idx:x,datalabels:p}]});else{const m={...c};m.datalabels=p;const u=a==null?void 0:a.map(N=>N.idx===x?m:N);r({...n,datasetOptions:u})}}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:()=>l("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>l("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Gt,{className:s.cn("h-4 w-4",{"rotate-90":i==="y"})})}),e.jsx("button",{onClick:()=>l("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ht,{className:s.cn("h-4 w-4",{"rotate-90":i==="y"})})}),e.jsx("button",{onClick:()=>l("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(_t,{className:s.cn("h-4 w-4",{"rotate-90":i==="y"})})})]})})]})}function ds({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 hr(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function pr({col:t,idx:n,className:a,iconClassName:r,children:i}){const c=s.useEditorStore(p=>{var m;return(m=p.card)==null?void 0:m.preferences}),l=s.useEditorStore(p=>{var m,u;return(u=(m=p.card)==null?void 0:m.preferences)==null?void 0:u.datasetOptions}),d=l==null?void 0:l.find(p=>p.idx===n),{setCardPreferences:o}=s.useEditorStore(p=>p.actions);function x(p){if(!d)o({...c,datasetOptions:[...l||[],{idx:n,type:p==="area"?"line":p,fill:p==="area"?"origin":""}]});else{const m={...d};m.type=p==="area"?"line":p,m.fill=p==="area"?"origin":"";const u=l==null?void 0:l.map(N=>N.idx===n?m:N);o({...c,datasetOptions:u})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[i||e.jsx(ds,{className:"max-w-[100px]",title:t,children:hr(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>x("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>x("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>x("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(xr,{idx:n})]})]})}function fr(){const t=s.useEditorStore(d=>d.card.type),n=s.useEditorStore(d=>d.isDevMode),a=s.useEditorStore(d=>d.card.preferences),{setCardPreferences:r}=s.useEditorStore(d=>d.actions);function i(d){var p;const o={datalabels:{display:d!=="none",align:d,anchor:d,clamp:!0}},x={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(p=a==null?void 0:a.chartOptions)==null?void 0:p.plugins,...o}}};r(x)}function c(){var d,o,x;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((x=(o=(d=a==null?void 0:a.chartOptions)==null?void 0:d.plugins)==null?void 0:o.datalabels)==null?void 0:x.anchor)||"none",onValueChange:i,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 l(){var d,o,x;return e.jsx("div",{children:e.jsxs(s.Select,{value:((x=(o=(d=a==null?void 0:a.chartOptions)==null?void 0:d.plugins)==null?void 0:o.datalabels)==null?void 0:x.anchor)||"none",onValueChange:i,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?c():l()})}function gr({column:t}){const n=s.useEditorStore(o=>o.card.type),a=s.useEditorStore(o=>{var x,p;return(p=(x=o.card)==null?void 0:x.config)==null?void 0:p.metricColumns}),r=(a==null?void 0:a.map(o=>o.label))||[],i=r==null?void 0:r.find(o=>o===t.label||o===t.name),c=i?r.indexOf(i):-1;function l(){return e.jsx("div",{className:"pr-1",children:i&&e.jsx(pr,{idx:c,col:i,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function d(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(fr,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&l(),["pie","doughnut"].includes(n)&&d()]})}function jr({field:t,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:i}=s.useSemaphorContext(),c=s.useEditorStore(x=>x.card),l=c==null?void 0:c.dataSource,d=["attribute-values",t.entityName,t.name,n,a],o=s.useQuery({queryKey:d,queryFn:async()=>{if(!(l!=null&&l.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const x={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},p={connection_id:l.connectionId,cardConfig:x,cardDataSource:l,cache_config:s.getCacheConfig({card:c})};console.log("requestBody",p);const m=await s.postRequestRegular(`${i.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",p);if(m!=null&&m.error)return console.error("Error fetching attribute values:",m.error),[];const u=t.name;return((m==null?void 0:m.records)||[]).map(b=>{const h=b[u]||b[t.alias||u]||b[t.label];return{id:h||"",value:h||"",label:String(h||"(empty)")}})}catch(x){return console.error("Error fetching attribute values:",x),[]}},enabled:!!t&&!!(l!=null&&l.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 dt({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:i,onSave:c}){var B,O;const l=!!i,[d,o]=k.useState(l?"values":"fields"),[x,p]=k.useState(""),[m,u]=k.useState({id:(i==null?void 0:i.id)||s.v4(),field:(i==null?void 0:i.field)||null,selectedValues:i?Array.isArray(i.value)?i.value:[i.value]:[]}),N=a.filter(L=>{var w;return l?!1:!((w=r==null?void 0:r.conditions)==null?void 0:w.some(E=>E.field.id===L.id))&&L.label.toLowerCase().includes(x.toLowerCase())}),b=L=>{u({...m,field:L}),o("values")},h=()=>{if(m.field&&m.selectedValues.length>0){const L={id:m.id,field:m.field,operator:"in",value:m.selectedValues};let g;if(l){const w=((r==null?void 0:r.conditions)||[]).map(E=>E.id===i.id?L:E);g={...r,conditions:w}}else{const w=(r==null?void 0:r.conditions)||[];g={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...w,L],groups:[]}}c(g),n(!1)}},y=()=>{if(!l||!i)return;const L=((r==null?void 0:r.conditions)||[]).filter(g=>g.id!==i.id);if(L.length>0){const g={...r,conditions:L};c(g)}else c(void 0);n(!1)},T=L=>{u({...m,selectedValues:L})},C=()=>{l&&i?(u({id:i.id,field:i.field,selectedValues:Array.isArray(i.value)?i.value:[i.value]}),o("values")):(u({id:s.v4(),field:null,selectedValues:[]}),o("fields")),p("")};return k.useEffect(()=>{t&&C()},[t,l,i]),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:l?`Edit Filter: ${(B=m.field)==null?void 0:B.label}`:d==="fields"?"Select Field to Filter":`Select Values for ${(O=m.field)==null?void 0:O.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!l&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&d==="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(L=>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:[L.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(L.value)?`${L.value.length} values`:String(L.value)})]},L.id))})]}),d==="fields"&&!l?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$1,{placeholder:"Search fields...",value:x,onChange:L=>p(L.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:N.map(L=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>b(L),children:[e.jsx(cs,{dataType:s.getDataType(L.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:L.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[L.entityName,".",L.name]})]})]},L.id))}),N.length===0&&x&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',x,'"']}),N.length===0&&!x&&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(br,{field:m.field,selectedValues:m.selectedValues,onValuesChange:T,onBack:l?void 0:()=>o("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:l?e.jsx(s.Button,{variant:"destructive",onClick:y,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:C,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:h,disabled:!m.field||m.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function br({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[i,c]=k.useState(""),{values:l,isLoading:d,isFetching:o}=jr({field:t,searchQuery:i,limit:500}),x=i?l.filter(u=>String(u.value).toLowerCase().includes(i.toLowerCase())):l,p=u=>{const N=n.includes(u);a(N?n.filter(b=>b!==u):[...n,u])},m=()=>{n.length===x.length&&x.length>0?a([]):a(x.map(u=>u.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$1,{placeholder:"Search values...",value:i,onChange:u=>c(u.target.value),className:"pl-10"})]}),d||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===x.length&&x.length>0,onCheckedChange:m}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",x.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:x.map(u=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>p(u.value),children:[e.jsx(s.Checkbox,{checked:n.includes(u.value),onCheckedChange:()=>p(u.value)}),e.jsx(ds,{className:"text-sm",children:u.label})]},u.id))})]})]})}function yr({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:i,hasPivotColumns:c=!1,cardType:l}){var vs,Ns,Cs,Ss,ws,Ts,Es;const{attributes:d,listeners:o,setNodeRef:x,transform:p,transition:m,isDragging:u}=s.useSortable({id:t.id}),N=s.useEditorStore(K=>K.card),b=s.useEditorStore(K=>K.frame),{scopedFields:h}=s.useScopedFields(),{userContext:y}=s.useCurrentUserInfo(),T=(y==null?void 0:y.type)==="organization",C=(vs=N.dataSource)==null?void 0:vs.semanticDomainId,{promoteMetric:B}=s.usePromoteCalculatedMetricToDomain({domainId:C}),{updateLabel:O,handleAggregationChange:L,handleDateFormatChange:g,handleGranularityChange:w,handleAliasTemplateChange:E,handleValueAliasesChange:f,removeField:M,handleMetricComparisonChange:j,handleKpiShowTrendlineChange:I,handleKpiTrendlineWindowChange:D,handleKpiTrendlineGranularityChange:P,handleMetricTargetValueChange:v}=s.useFieldManagement(N),[A,S]=k.useState(!1),[R,F]=k.useState(!1),[z,G]=k.useState(!1),[V,U]=k.useState(null),[Q,J]=k.useState(t.dateFormat||"YYYY-MM-DD"),[Z,q]=k.useState(t.customFormat||""),[Y,se]=k.useState(!!t.customFormat),[ne,_]=k.useState(t.granularity||"day"),[W,le]=k.useState(t.aliasTemplate||""),[he,$]=k.useState(t.valueAliases||{}),[H,ae]=k.useState((Ns=t.parameters)==null?void 0:Ns.filters),ie=K=>{K==="custom"?se(!0):(se(!1),J(K),(n==="groupBy"||_e)&&g(a,K,"",n))},ge=K=>{q(K),(n==="groupBy"||_e)&&g(a,"custom",K,n)},je=K=>{var re;_(K);const ee=(re=s.getDateFormatOptionsForGranularity(K)[0])==null?void 0:re.value;ee&&!Y&&(J(ee),n==="groupBy"&&g(a,ee,"",n)),n==="groupBy"&&w(a,K)},ve=K=>{le(K),n==="metrics"&&E(a,K)},Ne=K=>{$(K),n==="metrics"&&f(a,K)},ke=K=>{O(n,a,K)},X=K=>K!=null&&K.startsWith("card-source-")?K.replace("card-source-",""):K,oe=(K,ce,ee)=>{const re=X(K.id),de=X(ce.id);return re&&de&&re===de?!0:K.name===ce.name&&K.role===ce.role},xe=s.isCalculatedMetric(t)?(Cs=b==null?void 0:b.calculatedFields)==null?void 0:Cs.find(K=>oe(K,t)):void 0,we=t.fieldScope==="dashboard"||t.fieldScope===void 0&&!!xe,Ce=t.fieldScope==="domain",Me=Ce?"domain":we?"dashboard":"card",Oe=Ce?t:we&&xe?xe:t,te=K=>{var ce;if(ae(K),n==="metrics"){const ee={...t,parameters:{...t.parameters,filters:K}},re=[...((ce=N.config)==null?void 0:ce.metricColumns)||[]];re[a]=ee,s.useEditorStore.getState().actions.updateCardConfig(N.id,{metricColumns:re})}F(!1)},me=async K=>{await B(K),It()},pe=()=>{M(n,a)},Fe={transform:s.CSS.Transform.toString(p),transition:m},ms=s.getDataType(t.dataType),Ue=ms==="date",xs=l==="kpi",_e=n==="detailColumns",hs=((Ss=N.config)==null?void 0:Ss.metricColumns)||[],Ve=((ws=N.config)==null?void 0:ws.groupByColumns)||[],ps=s.useDashboardStore(K=>{var ce;return(ce=K.dashboard)==null?void 0:ce.filters})??[],fs=s.useDashboardStore(K=>K.filterValues),mt=s.getDateFormatOptionsForGranularity(ne),xt=!!l&&s.COMPARISON_SUPPORTED_CHART_TYPES.includes(l),ht=l==="kpi"||l==="table",Ie=k.useMemo(()=>Ve.find(K=>s.getDataType(K.dataType||"")==="date"),[Ve]),gs=k.useMemo(()=>Ve.some(K=>s.getDataType(K.dataType||"")==="date"),[Ve]),pt=k.useMemo(()=>{var re;if(!Ie)return!1;const K=(re=N.config)==null?void 0:re.filters;if(!K)return!1;const ce=de=>{const fe=de.field;return fe?Ie.id&&fe.id===Ie.id||Ie.qualifiedFieldName&&fe.qualifiedFieldName===Ie.qualifiedFieldName?!0:fe.name===Ie.name:!1},ee=de=>de.conditions.some(be=>s.getDataType(be.field.dataType||"")==="date"&&ce(be))?!0:de.groups.some(be=>ee(be));return ee(K)},[(Ts=N.config)==null?void 0:Ts.filters,Ie]),ft=k.useMemo(()=>dr(ps,Ie,fs),[ps,fs,Ie]),js=pt||ft,gt=k.useMemo(()=>hs.some(K=>K.comparisonType==="start_vs_end"),[hs]),jt=n!=="pivotBy",bt=Ue&&n==="groupBy"&&(!xs||gt),yt=!xs&&Ue&&(n==="groupBy"||_e),vt=l==="kpi"&&Ue&&n==="groupBy",Nt=n==="metrics",bs=xt&&n==="metrics",Ct=()=>{const K=t,ce=n==="metrics"&&s.isCalculatedMetric(K);return e.jsxs("div",{className:"space-y-1",children:[!ce&&e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:ee=>{ee.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}`}),ce&&K.calculatedFormula&&e.jsxs("div",{title:s.formatDisplayFormula(K.calculatedFormula),onPointerDown:ee=>{ee.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:["= ",s.formatDisplayFormula(K.calculatedFormula)]})]})},St=()=>jt?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(Te,{value:t.label??"",onSave:ke,placeholder:"Display label...",type:"text"})]}):null,ys=()=>bt?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:ne,onValueChange:je,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(K=>e.jsx(s.SelectItem,{className:"text-xs",value:K,children:s.toTitleCase(K)},K))})]})]}):null,wt=()=>yt?e.jsxs(e.Fragment,{children:[ys(),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:Y?"custom":Q,onValueChange:ie,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:mt.map(K=>e.jsx(s.SelectItem,{className:"text-xs",value:K.value,children:K.label},K.value))})]}),Y&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:Z,onChange:K=>{K.stopPropagation(),ge(K.target.value)},onClick:K=>K.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,Tt=()=>{var ce,ee,re,de;const K=vt;return K?e.jsx(e.Fragment,{children:K&&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:((ce=N.config)==null?void 0:ce.showTrendline)||!1,onCheckedChange:I})]})}),((ee=N.config)==null?void 0:ee.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$1,{type:"number",min:"1",max:"365",value:((re=N.config)==null?void 0:re.trendlineWindow)||30,onChange:fe=>{const be=parseInt(fe.target.value)||30;D(be)},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:((de=N.config)==null?void 0:de.trendlineGranularity)||"day",onValueChange:P,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"})]})]})]})]})]})}):null},Et=()=>{if(!Nt)return null;const K=t,ce=s.isCalculatedMetric(K);return e.jsxs(e.Fragment,{children:[ce&&T&&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:()=>G(!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:ee=>{L(a,ee)},disabled:ce,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"})]})]})]})]}),bs&&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:K.comparisonType||"none",onValueChange:ee=>j(a,ee),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"}),(()=>{const ee=!gs||!js,re=gs?js?void 0:"Add a date filter to enable":"Add a date groupBy to enable",de=(fe,be)=>e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.SelectItem,{value:fe,disabled:ee,title:re,children:be})}),ee&&re&&e.jsx(s.TooltipContent,{side:"right",children:re})]})});return e.jsxs(e.Fragment,{children:[de("previous_period","Previous Period"),de("same_period_last_year","Same Period Last Year"),de("start_vs_end","Start vs End")]})})(),ht&&e.jsx(s.SelectItem,{value:"target",children:"Target"})]})]})]}),bs&&K.comparisonType==="target"&&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(s.Input$1,{type:"number",value:K.targetValue!==void 0&&K.targetValue!==null?String(K.targetValue):"",onChange:ee=>{const re=ee.target.value;if(re===""){v(a,void 0);return}const de=Number(re);v(a,Number.isFinite(de)?de:void 0)},className:"h-8 text-xs",placeholder:"Enter target value..."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(H==null?void 0:H.conditions)&&H.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:H.conditions.map(ee=>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:()=>{U(ee),F(!0)},children:[e.jsxs("span",{className:"font-medium",children:[ee.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(ee.value)?ee.value.length===1?String(ee.value[0]):ee.value.length<=2?ee.value.join(", "):`${ee.value.slice(0,2).join(", ")} +${ee.value.length-2}`:String(ee.value)})}),Array.isArray(ee.value)&&ee.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 (",ee.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:ee.value.map((re,de)=>e.jsx("div",{children:String(re)},de))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:re=>{var fe;re.stopPropagation();const de=H.conditions.filter(be=>be.id!==ee.id);if(de.length>0){const be={...H,conditions:de};te(be)}else if(ae(void 0),n==="metrics"){const be={...t,parameters:{...t.parameters,filters:void 0}},Ae=[...((fe=N.config)==null?void 0:fe.metricColumns)||[]];Ae[a]=be,s.useEditorStore.getState().actions.updateCardConfig(N.id,{metricColumns:Ae})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},ee.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{U(null),F(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(gr,{column:t}),c&&e.jsxs(e.Fragment,{children:[e.jsx(ur,{aliasTemplate:W,onAliasTemplateChange:ve}),e.jsx(mr,{valueAliases:he,onValueAliasesChange:Ne})]})]})},{columns:kt=[],refetch:It}=s.useColumns(),At=(H==null?void 0:H.conditions)&&H.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:x,style:Fe,...d,...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 ${u?"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(cs,{dataType:ms}),e.jsx(ds,{className:s.cn("w-[140px] flex-1 text-sm",At&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((Es=H==null?void 0:H.conditions)==null?void 0:Es.length)&&!A&&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:H.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:H.conditions.map(K=>e.jsxs("div",{children:[K.field.label,":"," ",Array.isArray(K.value)?`${K.value.length} values`:String(K.value)]},K.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:K=>{K.stopPropagation(),S(!A)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${A?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:K=>{K.stopPropagation(),i(r==="asc"?"desc":"asc")},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:K=>{K.stopPropagation(),pe()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),A&&e.jsxs("div",{className:"space-y-3",children:[Ct(),St(),l==="kpi"&&ys(),wt(),Tt(),Et()]})]}),R&&e.jsx(dt,{open:R,onOpenChange:K=>{F(K),K||U(null)},availableFields:kt,existingFilters:H,editingCondition:V,onSave:K=>{var ce;if(K)te(K);else if(ae(void 0),n==="metrics"){const ee={...t,parameters:{...t.parameters,filters:void 0}},re=[...((ce=N.config)==null?void 0:ce.metricColumns)||[]];re[a]=ee,s.useEditorStore.getState().actions.updateCardConfig(N.id,{metricColumns:re})}U(null)}}),z&&n==="metrics"&&e.jsx(s.CalculatedFieldEditor,{open:z,onOpenChange:G,availableFields:h,existingField:Oe,existingFieldScope:Me,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:K=>{var Ae;if(K.role!=="metric")return;const ce=[...((Ae=N.config)==null?void 0:Ae.metricColumns)||[]];ce[a]=K;const{frame:ee,actions:re}=s.useEditorStore.getState();if(re.updateCardConfig(N.id,{metricColumns:ce}),!s.isCalculatedMetric(K))return;const de=ee.calculatedFields||[],fe=de.findIndex(Ee=>Ee.name===t.name&&Ee.role===t.role);if(fe<0)return;const be=de.map((Ee,ze)=>ze===fe?{...K,id:Ee.id}:Ee);re.updateFrame({calculatedFields:be})},onSaveToDashboard:K=>{var ze;if(K.role!=="metric")return;const{frame:ce,actions:ee}=s.useEditorStore.getState(),re=ce.calculatedFields||[],de=re.findIndex(He=>oe(He,K)),fe=de>=0&&re[de].id!==K.id?{...K,id:re[de].id}:K,be=de>=0?re.map((He,Dt)=>Dt===de?fe:He):[...re,fe];ee.updateFrame({calculatedFields:be});const Ae=[...((ze=N.config)==null?void 0:ze.metricColumns)||[]],Ee=t;Ae[a]={...fe,id:Ee.id,aliasTemplate:Ee.aliasTemplate,valueAliases:Ee.valueAliases,parameters:Ee.parameters,customFormat:Ee.customFormat},ee.updateCardConfig(N.id,{metricColumns:Ae})},onPromoteMetricToDomain:C&&T?me:void 0,domainId:C,cardId:N.id})]})}function vr({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"})]})]})]});case"detailColumns":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields to display as columns in the detail table. No aggregation applied - shows raw values from the database."})]});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 Pe({zone:t,fields:n,label:a,placeholder:r,shouldShow:i,hasPivotColumns:c=!1,activeField:l=null}){const{isOver:d,setNodeRef:o}=s.useDroppable({id:t}),{updateSortByColumn:x}=s.useEditorActions(),p=s.useEditorStore(y=>y.card),m=s.useEditorStore(y=>y.card.type),u=n.length>0,N=k.useMemo(()=>!l||!d?!0:s.validateFieldForChartType(l,t,m).isValid,[l,d,t,m]),b=(y,T)=>{var B;!((B=p.config)!=null&&B.sortByColumns)||p.config.sortByColumns.findIndex(O=>O.id===y)===-1||x(p.id,y,{direction:T})};if(t==="sortBy"&&i===!1)return null;const h=t!=="sortBy"&&m!=="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}),h&&e.jsx(vr,{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":d&&N,"border-red-500 bg-red-50 dark:bg-red-950":d&&!N,"border-muted-foreground/30 bg-muted/40":!d&&u,"min-h-[60px] border-muted-foreground/20 bg-background":!d&&!u}),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,{id:t,items:n.map(y=>y.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((y,T)=>{const B=y.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(yr,{field:y,zone:t,index:T,sortDirection:B,onSortDirectionChange:O=>b(y.id,O),hasPivotColumns:c,cardType:m})})},y.id)})})})})]})}function Nr({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r,detailFields:i,activeField:c}){var Q,J,Z,q;const[l,d]=k.useState(!1),o=s.useEditorStore(Y=>{var se;return!!((se=Y.card.customCardPreferences)!=null&&se.url)}),x=s.useEditorStore(Y=>Y.card),p=s.useEditorStore(Y=>Y.frame),m=s.findCustomVisualConfigCard(p,x),{manifest:u}=s.useCustomVisual(((Q=m==null?void 0:m.customCardPreferences)==null?void 0:Q.url)||""),N=(J=u==null?void 0:u.visuals)==null?void 0:J.find(Y=>{var se;return Y.name===((se=m==null?void 0:m.customCardPreferences)==null?void 0:se.componentName)}),b=s.resolveMultiInputType(m,N)==="multiple",h=b&&!!((Z=m==null?void 0:m.customCardPreferences)!=null&&Z.url),y=s.getConfigSlotExpectedType(N==null?void 0:N.slots),T=s.useEditorStore(Y=>Y.actions.updateCardConfig),C=s.useEditorStore(Y=>Y.actions.updateFrame),{scopedFields:B,refetch:O}=s.useScopedFields(),{userContext:L}=s.useCurrentUserInfo(),g=b&&(m==null?void 0:m.id)===x.id&&y?y:x==null?void 0:x.type,w=g==="detailTable",E=t.length>0||a.length>0||i.length>0,f=!w&&(g!=="kpi"||a.length<=2),M=!w,j=!w&&g!=="kpi",I=g!=="kpi"&&E,D=w,P=w?"Drop fields from Columns":"Drop fields from Rows or Metrics",v=(q=x.dataSource)==null?void 0:q.semanticDomainId,{promoteMetric:A}=s.usePromoteCalculatedMetricToDomain({domainId:v}),S=(L==null?void 0:L.type)==="organization",R=Y=>{const se=p.calculatedFields||[],ne=se.findIndex(H=>H.name===Y.name&&H.role===Y.role),_=ne>=0?{...Y,id:se[ne].id}:Y,W=ne>=0?se.map((H,ae)=>ae===ne?_:H):[...se,_];C({calculatedFields:W});const le=s.getNewField(_,"metrics",a),he=a.findIndex(H=>H.name===le.name&&H.role===le.role),$=he>=0?a.map((H,ae)=>ae===he?{...H,...le,id:H.id}:H):[...a,le];T(x.id,{metricColumns:$})},F=async Y=>{await A(Y),O()},z=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(g),G=j&&!z,V=()=>g==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},U=()=>g==="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:[f&&e.jsx(Pe,{zone:"groupBy",fields:t,label:V().label,placeholder:V().placeholder,activeField:c}),G&&e.jsx(Pe,{zone:"pivotBy",fields:n,label:"Pivot Columns",placeholder:"Drop fields to pivot data",activeField:c}),M&&e.jsx(Pe,{zone:"metrics",fields:a,label:U().label,placeholder:U().placeholder,hasPivotColumns:n.length>0,activeField:c}),D&&e.jsx(Pe,{zone:"detailColumns",fields:i,label:"Columns",placeholder:"Drag columns to display"}),a.length>=1&&S&&e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:()=>d(!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"]}),I&&e.jsx(Pe,{zone:"sortBy",fields:r,label:"Sort By",placeholder:P,activeField:c})]})]}),(!o||h)&&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:"CHART SETTINGS"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsx(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:e.jsx(ct,{mode:"config"})})})]}),(o||h)&&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(_s,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"COMPONENT SETTINGS"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsx(lt,{})})]})]}),e.jsx(s.CalculatedFieldEditor,{open:l,onOpenChange:d,availableFields:B,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:Y=>{Y.role==="metric"&&T(x.id,{metricColumns:[...a,Y]})},onSaveToDashboard:Y=>{Y.role==="metric"&&R(Y)},onPromoteMetricToDomain:v&&S?F:void 0,domainId:v,cardId:x.id})]})}function Cr({onEditJoins:t}){const n=s.useEditorStore(d=>d.card),{autoJoinMetadata:a}=s.useDashboardCardQuery(n);if(!(a!=null&&a.autoResolved))return null;const{resolvedJoinPlan:r}=a,i=(r==null?void 0:r.joins)||[];if(i.length===0)return null;const c=d=>!d||d.length===0?"No conditions":d.map(o=>{var u,N,b,h;const x=`${(u=o.source)==null?void 0:u.entityName}.${(N=o.source)==null?void 0:N.name}`,p=`${(b=o.target)==null?void 0:b.entityName}.${(h=o.target)==null?void 0:h.name}`,m=o.operator||"=";return`${x} ${m} ${p}`}).join(" AND "),l=d=>!d.joinKeyGroups||d.joinKeyGroups.length===0?"No conditions defined":d.joinKeyGroups.length===1?c(d.joinKeyGroups[0].keys):d.joinKeyGroups.map((o,x)=>({id:x,operator:o.operator,condition:c(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(ta,{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:"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:i.length})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:i.map((d,o)=>{const x=l(d),p=Array.isArray(x);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:d.source.name}),e.jsx(s.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:d.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:d.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:p?x.map(m=>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:m.condition}),m.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",m.operator,")"]})]},m.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:x})})})]},d.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 Gs={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 Sr({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:i,sortByFields:c,detailFields:l,activeField:d}){var E,f;const[o,x]=k.useState(()=>Gs.getItem("chart-selector-expanded")==="true"),[p,m]=k.useState(!1),u=s.useEditorStore(M=>M.card),N=s.useEditorStore(M=>M.actions.updateCardConfig),b=a.length>0||r.length>0||i.length>0||l.length>0,{data:h,autoJoinMetadata:y}=s.useDashboardCardQuery(u),T=((E=u==null?void 0:u.config)==null?void 0:E.joinPlan)||(y!=null&&y.autoResolved?y.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),C=((f=u==null?void 0:u.dataSource)==null?void 0:f.selectedEntities)||[],B=M=>{N(u.id,{...u==null?void 0:u.config,joinPlan:M}),m(!1)},O=()=>{N(u.id,{...u==null?void 0:u.config,joinPlan:void 0}),m(!1)},L=()=>{m(!1)},g=()=>{m(!0)};k.useEffect(()=>{Gs.setItem("chart-selector-expanded",String(o))},[o]);const w=()=>{x(M=>!M)};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":o}),children:[e.jsx("div",{className:s.cn("overflow-hidden transition-all duration-300 ease-in-out",o?"max-h-[200px] opacity-100":"max-h-0 opacity-0"),children:o&&e.jsx(os,{selectedChart:t,onChartChange:n,variant:"outline"})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:"flex items-center justify-center",children:e.jsx(s.ChartQuickSelector,{selectedChart:t,onChartChange:n,isDropdownExpanded:o,onToggleDropdown:w})})]}),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:b||h}),children:e.jsx(ye.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(Cr,{onEditJoins:g}),e.jsx(Nr,{groupByFields:a,pivotByFields:r,metricsFields:i,sortByFields:c,detailFields:l,activeField:d})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]}),e.jsx(Xs,{open:p,onOpenChange:m,joinPlan:T,availableDataSources:C,onSave:B,onCancel:L,onRemove:O,children:e.jsx("div",{})})]})}function wr({initialFilters:t,availableFields:n}={}){const[a,r]=k.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(L=>L.card.dataSource);const{columns:i,isLoading:c}=s.useColumns(),d=n||i||[],o={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},x=L=>{const g=w=>{if(w.id===L){const E=d[0]||o,f=s.getDataType(E.dataType)==="date";return{...w,conditions:[...w.conditions,{id:`condition-${Date.now()}`,field:E,operator:f?"between":"=",value:f?[]:""}]}}return{...w,groups:w.groups.map(g)}};r(g(a))},p=L=>{const g=w=>{if(w.id===L){const E=d[0]||o,f=s.getDataType(E.dataType)==="date";return{...w,groups:[...w.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:E,operator:f?"between":"=",value:f?[]:""}],groups:[]}]}}return{...w,groups:w.groups.map(g)}};r(g(a))},m=(L,g)=>{const w=E=>E.id===L?{...E,conditions:E.conditions.filter(f=>f.id!==g)}:{...E,groups:E.groups.map(w)};r(w(a))},u=(L,g)=>{const w=E=>E.id===L?{...E,groups:E.groups.filter(f=>f.id!==g)}:{...E,groups:E.groups.map(w)};r(w(a))},N=(L,g,w,E)=>{if(w==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const f=M=>M.id===L?{...M,conditions:M.conditions.map(j=>j.id===g?{...j,[w]:E}:j)}:{...M,groups:M.groups.map(f)};r(f(a))},b=(L,g,w)=>{const E=f=>f.id===L?{...f,conditions:f.conditions.map(M=>M.id===g?{...M,...w}:M)}:{...f,groups:f.groups.map(E)};r(E(a))},h=(L,g)=>{const w=E=>E.id===L?{...E,logicalOperator:g}:{...E,groups:E.groups.map(w)};r(w(a))},y=(L,g)=>{const w=E=>E.id===L?{...E,negate:g}:{...E,groups:E.groups.map(w)};r(w(a))},T=(L,g,w)=>{const E=f=>f.id===L?{...f,conditions:s.arrayMove(f.conditions,g,w)}:{...f,groups:f.groups.map(E)};r(E(a))},C=(L,g,w)=>{const E=f=>f.id===L?{...f,groups:s.arrayMove(f.groups,g,w)}:{...f,groups:f.groups.map(E)};r(E(a))},B=L=>{if(!L||L.conditions.length===0&&L.groups.length===0)return"-- No filters defined";const g=E=>{let f="";typeof E.field=="object"?f=E.field.entityName?`${E.field.entityName}.${E.field.name}`:E.field.name:f=String(E.field);const M=E.operator;let j=E.value;if(E.field.dataType==="string"&&!["in","not in"].includes(E.operator))typeof j=="string"?j=`'${j}'`:Array.isArray(j)&&(j=`'${j.join(", ")}'`);else if(E.field.dataType==="date"||E.field.dataType==="datetime"||E.field.dataType==="timestamp")if(E.operator==="between"&&Array.isArray(j)&&j.length===2){const I=j[0]?`'${j[0]}'`:"NULL",D=j[1]?`'${j[1]}'`:"NULL";return`${f} BETWEEN ${I} AND ${D}`}else if((E.operator==="in"||E.operator==="not in")&&Array.isArray(j)){const I=j.map(D=>D?`'${D}'`:"NULL").join(", ");return`${f} ${M} (${I})`}else typeof j=="string"||j instanceof Date?j=`'${j}'`:Array.isArray(j)&&j.length>0&&(j=`'${j[0]}'`);else if(["in","not in"].includes(E.operator)){let I=[];Array.isArray(j)?I=j.map(D=>typeof D=="string"?`'${D}'`:String(D)):typeof j=="string"?I=j.split(",").map(D=>{const P=D.trim();return E.field.dataType==="string"?`'${P}'`:P}):typeof j=="number"&&(I=[String(j)]),j=`(${I.join(", ")})`}switch(M){case"contains":return typeof j=="string"?`${f} LIKE '%${j.replace(/'/g,"")}'`:`${f} LIKE '%${String(j)}'`;case"startsWith":return typeof j=="string"?`${f} LIKE '${j.replace(/'/g,"")}%'`:`${f} LIKE '${String(j)}%'`;case"endsWith":return typeof j=="string"?`${f} LIKE '%${j.replace(/'/g,"")}'`:`${f} LIKE '%${String(j)}'`;case"isNull":return`${f} IS NULL`;case"isNotNull":return`${f} IS NOT NULL`;default:return`${f} ${M} ${j}`}},w=E=>{const f=E.conditions.map(g),M=E.groups.map(P=>w(P)),j=[...f,...M].filter(Boolean);if(j.length===0)return"";const I=j.join(` ${E.logicalOperator} `),D=j.length>1?`(${I})`:I;return E.negate?`NOT ${D}`:D};return w(L)},O=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:d,isLoading:c,addCondition:x,addGroup:p,removeCondition:m,removeGroup:u,updateCondition:N,updateConditionFields:b,updateGroupOperator:h,updateGroupNegate:y,reorderConditions:T,reorderGroups:C,generateSQLPreview:B,hasAnyFilters:O}}function Tr({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 Er=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function kr({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:i="w-64"}){const[c,l]=k.useState(!1),d=k.useMemo(()=>{const o={};return a.forEach(x=>{const p=Er(x);o[p]||(o[p]={}),o[p][x.entityId]||(o[p][x.entityId]=[]),o[p][x.entityId].push(x)}),o},[a]);return e.jsxs(s.Popover,{modal:!0,open:c,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":c,className:s.cn("justify-between",!t&&"text-muted-foreground",i),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Tr,{children:[t.entityName,".",t.name]})}):r,e.jsx(s.ChevronsUpDown,{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(d).map(([o,x])=>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(x).map(([p,m])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[s.getEntityIcon(m[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:m[0].entityName})]}),m.map((u,N)=>e.jsxs(s.CommandItem,{value:u.id,onSelect:()=>{n(u),l(!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)===u.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:u.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:u.description&&e.jsx("span",{children:u.description})})]})]},u.id+N))]},`${o}-${p}`))},o))})]})})]})}function us(t){var h;const n=s.useEditorStore(y=>y.card),{authToken:a,tokenProps:r}=s.useSemaphorContext(),i=s.useEditorStore(y=>y.card.config),c=i==null?void 0:i.joinPlan,l={...t,alias:t.name,label:"value",role:"groupby"},d={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},o={...l,role:"sortby",direction:"asc"},x={joinPlan:c,groupByColumns:[l],metricColumns:[d],sortByColumns:[o]},p=((h=n.dataSource)==null?void 0:h.connectionId)||n.connectionId,{data:m,isPending:u,error:N}=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:p,cardConfig:x,cardDataSource:n.dataSource})}catch(y){console.log(t),console.error("error",y)}},enabled:!!p,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((m==null?void 0:m.records)||[]).map(y=>({label:y.value||"BLANK",value:y.value||"BLANK",count:(y==null?void 0:y.count)||0})),isPending:u,error:N}}function Ir({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:i}){const[c,l]=as.useState(!1),{filterValues:d}=us(t),o=p=>{a(n.filter(m=>m!==p))},x=p=>{n.includes(p)?a(n.filter(m=>m!==p)):a([...n,p])};return e.jsx("div",{className:s.cn("w-full",i),children:e.jsxs(s.Popover,{open:c,onOpenChange:l,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":c,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(p=>{const m=d.find(u=>u.value===p);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[m==null?void 0:m.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:u=>{u.key==="Enter"&&o(p)},onMouseDown:u=>{u.preventDefault(),u.stopPropagation()},onClick:u=>{u.stopPropagation(),o(p)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},p)}):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:d.map((p,m)=>e.jsxs(s.CommandItem,{onSelect:()=>x(p.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.includes(p.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:p.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p.count})]})]},p.value+m))})]})]})})]})})}function Ar({field:t,value:n,onChange:a,placeholder:r="Select value...",className:i}){const{filterValues:c,isPending:l,error:d}=us(t);return l?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..."]}):d?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:i||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:c.map((o,x)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:o.value,children:o.label},o.value+x))})]})}function Dr({value:t,operator:n,onChange:a,className:r}){var o,x,p;const{tokenProps:i}=s.useSemaphorContext(),c=((x=(o=i==null?void 0:i.params)==null?void 0:o.calendarContext)==null?void 0:x.tz)||((p=i==null?void 0:i.params)==null?void 0:p.timezone),l=k.useMemo(()=>{if(t){if(n==="between"||n==="not between"){if(Array.isArray(t)&&t.length===2){const m=t[0]?new Date(t[0]):void 0,u=t[1]?new Date(t[1]):void 0;if(m&&u)return{from:m,to:u}}}else if(n==="="||n==="!="){if(!Array.isArray(t)&&t){const m=new Date(t);if(!isNaN(m.getTime()))return{from:m,to:m}}}else if(n===">"||n===">="){if(!Array.isArray(t)&&t){const m=new Date(t);if(!isNaN(m.getTime()))return{from:m,to:void 0}}}else if(n==="<"||n==="<="){if(!Array.isArray(t)&&t){const m=new Date(t);if(!isNaN(m.getTime()))return{from:void 0,to:m}}}else if((n==="in"||n==="not in")&&Array.isArray(t)&&t.length>0){const m=new Date(t[0]),u=t.length>1?new Date(t[t.length-1]):m;if(!isNaN(m.getTime()))return{from:m,to:u}}}},[t,n]),d=m=>{if(!m){a(void 0);return}if(m.from&&m.to)a([m.from.toISOString(),m.to.toISOString()]);else if(m.from){const u=new Date(m.from);u.setHours(23,59,59,999),a([m.from.toISOString(),u.toISOString()])}else if(m.to){const u=new Date(m.to);u.setHours(0,0,0,0),a([u.toISOString(),m.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:l,onChange:d,timezone:c,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const Lr=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Mr=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Or=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Fr=["=","!=","isNull","isNotNull"],Rr=["between","isNull","isNotNull"],Br={"=":"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 Us(t){return Br[t]||s.titleCase(t)}function Pr(t){switch(t){case"string":return Mr;case"number":return Or;case"boolean":return Fr;case"date":return Rr;default:return Lr}}function ut({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:i,onRemoveCondition:c,onUpdateGroupOperator:l,availableFields:d,updateConditionFields:o}){const{attributes:x,listeners:p,setNodeRef:m,transform:u,transition:N,isDragging:b}=s.useSortable({id:t.id}),{isPending:h,error:y}=us(t.field),T={transform:s.CSS.Transform.toString(u),transition:N};return e.jsxs("div",{ref:m,style:T,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${b?"z-50 opacity-50":""}`,children:[e.jsx("div",{...x,...p,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:C=>l(a,C),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(kr,{value:t.field,onValueChange:C=>{const B=C,O=s.getDataType(B.dataType)==="date";o(a,t.id,{field:B,value:"",operator:O?"between":"="})},availableFields:d,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:C=>{C==="in"||C==="not in"?o(a,t.id,{operator:C,value:[]}):C==="isNull"||C==="isNotNull"?o(a,t.id,{operator:C,value:null}):o(a,t.id,{operator:C,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?Us(t.operator):""})}),e.jsx(s.SelectContent,{children:Pr(s.getDataType(t.field.dataType)).map(C=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:C,children:Us(C)},C))})]}),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"?h?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..."]}):y?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Ir,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(C=>typeof C=="string")?t.value:[],onChange:C=>o(a,t.id,{value:C}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input$1,{value:typeof t.value=="string"?t.value:"",onChange:C=>o(a,t.id,{value:C.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Ar,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:C=>o(a,t.id,{value:C}),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:C=>o(a,t.id,{value:C==="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(Dr,{value:t.value,operator:t.operator,onChange:C=>o(a,t.id,{value:C}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:C=>i(a,t.id,"value",C.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:()=>c(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Vr({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:i,onRemoveGroup:c,onUpdateCondition:l,onUpdateField:d,onRemoveCondition:o,onReorderConditions:x,onReorderGroups:p,onAddCondition:m,onAddGroup:u,availableFields:N,renderFilterGroup:b,updateConditionFields:h}){const{attributes:y,listeners:T,setNodeRef:C,transform:B,transition:O,isDragging:L}=s.useSortable({id:t.id}),g={transform:s.CSS.Transform.toString(B),transition:O},w=f=>{const{active:M,over:j}=f;if(j&&M.id!==j.id){const I=t.conditions.findIndex(P=>P.id===M.id),D=t.conditions.findIndex(P=>P.id===j.id);I!==-1&&D!==-1&&x(t.id,I,D)}},E=f=>{const{active:M,over:j}=f;if(j&&M.id!==j.id&&a){const I=t.groups.findIndex(P=>P.id===M.id),D=t.groups.findIndex(P=>P.id===j.id);I!==-1&&D!==-1&&p(a,I,D)}};return e.jsxs("div",{ref:C,style:g,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${L?"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",{...y,...T,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:()=>i(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:f=>r(t.id,f),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&&c(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:w,children:e.jsx(s.SortableContext,{items:t.conditions.map(f=>f.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((f,M)=>e.jsx(ut,{condition:f,index:M,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:l,onUpdateField:d,onRemoveCondition:o,onUpdateGroupOperator:r,availableFields:N,updateConditionFields:h},f.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:E,children:e.jsx(s.SortableContext,{items:t.groups.map(f=>f.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(f=>b(f,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:()=>m(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:()=>u(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function zr({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:i}){const{currentFilters:c,availableFields:l,isLoading:d,addCondition:o,addGroup:x,removeCondition:p,removeGroup:m,updateCondition:u,updateConditionFields:N,updateGroupOperator:b,updateGroupNegate:h,reorderConditions:y,reorderGroups:T,generateSQLPreview:C,hasAnyFilters:B,setCurrentFilters:O}=wr({initialFilters:t,availableFields:n}),L=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[g,w]=k.useState(!1),E=(j,I,D)=>{const P=v=>v.id===j?{...v,conditions:v.conditions.map(A=>A.id===I?{...A,field:D,dataType:D.dataType}:A)}:{...v,groups:v.groups.map(P)};O(P(c))},f=(j,I=0,D)=>I===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:L,collisionDetection:s.closestCenter,onDragEnd:P=>{const{active:v,over:A}=P;if(A&&v.id!==A.id){const S=j.conditions.findIndex(F=>F.id===v.id),R=j.conditions.findIndex(F=>F.id===A.id);S!==-1&&R!==-1&&y(j.id,S,R)}},children:e.jsx(s.SortableContext,{items:j.conditions.map(P=>P.id),strategy:s.verticalListSortingStrategy,children:j.conditions.map((P,v)=>e.jsx(ut,{condition:P,index:v,groupId:j.id,groupLogicalOperator:j.logicalOperator,onUpdateCondition:u,onUpdateField:E,onRemoveCondition:p,onUpdateGroupOperator:b,availableFields:l,updateConditionFields:N},P.id))})}),e.jsx(s.DndContext,{sensors:L,collisionDetection:s.closestCenter,onDragEnd:P=>{const{active:v,over:A}=P;if(A&&v.id!==A.id){const S=j.groups.findIndex(F=>F.id===v.id),R=j.groups.findIndex(F=>F.id===A.id);S!==-1&&R!==-1&&T(j.id,S,R)}},children:e.jsx(s.SortableContext,{items:j.groups.map(P=>P.id),strategy:s.verticalListSortingStrategy,children:j.groups.map(P=>f(P,I+1,j.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(j.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),g&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>x(j.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},j.id):e.jsx(Vr,{group:j,depth:I,parentGroupId:D,onUpdateGroupOperator:b,onUpdateGroupNegate:h,onRemoveGroup:m,onUpdateCondition:u,onUpdateField:E,onRemoveCondition:p,onReorderConditions:y,onReorderGroups:T,onAddCondition:o,onAddGroup:x,availableFields:l,renderFilterGroup:f,updateConditionFields:N},j.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:[d?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):f(c),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:g,onCheckedChange:j=>w(j)}),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:C(c)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:i,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?c:null),children:"Apply Filters"})]})]})}function $r({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:i,isOpen:c,onOpenChange:l}){const d=x=>{a(t,x),l(!1)},o=()=>{r(t),l(!1)};return e.jsxs(s.Dialog,{modal:!1,open:c,onOpenChange:l,children:[c&&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:x=>{x.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(zr,{filters:n,availableFields:i,onSave:d,onCancel:()=>l(!1),onClearAll:o})]})]})}function qr({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var T,C;const[i,c]=k.useState(null),l=s.useEditorStore(B=>B.card),d=s.useEditorStore(B=>B.actions.updateCardConfig),o=(T=l==null?void 0:l.config)==null?void 0:T.joinPlan,x=k.useCallback(B=>B.entityName===s.CALCULATED_FIELD_ENTITY_MARKER||B.entityName==="calculated_fields"||B.qualifiedEntityName==="calculated_fields",[]),p=(C=l==null?void 0:l.dataSource)==null?void 0:C.semanticDomainId,{data:m}=s.useJoinabilityMap(p),u=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],N=k.useCallback(B=>B.startsWith("card-source-")?"source":B.startsWith("card-")?null:B.startsWith("source-")||n.find(O=>O.id===B)?"source":a("groupBy").find(O=>O.id===B)?"groupBy":a("metrics").find(O=>O.id===B)?"metrics":a("pivotBy").find(O=>O.id===B)?"pivotBy":a("sortBy").find(O=>O.id===B)?"sortBy":a("detailColumns").find(O=>O.id===B)?"detailColumns":null,[n,a]),b=k.useCallback(B=>{c(B.active.id)},[]),h=k.useCallback(B=>{var M;const{active:O,over:L}=B;if(!L||!t){c(null);return}const g=O.id,w=L.id,E=N(g),f=N(w)||w;if(f==="sortBy"){if(E==="source"){const j=n.find(D=>D.id===g);if(!j){c(null);return}if(!(a("groupBy").some(D=>D.name===j.name&&D.qualifiedEntityName===j.qualifiedEntityName)||a("metrics").some(D=>D.name===j.name&&D.qualifiedEntityName===j.qualifiedEntityName)||a("detailColumns").some(D=>D.name===j.name&&D.qualifiedEntityName===j.qualifiedEntityName))){c(null);return}}else if(E==="pivotBy"){c(null);return}else if(E!=="groupBy"&&E!=="metrics"&&E!=="sortBy"&&E!=="detailColumns"){c(null);return}}if(E==="source"&&f==="sortBy"){const j=[...n].find(v=>v.id===g);if(!j){c(null);return}const I=a("sortBy");if(s.fieldAlreadyExists(j,I)){c(null);return}const D=s.validateFieldForChartType(j,"sortBy",l.type);if(!D.isValid){s.ue.error("Invalid Field Type",{description:D.reason,position:"top-center",duration:3e3}),c(null);return}const P=s.getNewField(j,"sortBy",I);c(null),r("sortBy",[...I,P]);return}if(E==="source"&&f!=="source"&&f!=="sortBy"){const j=[...n].find(R=>R.id===g);if(!j){c(null);return}const I=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],D=I.filter(R=>!x(R));if(D.length>0){const R=D[0].qualifiedEntityName;if(!R){c(null);return}if(R!==j.qualifiedEntityName&&!x(j)&&j.qualifiedEntityName)if(p&&(m!=null&&m.joinabilityMap)){if(s.calculateFieldState(j,{joinabilityMap:m.joinabilityMap,selectedFields:I,baseEntityName:(M=o==null?void 0:o.baseEntity)==null?void 0:M.name}).state==="unreachable"){s.showJoinRequiredNotification(),c(null);return}}else{if(!o){s.showJoinRequiredNotification(),c(null);return}if(!s.areEntitiesJoined(R,j.qualifiedEntityName,o)){s.showJoinRequiredNotification(),c(null);return}}}const P=a(f);if(s.fieldAlreadyExists(j,P)){c(null);return}const v=s.validateFieldForChartType(j,f,l.type);if(!v.isValid){s.ue.error("Invalid Field Type",{description:v.reason,position:"top-center",duration:3e3}),c(null);return}const A=s.getNewField(j,f,P),S=[...P,A];c(null),r(f,S),f==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(l.type,l.config,d,t,S);return}if(E&&f&&E!=="source"&&f!=="source"&&E!==f){const j=a(E),I=a(f),D=j.find(R=>R.id===g);if(!D){c(null);return}const P=s.validateFieldForChartType(D,f,l.type);if(!P.isValid){s.ue.error("Invalid Field Type",{description:P.reason,position:"top-center",duration:3e3}),c(null);return}const v=s.getNewField(D,f,I);if(c(null),f==="sortBy"){s.fieldAlreadyExists(D,I)||r(f,[...I,v]);return}const A=j.filter(R=>R.id!==g),S=[...I,v];r(E,A),r(f,S),f==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(l.type,l.config,d,t,S);return}if(E&&f&&E===f&&E!=="source"){const j=a(E),I=j.findIndex(P=>P.id===g),D=j.findIndex(P=>P.id===w);if(I!==D){const P=s.arrayMove(j,I,D);r(E,P)}}c(null)},[t,n,a,r,N,o,p,m,x,l.type,d,l.config]),y=i?u.find(B=>B.id===i):null;return{activeId:i,activeField:y,handleDragStart:b,handleDragEnd:h}}function Kr({activeView:t,onViewChange:n,splitViewEnabled:a}){const r=s.useEditorStore(d=>d.card),{config:i}=k.useContext(s.SemaphorContext).tokenProps,c=(i==null?void 0:i.showInfoTab)!==!1,l=()=>a?!1:!["table","pivotTable","aggregateTable","detailTable"].includes(r.type);return e.jsx(s.Tabs,{value:t,onValueChange:d=>n(d),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"}),l()&&e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),r.type!=="kpi"&&c&&e.jsx(s.TabsTrigger,{value:"info",className:"rounded-md transition data-[state=active]:bg-muted",children:"Info"})]})})}const Gr=[{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 Ur(){var o,x;const t=s.useEditorStore(p=>p.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=k.useState(!1),[i,c]=k.useState(""),l=p=>{if(p==="custom"){r(!0);return}r(!1),n(t.id,parseInt(p))},d=p=>{const m=p.target.value;c(m),m&&!isNaN(parseInt(m))&&n(t.id,parseInt(m))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(s.Input,{type:"number",value:i,onChange:d,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((x=(o=t.config)==null?void 0:o.rowLimit)==null?void 0:x.toString())||"100",onValueChange:l,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:Gr.map(p=>e.jsx(s.SelectItem,{value:p.value,children:p.label},p.value))})]})})}function _r({card:t,queryData:n,isLoading:a,isFetching:r,pagination:i,onPaginationChange:c,onSortChange:l,sortState:d,splitViewEnabled:o}){const x=k.useMemo(()=>(n==null?void 0:n.records)||[],[n==null?void 0:n.records]);return!o||["table","pivotTable","aggregateTable","detailTable"].includes(t.type)?e.jsx(ns,{}):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(ns,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:[(a||r)&&(n==null?void 0:n.records)&&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"})}),(n==null?void 0:n.records)&&e.jsx(s.TableVisual,{card:t,data:x,paginationMetadata:i,onPaginationChange:c,isLoading:a||r,onSortChange:l,sortState:d})]})})]})}const Hr="semaphor-split-view-enabled";function Jr(){return Zs(Hr,!0)}function Yr({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onFiltersClick:i,activeCard:c,columns:l,columnsLoading:d,columnsError:o}){var se,ne,_;const x=s.useEditorStore(W=>W.card),p=s.useDashboardStore(W=>W.filterValues),m=s.useDashboardStore(W=>W.selectedSheetId),u=s.useDashboardStore(W=>W.inlineFilterValuesMap[(c==null?void 0:c.id)||""]),{updateCardConfig:N,setCard:b,updateCardInFrame:h,setShowAIDialog:y}=s.useEditorActions(),T=s.useEditorStore(W=>W.showAIDialog),C=s.useDashboardStore(W=>W.isVisualEditing),[B,O]=k.useState(!1),[L,g]=k.useState(!1),[w,E]=k.useState(null),{config:f}=k.useContext(s.SemaphorContext).tokenProps,M=(f==null?void 0:f.showInfoTab)!==!1,[j,I]=Jr();s.useEditorStore(W=>{var le;return!!((le=W.card.customCardPreferences)!=null&&le.url)});const{data:D,errorMessage:P,isLoading:v,isFetching:A,errorSql:S,pagination:R,refetch:F,comparisonMetadata:z}=s.useDashboardCardQuery(c),G=k.useMemo(()=>(D==null?void 0:D.records)||[],[D==null?void 0:D.records]),[V,U]=k.useState(!1);k.useEffect(()=>{A||U(!1)},[A]);const Q=()=>{const W=!j;W&&t==="table"&&n("chart"),I(W)},J=(W,le)=>{const he={...c,paginationConfig:{page:W+1,pageSize:le}};b(he),h(he)};function Z(){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(x.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(p||{},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(c.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",l.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:d?"Loading...":o?"Error loading columns":JSON.stringify(l.slice(0,5),null,2)})]})]})]})}const q=W=>{if(!x.config)return;const le=s.sortStateToSortByColumns(W,x.config.metricColumns,x.config.groupByColumns,x.config.detailColumns);N(x.id,{...x.config,sortByColumns:le})},Y=k.useMemo(()=>{var W;return s.sortByColumnsToSortState((W=x.config)==null?void 0:W.sortByColumns)},[(se=x.config)==null?void 0:se.sortByColumns]);return e.jsxs("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":T&&C}),children:[a&&Z(),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"&&T&&e.jsx("div",{className:"w-[260px]",children:e.jsx(os,{variant:"outline"})}),e.jsx(Kr,{activeView:t,onViewChange:n,splitViewEnabled:j}),e.jsx(s.FilterInfo,{cardId:c.id,cardFilters:(ne=c.config)==null?void 0:ne.filters,cardFilterCount:s.getFilterCount(((_=c.config)==null?void 0:_.filters)||null),onFiltersClick:i,inlineFilters:c.inlineFilters,inlineFilterValues:u,sheetId:m||""}),z&&x.type!=="table"&&e.jsx(s.ComparisonMetadataBadge,{metadata:z,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Ur,{})}),T&&e.jsx(ye.EditorClearButton,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:v||A,onClick:()=>{U(!0),F()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":V})})}),t==="chart"&&e.jsx(s.IconButton,{tooltip:j?"Hide Results Table":"Show Results Table",onClick:Q,children:j?e.jsx(Vt,{className:"size-4"}):e.jsx(ea,{className:"size-4"})}),t==="chart"&&e.jsx(e.Fragment,{children:e.jsx(rt,{})}),!T&&e.jsx(s.IconButton,{onClick:()=>y(!T),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),r&&s.isDevEnv]})]}),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":j&&!["table","pivotTable","aggregateTable","detailTable"].includes(c.type)}),children:e.jsx(_r,{card:c,queryData:D,isLoading:v,isFetching:A,pagination:R,onPaginationChange:J,onSortChange:q,sortState:Y,splitViewEnabled:j})}),t==="table"&&(D==null?void 0:D.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:[(v||A)&&(D==null?void 0:D.records)&&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"})}),e.jsx(s.TableVisual,{card:c,data:G,comparisonMetadata:z,paginationMetadata:R,onPaginationChange:J,isLoading:v||A,onSortChange:q,sortState:Y})]}),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:P?e.jsx(ls,{error:P,errorSql:S,onSendFeedback:()=>{const W=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:x.config,dataSource:c.dataSource,dashboardFilters:p,errorMessage:P,errorSql:S,generatedSql:D==null?void 0:D.sql});E(W),g(!0)},onOpenInEditor:()=>{y(!0),setTimeout(()=>{const W=s.useEditorStore.getState().actions;W.setIsDevMode(!0),W.setCardSql(S||""),setTimeout(()=>{W.setRunSql(!0)},100)},100)}}):(D==null?void 0:D.sql)&&e.jsx(tt,{sql:D.sql,showCardDetails:!0})})})]}),w&&e.jsx(s.FeedbackDialog,{open:L,onOpenChange:g,feedbackData:w})]})]})}function Qr({activeField:t}){const[n,a]=k.useState(!0);return k.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(cs,{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 Wr=()=>{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 i;if((i=r.reason)!=null&&i.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 Xr({column:t,isSelected:n,onSelect:a,availableFields:r,width:i,onWidthChange:c}){var F,z,G;const l=s.useEditorStore(V=>V.card),{updateCardConfig:d,removeGroupByColumn:o,removeMetricColumn:x,updateFilters:p}=s.useEditorActions(),[m,u]=k.useState(!1),[N,b]=k.useState(!1),h=k.useRef(null),y=k.useCallback(V=>{V.preventDefault(),V.stopPropagation(),b(!0),h.current={startX:V.clientX,startWidth:i||150};const U=J=>{if(!h.current)return;const Z=J.clientX-h.current.startX,q=Math.max(80,h.current.startWidth+Z);c==null||c(t.id,q)},Q=()=>{b(!1),h.current=null,document.removeEventListener("mousemove",U),document.removeEventListener("mouseup",Q)};document.addEventListener("mousemove",U),document.addEventListener("mouseup",Q)},[i,t.id,c]),T=(F=l==null?void 0:l.config)==null?void 0:F.filters,C=(z=T==null?void 0:T.conditions)==null?void 0:z.some(V=>V.field.name===t.name&&V.field.qualifiedEntityName===t.qualifiedEntityName),B=V=>{V?p(l.id,V):d(l.id,{filters:void 0})},{attributes:O,listeners:L,setNodeRef:g,transform:w,transition:E,isDragging:f}=s.useSortable({id:t.id}),M={transform:s.CSS.Transform.toString(w),transition:E},j=s.getDataType(t.dataType),I=Zr(j),D=()=>{var Q;const V=((Q=l==null?void 0:l.config)==null?void 0:Q.sortByColumns)||[],U=V.findIndex(J=>J.name===t.name);if(U!==-1){const J=[...V];J[U]={...J[U],direction:"asc"},d(l.id,{sortByColumns:J})}else d(l.id,{sortByColumns:[...V,{...t,id:`sort-${t.id}`,role:"sortby",direction:"asc"}]})},P=()=>{var Q;const V=((Q=l==null?void 0:l.config)==null?void 0:Q.sortByColumns)||[],U=V.findIndex(J=>J.name===t.name);if(U!==-1){const J=[...V];J[U]={...J[U],direction:"desc"},d(l.id,{sortByColumns:J})}else d(l.id,{sortByColumns:[...V,{...t,id:`sort-${t.id}`,role:"sortby",direction:"desc"}]})},v=()=>{var Q;const V=((Q=l==null?void 0:l.config)==null?void 0:Q.groupByColumns)||[];if(!V.some(J=>J.name===t.name)){const J={...t,id:`groupby-${t.id}-${Date.now()}`,role:"groupby"};d(l.id,{groupByColumns:[...V,J]})}},A=V=>{var J;const U=((J=l==null?void 0:l.config)==null?void 0:J.metricColumns)||[];if(!U.some(Z=>Z.name===t.name&&Z.aggregate===V)){const Z={...t,id:`metric-${t.id}-${V}-${Date.now()}`,label:`${V} of ${t.label||t.name}`,role:"metric",aggregate:V};d(l.id,{metricColumns:[...U,Z]})}},S=()=>{t.role==="groupby"?o(l.id,t.id):t.role==="metric"&&x(l.id,t.id)},R={...M,width:i?`${i}px`:void 0,minWidth:i?`${i}px`:"120px"};return e.jsxs("th",{ref:g,style:R,className:s.cn("group relative border-r border-border bg-background px-1 py-0",f&&"opacity-50",n&&"bg-primary/10",N&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...O,...L,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(I,{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,")"]}),C&&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:()=>u(!0),children:[e.jsx(s.Filter,{className:s.cn("mr-2 h-4 w-4",C&&"text-primary")}),C?"Edit Filter":"Filter"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:D,children:[e.jsx(Ft,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(s.DropdownMenuItem,{onClick:P,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:()=>A("SUM"),children:"Sum"}),e.jsx(s.DropdownMenuItem,{onClick:()=>A("AVG"),children:"Average"}),e.jsx(s.DropdownMenuItem,{onClick:()=>A("COUNT"),children:"Count"}),e.jsx(s.DropdownMenuItem,{onClick:()=>A("DISTINCT"),children:"Count Distinct"}),e.jsx(s.DropdownMenuItem,{onClick:()=>A("MIN"),children:"Min"}),e.jsx(s.DropdownMenuItem,{onClick:()=>A("MAX"),children:"Max"})]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:v,children:[e.jsx(rs,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(s.DropdownMenuItem,{disabled:!0,children:[e.jsx(Hs,{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:S,className:"text-destructive focus:text-destructive",children:[e.jsx(s.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:y,className:s.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",N&&"bg-primary")}),e.jsx(dt,{open:m,onOpenChange:u,availableFields:r.length>0?r:[t],existingFilters:T,editingCondition:C?(G=T==null?void 0:T.conditions)==null?void 0:G.find(V=>V.field.name===t.name&&V.field.qualifiedEntityName===t.qualifiedEntityName):void 0,onSave:B})]})}function Zr(t){switch(t){case"number":return s.Hash;case"date":return s.Calendar;case"string":default:return s.Type}}function el({selectedColumn:t,onColumnSelect:n,isLoading:a=!1,sourceFields:r=[]}){var E,f,M,j;const i=s.useEditorStore(I=>I.card),{updateCardConfig:c}=s.useEditorActions(),[l,d]=k.useState(null),[o,x]=k.useState({}),[p,m]=k.useState(!1),u=k.useMemo(()=>{var P,v;const I=((P=i==null?void 0:i.config)==null?void 0:P.groupByColumns)||[],D=((v=i==null?void 0:i.config)==null?void 0:v.metricColumns)||[];return[...I,...D]},[(E=i==null?void 0:i.config)==null?void 0:E.groupByColumns,(f=i==null?void 0:i.config)==null?void 0:f.metricColumns]),N=k.useMemo(()=>{const I=new Set(u.map(D=>`${D.qualifiedEntityName}.${D.name}`));return r.filter(D=>!I.has(`${D.qualifiedEntityName}.${D.name}`))},[r,u]),{data:b,isLoading:h}=s.useDashboardCardQuery(i),y=(b==null?void 0:b.records)||[],T=k.useCallback((I,D)=>{x(P=>({...P,[I]:D}))},[]),C=k.useCallback(I=>{var A,S;const D=s.getDataType(I.dataType),P=((A=i==null?void 0:i.config)==null?void 0:A.groupByColumns)||[],v=((S=i==null?void 0:i.config)==null?void 0:S.metricColumns)||[];if(D==="number"){const R={...I,id:`metric-${I.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};c(i.id,{metricColumns:[...v,R]})}else{const R={...I,id:`groupby-${I.id}-${Date.now()}`,role:"groupby"};c(i.id,{groupByColumns:[...P,R]})}m(!1)},[(M=i==null?void 0:i.config)==null?void 0:M.groupByColumns,(j=i==null?void 0:i.config)==null?void 0:j.metricColumns,i.id,c]),B=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),O=I=>{d(I.active.id)},L=I=>{const{active:D,over:P}=I;if(d(null),!P||D.id===P.id)return;const v=u.findIndex(S=>S.id===D.id),A=u.findIndex(S=>S.id===P.id);if(v!==-1&&A!==-1){const S=s.arrayMove(u,v,A),R=S.filter(z=>z.role==="groupby"),F=S.filter(z=>z.role==="metric");c(i.id,{groupByColumns:R,metricColumns:F})}},g=l?u.find(I=>I.id===l):null,w=I=>{let D="";for(;I>=0;)D=String.fromCharCode(I%26+65)+D,I=Math.floor(I/26)-1;return D};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"})}):u.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:L,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:u.map(I=>I.id),strategy:s.horizontalListSortingStrategy,children:u.map((I,D)=>e.jsx("th",{style:{width:o[I.id]?`${o[I.id]}px`:void 0,minWidth:o[I.id]?`${o[I.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:w(D)},`letter-${I.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:u.map(I=>I.id),strategy:s.horizontalListSortingStrategy,children:u.map(I=>e.jsx(Xr,{column:I,isSelected:(t==null?void 0:t.id)===I.id,onSelect:()=>n(I),availableFields:r,width:o[I.id],onWidthChange:T},I.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(s.Popover,{open:p,onOpenChange:m,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:N.map(I=>{const D=s.getDataType(I.dataType),P=D==="number"?s.Hash:D==="date"?s.Calendar:s.Type;return e.jsxs(s.CommandItem,{value:I.label||I.name,onSelect:()=>C(I),children:[e.jsx(P,{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:I.label||I.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:I.entityName})]})]},I.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:h?e.jsx("tr",{children:e.jsx("td",{colSpan:u.length+2,className:"h-32 text-center",children:e.jsx(s.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):y.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:u.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):y.slice(0,100).map((I,D)=>e.jsxs("tr",{className:s.cn("border-b border-border transition-colors hover:bg-muted/50",D%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:D+1}),u.map(P=>{const v=I[P.name]??I[P.label??""];return e.jsx("td",{style:{width:o[P.id]?`${o[P.id]}px`:void 0,minWidth:o[P.id]?`${o[P.id]}px`:"120px"},className:s.cn("border-r border-border px-3 py-2 text-sm",(t==null?void 0:t.id)===P.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:sl(v,P)})},`${D}-${P.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},D))})]}),e.jsx(s.DragOverlay,{children:g&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:g.label||g.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(y.length,100)," of ",y.length," rows"]}),e.jsxs("span",{children:[u.length," columns"]})]})]})}function sl(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 tl({entityGroups:t,isLoading:n=!1}){var B,O;const a=s.useEditorStore(L=>L.card),{updateCardConfig:r,removeGroupByColumn:i,removeMetricColumn:c}=s.useEditorActions(),[l,d]=k.useState(!0),[o,x]=k.useState(""),[p,m]=k.useState(new Set),u=((B=a==null?void 0:a.config)==null?void 0:B.groupByColumns)||[],N=((O=a==null?void 0:a.config)==null?void 0:O.metricColumns)||[],b=L=>{const g=new Set(p);g.has(L)?g.delete(L):g.add(L),m(g)},h=L=>u.some(g=>g.name===L.name&&g.qualifiedEntityName===L.qualifiedEntityName)||N.some(g=>g.name===L.name&&g.qualifiedEntityName===L.qualifiedEntityName),y=(L,g)=>{if(g)if(s.getDataType(L.dataType)==="number"){const E={...L,id:`metric-${L.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(a.id,{metricColumns:[...N,E]})}else{const E={...L,id:`groupby-${L.id}-${Date.now()}`,role:"groupby"};r(a.id,{groupByColumns:[...u,E]})}else{const w=u.findIndex(f=>f.name===L.name&&f.qualifiedEntityName===L.qualifiedEntityName),E=N.findIndex(f=>f.name===L.name&&f.qualifiedEntityName===L.qualifiedEntityName);w!==-1&&i(a.id,u[w].id),E!==-1&&c(a.id,N[E].id)}},T=L=>{if(!o)return L;const g=o.toLowerCase();return L.filter(w=>w.name.toLowerCase().includes(g)||w.label&&w.label.toLowerCase().includes(g))},C=L=>{switch(s.getDataType(L)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.Type}};return l?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:()=>d(!1),title:"Close panel",children:e.jsx(Yt,{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,{placeholder:"Search columns...",value:o,onChange:L=>x(L.target.value),className:"h-8 pl-8 text-sm"})]})}),(u.length>0||N.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[u.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(rs,{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:u.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:u.map(L=>{const g=C(L.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(g,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:L.label||L.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:()=>i(a.id,L.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},L.id)})})})]}),N.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:N.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:N.map(L=>{const g=C(L.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(g,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:L.label||L.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:L.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:()=>c(a.id,L.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},L.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(L=>{const g=T(L.columns);if(g.length===0)return null;const w=p.has(L.entityId)||o.length>0;return e.jsxs(s.Collapsible,{open:w,onOpenChange:()=>b(L.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",w&&"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:L.label||L.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:g.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:g.map(E=>{const f=C(E.dataType),M=h(E);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:j=>y(E,j),className:"h-3.5 w-3.5"}),e.jsx(f,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:E.label||E.name})]},E.id)})})})]},L.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:()=>d(!0),title:"Open panel",children:e.jsx(Qt,{className:"h-4 w-4"})})})}const al=[{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 nl({value:t,onChange:n,onSubmit:a,onCancel:r,selectedColumn:i,availableColumns:c}){const[l,d]=k.useState(!1),[o,x]=k.useState("column"),p=k.useRef(null);k.useEffect(()=>{const b=h=>{h.key==="Escape"&&t?r():h.key==="Enter"&&t&&!l&&a(t)};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[t,r,a,l]);const m=b=>{const h=`[${b.label||b.name}]`,y=p.current;if(y){const T=y.selectionStart||0,C=y.selectionEnd||0,B=t.slice(0,T)+h+t.slice(C);n(B),setTimeout(()=>{y.setSelectionRange(T+h.length,T+h.length),y.focus()},0)}else n(t+h);d(!1)},u=b=>{const h=p.current;if(h){const y=h.selectionStart||0,T=h.selectionEnd||0,C=t.slice(0,y)+b.syntax+t.slice(T);n(C),setTimeout(()=>{h.setSelectionRange(y+b.name.length+1,y+b.syntax.length-1),h.focus()},0)}else n(t+b.syntax);d(!1)},N=b=>{switch(s.getDataType(b)){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:i?e.jsx("span",{className:"truncate",children:i.label||i.name}):e.jsx("span",{children:"—"})}),e.jsxs(s.Popover,{open:l&&o==="function",onOpenChange:b=>{d(b),b&&x("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(Zt,{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:al.map(b=>e.jsx(s.CommandItem,{value:b.name,onSelect:()=>u(b),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:b.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:b.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:b.syntax})]})},b.name))})]})]})})]}),e.jsxs(s.Popover,{open:l&&o==="column",onOpenChange:b=>{d(b),b&&x("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:c.map(b=>{const h=N(b.dataType);return e.jsxs(s.CommandItem,{value:b.label||b.name,onSelect:()=>m(b),children:[e.jsx(h,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:b.label||b.name})]},b.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(s.Input,{ref:p,value:t,onChange:b=>n(b.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 rl({className:t}){var u,N,b,h;const n=s.useEditorStore(y=>y.card),[a,r]=k.useState(null),[i,c]=k.useState(""),{columns:l=[],columnGroups:d=[],isLoading:o}=s.useColumns();(u=n==null?void 0:n.config)!=null&&u.groupByColumns,(N=n==null?void 0:n.config)!=null&&N.metricColumns,(b=n==null?void 0:n.config)!=null&&b.groupByColumns,(h=n==null?void 0:n.config)!=null&&h.pivotByColumns;const x=y=>{r(y),c(y?`[${y.label||y.name}]`:"")},p=y=>{console.log("Formula submitted:",y),c(""),r(null)},m=()=>{c(""),r(null)};return e.jsxs("div",{className:s.cn("flex h-full w-full flex-col",t),children:[e.jsx(nl,{value:i,onChange:c,onSubmit:p,onCancel:m,selectedColumn:a,availableColumns:l}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(el,{selectedColumn:a,onColumnSelect:x,isLoading:o,sourceFields:l})}),e.jsx(tl,{entityGroups:d,isLoading:o})]})]})}function ll(){var z,G;const[t,n]=k.useState("chart"),[a,r]=k.useState(!1),[i,c]=k.useState(!1),[l,d]=k.useState(!0),o=s.useEditorStore(V=>V.showAIDialog),x=s.useDashboardStore(V=>V.isVisualEditing),{setCardType:p}=s.useEditorActions(),m=s.useEditorStore(V=>V.card.type);k.useEffect(()=>Wr(),[]);const u=V=>{p(V)},N=s.useEditorStore(V=>V.frame),b=s.useEditorStore(V=>V.card);s.useEditorStore(V=>V.activeTabCardId),s.useEditorStore(V=>V.actions.getAvailableFields);const{addCard:h,removeCard:y,updateCard:T,setActiveCard:C,updateFilters:B}=s.useEditorActions(),{columnFields:O=[],scopedFields:L=[],isLoading:g,error:w}=s.useScopedFields(),E=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),f=b,{getFieldsForContainer:M,setFieldsForContainer:j}=s.useFieldManagement(f),{activeField:I,handleDragStart:D,handleDragEnd:P}=qr({activeCardId:N.activeCardId,sourceFields:L,getFieldsForContainer:M,setFieldsForContainer:j}),v=(V,U)=>{U&&B(V,U)},A=V=>{var U;T(V,{config:{...(U=N.cards.find(Q=>Q.id===V))==null?void 0:U.config,filters:void 0}})},S=O,R=V=>{if(!V)return 0;let U=V.conditions.length;return V.groups.forEach(Q=>{U+=R(Q)}),U},F=R(((z=f==null?void 0:f.config)==null?void 0:z.filters)||null);return e.jsxs(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragStart:D,onDragEnd:P,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(et,{isVisible:l,onToggleVisibility:()=>d(!l)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:m==="tableBuilder"?e.jsx(rl,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!o&&e.jsx(Sr,{selectedChart:m,onChartChange:u,groupByFields:M("groupBy"),pivotByFields:M("pivotBy"),metricsFields:M("metrics"),sortByFields:M("sortBy"),detailFields:M("detailColumns"),activeField:I}),e.jsx(Yr,{selectedChart:m,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onFiltersClick:()=>c(!0),filterCount:F,activeCard:f,dataSourceState:b.dataSource||s.EMPTY_DATA_SOURCE,columns:O,columnsLoading:g,columnsError:w,getFieldsForContainer:M,cards:N.cards,activeCardId:N.activeCardId,addCard:h,setActiveCard:C})]})}),!l&&x&&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:()=>d(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),f&&e.jsx($r,{cardId:f.id,filters:((G=f.config)==null?void 0:G.filters)||null,onFiltersChange:v,onClearFilters:A,availableFields:S,isOpen:i,onOpenChange:c}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Qr,{activeField:I||null})})]})}function ol({authToken:t,onSave:n,onClose:a}){const r=k.useRef(null),i=s.useEditorStore(g=>g.showAIDialog),c=s.useEditorStore(g=>g.isDevMode),l=s.useAssistantLayoutStore(g=>g.setFullscreen),d=s.useAssistantLayoutStore(g=>g.setPanelOpen),o=s.useAssistantLayoutStore(g=>g.setContainer),x=s.useAssistantPanel("editor"),p=s.useFullscreenAssistant(),m=s.useAssistantContainer("editor"),u=p==="editor",N=k.useCallback(g=>{o("editor",g)},[o]),{setAuthToken:b}=s.useDashboardActions(),{setShowAIDialog:h,setOnSave:y,setOnClose:T}=s.useEditorActions(),{setActiveAssistantType:C}=s.useAIActions();k.useEffect(()=>{n&&y(n),a&&T(a)},[n,y,a,T]),k.useEffect(()=>{t&&t.accessToken&&b(t)},[t,b]),k.useEffect(()=>{var g,w;i?((g=r.current)==null||g.resize(40),d("editor",!0),C("editor")):((w=r.current)==null||w.resize(0),d("editor",!1),p==="editor"&&l(null),C(null))},[i,d,C,l,p]);function B(g){var w;g<1?(h(!1),d("editor",!1),p==="editor"&&l(null),C(null),(w=r.current)==null||w.resize(0)):(i||(h(!0),C("editor")),x.isOpen||d("editor",!0))}function O(){return e.jsxs(e.Fragment,{children:[e.jsx(et,{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",u&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(or,{})}),e.jsx(s.ResizableHandle,{disabled:!i}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:B,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Ks,{isFullscreen:u,onFullscreenChange:g=>l(g?"editor":null),fullscreenContainer:m})})})]}),e.jsx("div",{ref:N,className:s.cn("absolute inset-0",!u&&"pointer-events-none")})]})]})}function L(){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",u&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(ll,{})}),e.jsx(s.ResizableHandle,{disabled:!i}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:B,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Ks,{isFullscreen:u,onFullscreenChange:g=>l(g?"editor":null),fullscreenContainer:m})})})]}),e.jsx("div",{ref:N,className:s.cn("absolute inset-0",!u&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:c?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:O()}):L()})}function il(){s.useDashboardStore(l=>l.selectedCardId);const t=s.useDashboardStore(l=>l.selectedSheetId),{setIsVisualEditing:n}=s.useDashboardStore(l=>l.actions),a=s.useDashboardStore(l=>l.isVisualEditing),r=s.useDashboardStore(l=>l.actions.updateFrame);function i(l){t&&(r(t,l),n(!1))}function c(){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(ol,{onSave:i,onClose:c})})}exports.default=il;
177
+ `;l(x)}:void 0}}function nt({className:t,...n}){var ne,_,W,le,he;const a=s.useEditorStore($=>$.card),r=((ne=a.customCardPreferences)==null?void 0:ne.showCardHeader)??!0,i=((W=(_=a.preferences)==null?void 0:_.displayOptions)==null?void 0:W.showInlineFilterBar)??!0,c=s.useEditorStore($=>$.frame),l=s.useDashboardStore($=>$.dashboard.filters),d=s.useDashboardStore($=>$.selectedSheetId),[o,x]=I.useState(!1),{currentUser:p}=s.useCurrentUserInfo(),{tokenProps:m}=I.useContext(s.SemaphorContext),u=s.useEditorStore($=>$.actions.setRunSql),{updateFilter:N}=s.useDashboardActions(),b=l==null?void 0:l.find($=>$.id===c.filterId),h=I.useMemo(()=>s.findCustomVisualConfigCard(c,a),[c,a]),{manifest:y}=s.useCustomVisual(((le=h==null?void 0:h.customCardPreferences)==null?void 0:le.url)||""),T=I.useMemo(()=>{var $;return($=y==null?void 0:y.visuals)==null?void 0:$.find(H=>{var ae;return H.name===((ae=h==null?void 0:h.customCardPreferences)==null?void 0:ae.componentName)})},[y,(he=h==null?void 0:h.customCardPreferences)==null?void 0:he.componentName]),C=s.resolveMultiInputType(h,T),B=I.useMemo(()=>s.getCustomVisualInputCards({frame:c,configCard:h,isMultiInputVisual:C==="multiple"}),[c,h,C]),O=I.useMemo(()=>{const $=B.findIndex(H=>(H==null?void 0:H.id)===(a==null?void 0:a.id));return $<0?-1:s.getSlotIndexForCard(a,$)},[B,a]),L=I.useMemo(()=>!h||C!=="multiple"||O<0?a.type:s.getEffectiveCardTypeForSlot(a,O,T==null?void 0:T.slots)??a.type,[h,C,O,a,T==null?void 0:T.slots]),g=L??a.type,w=I.useMemo(()=>g===a.type?a:{...a,type:g},[a,g]),E=I.useMemo(()=>L!==a.type?{...a,type:L}:a,[a,L]),{data:f,isLoading:M,isFetching:j,errorMessage:k,errorSql:D,pagination:P}=s.useDashboardCardQuery(E),{handleOpenInEditor:v,handleDebugWithAssistant:A}=at(k,D||a.sql||a.python),S=I.useMemo(()=>(f==null?void 0:f.records)||[],[f==null?void 0:f.records]),{setCard:R,updateCardInFrame:F}=s.useEditorActions(),{data:z}=s.useTopoJson(w),G=I.useMemo(()=>{var $;return g!=="pivotTable"||!(($=f==null?void 0:f.records)!=null&&$.length)?null:{records:f.records,columnSubtotalMeta:f.columnSubtotalMeta,subtotalColumns:f.subtotalColumns||[],pivotSchema:f.pivotSchema||[],groupByColumns:f.groupByColumns}},[g,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]),V=s.usePivotTableConfig(w,G),U=()=>{x(!0)},Q=I.useMemo(()=>{const $=typeof window<"u"?window.location.href:"",H=typeof navigator<"u"?navigator.userAgent:"",ae=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:s.FeedbackCategory.QUERY_GENERATION,user:p,tokenContext:m,systemState:{cardConfig:a.config,dataSource:a.dataSource,dashboardFilters:l,errorMessage:k||void 0,errorSql:D||a.sql||a.python,generatedSql:D||a.sql},metadata:{url:$,userAgent:H,timestamp:new Date().toISOString(),viewport:ae}}},[p,m,a,l,k,D]),J=($,H)=>{var ie,ge;const ae={...a,paginationConfig:{page:$+1,pageSize:H}};R(ae),F(ae),a.sql&&((ge=(ie=a.preferences)==null?void 0:ie.tablePrefs)!=null&&ge.enableDevModePagination)&&u(!0)},Z=$=>{var ie,ge,je,ve,Ne;const H=s.sortStateToSortByColumns($,(ie=a.config)==null?void 0:ie.metricColumns,(ge=a.config)==null?void 0:ge.groupByColumns,(je=a.config)==null?void 0:je.detailColumns),ae={...a,config:{...a.config||{},sortByColumns:H}};R(ae),F(ae),a.sql&&((Ne=(ve=a.preferences)==null?void 0:ve.tablePrefs)!=null&&Ne.enableDevModePagination)&&u(!0)},q=I.useMemo(()=>!w.id||!(f!=null&&f.records)?null:s.createChartConfig({card:w,data:f==null?void 0:f.records,cardType:g,queryConfig:w.queryConfig,customCfg:w.customCfg,preferences:w.preferences,topoJson:z}),[w.id,f==null?void 0:f.records,g,w.customCfg,w.preferences,z]);function Y($){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(s.EditorCustomVisual,{card:$})})}function se(){var $;if(f!=null&&f.records&&(f==null?void 0:f.records.length)===0&&!M&&!j)return k?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ls,{error:k,errorSql:D||a.sql||a.python,onOpenInEditor:v,onDebugWithAssistant:A,onSendFeedback:U,showFeedbackButton:!0})}):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((M||j)&&(!(f!=null&&f.records)||f.records.length===0))return g==="table"||g==="detailTable"?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(!w.id)return null;if(g==="custom")return Y(a);if(!["table","pivotTable","aggregateTable","detailTable","custom"].includes(g)&&q)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:M||j?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:q})});if(g==="table"||g==="detailTable")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:w,data:S,comparisonMetadata:($=f==null?void 0:f.metadata)==null?void 0:$.comparisonMetadata,paginationMetadata:P,onPaginationChange:J,onSortChange:Z,isLoading:M||j})});if(g==="pivotTable"&&V)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:w,data:V.data,options:V.options,onAggregationChange:H=>{const ae=s.handleAggregationChange(H,a.config),ie={...a,config:ae};R(ie),F(ie)},onAggregationLabelChange:H=>{const ae=s.handleAggregationLabelChange(H,a.config),ie={...a,config:ae};R(ie),F(ie)}})});if(g==="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:w,data:(f==null?void 0:f.records)||[],groupByColumns:f==null?void 0:f.groupByColumns,pivotSchema:f==null?void 0:f.pivotSchema,paginationMetadata:P,onPaginationChange:J,onAggregationChange:H=>{const ae=s.handleAggregationChange(H,a.config),ie={...a,config:ae};R(ie),F(ie)},isLoading:M||j})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[(M||j)&&(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:$=>R({...a,title:$}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(pa,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(ha,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:(a.description||"").trim(),onSave:$=>R({...a,description:$.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),b&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:b.title||b.column,onSave:$=>N({...b,title:$}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:b})]})]}),i&&a.inlineFilters&&a.inlineFilters.length>0&&e.jsx("div",{className:"px-6 pb-3",children:e.jsx(s.InlineFilterBar,{card:a,sheetId:d||""})}),e.jsxs(s.CardContent,{className:"flex min-h-0 grow flex-col",children:[e.jsx("div",{className:"min-h-0 flex-1 grow basis-0",children:se()}),s.isCardSummaryVisibleOnCard(w)&&e.jsx("div",{className:"pt-3",children:e.jsx(s.CardSummary,{card:w,mode:"editor"})})]}),e.jsx(s.FeedbackDialog,{open:o,onOpenChange:x,feedbackData:Q,showDebugInfo:!0})]})}const Qe=({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}),fa=()=>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."})]})]}),ga=({customCode:t,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:i})=>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(Qe,{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(Qe,{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(Qe,{language:"javascript",value:t,onChange:i})})]}),ja=({error:t,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:i})=>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:i,variant:"outline",children:"Close"})]});function ba(){const[t,n]=I.useState(!1),[a,r]=I.useState(""),[i,c]=I.useState(""),[l,d]=I.useState(""),[o,x]=I.useState(""),p=s.useEditorStore(w=>w.card),m=ye.useEffectiveEditorCardType(),u=s.useEditorStore(w=>w.card.customCfg),N=u?JSON.stringify(u,null,2):"",b=I.useMemo(()=>m!==p.type?{...p,type:m}:p,[p,m]),{data:h}=s.useDashboardCardQuery(b),{data:y}=s.useTopoJson(p),{setCardCustomCfg:T,setCustomVisualCode:C}=s.useEditorActions(),B=w=>{var E,f;return JSON.stringify({...w,data:{...w.data,datasets:(f=(E=w.data)==null?void 0:E.datasets)==null?void 0:f.map(M=>({...M,data:[]}))}},null,2)},O=()=>{var E,f;if(!((E=h==null?void 0:h.records)!=null&&E.length))return;const w=s.createChartConfig({card:p,data:h.records,cardType:p.type,queryConfig:p.queryConfig,preferences:p.preferences,topoJson:y});if(w){r(B(w)),d(((f=p.preferences)==null?void 0:f.customVisualCode)||"");const M=s.merge(w,u);c(B(M))}},L=()=>{try{if(l&&C(l),i){const w=JSON.parse(i),E=s.getObjectDiff(JSON.parse(a),w);T(E),x("")}}catch{x("Invalid JSON configuration")}},g=Object.keys(u||{}).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:O,className:g?"":"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(fa,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(nt,{className:"w-1/2 rounded shadow-none"})}),e.jsx(ga,{customCode:l,cardCustomCfgString:N,mergedConfig:i,onConfigChange:w=>c(w??""),onCodeChange:w=>d(w??"")})]}),e.jsx(ja,{error:o,hasCardCustomConfig:!!u,onReset:()=>{c(a),T(null)},onApply:L,onClose:()=>n(!1)})]})]})}function ya({isStarred:t,onClick:n,className:a}){const r=i=>{i.stopPropagation(),i.preventDefault(),n(i)};return e.jsx("button",{type:"button",onClick:r,className:s.cn("flex items-center justify-center rounded-sm p-0.5 transition-all","hover:bg-muted/80",a),"aria-label":t?"Remove from favorites":"Add to favorites",children:e.jsx(s.Star,{className:s.cn("h-3.5 w-3.5 transition-colors",t?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-foreground")})})}function Ds({chartType:t,chartName:n,isCustom:a=!1,pluginName:r,isStarred:i,showStar:c=!0,onSelect:l,onToggleStar:d}){return e.jsxs("button",{onClick:l,className:s.cn("group relative 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:[c&&e.jsx("div",{className:s.cn("absolute left-1 top-1 transition-opacity",i?"opacity-100":"opacity-0 group-hover:opacity-100"),children:e.jsx(ya,{isStarred:i,onClick:()=>d()})}),a&&r&&e.jsx("div",{className:"absolute right-1 top-1",children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center justify-center",children:e.jsx(s.Info,{className:"h-3 w-3 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"top",className:"text-xs",children:r})]})}),e.jsx(s.ChartIcon,{chartType:t,chartName:n,isCustom:a,className:"h-6 w-6"}),e.jsx("span",{title:n,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:n})]})}const Ls=[{id:"table",name:"Table"},{id:"bar",name:"Bar Chart"},{id:"line",name:"Line Chart"},{id:"area",name:"Area Chart"},{id:"combo",name:"Combo Chart"},{id:"stackedBar",name:"Stacked Bar"},{id:"stackedArea",name:"Stacked Area"},{id:"stackedLine",name:"Stacked Line"},{id:"scatter",name:"Scatter"},{id:"bubble",name:"Bubble"},{id:"pie",name:"Pie Chart"},{id:"doughnut",name:"Doughnut"},{id:"funnel",name:"Funnel"},{id:"radar",name:"Radar"},{id:"polarArea",name:"Polar Area"},{id:"tornado",name:"Tornado"},{id:"range",name:"Range"},{id:"bullet",name:"Bullet Chart"},{id:"treemap",name:"Treemap"},{id:"heatmap",name:"Heatmap"},{id:"kpi",name:"KPI"},{id:"text",name:"Text"},{id:"map",name:"Map"}];function va({onChartSelect:t,onClose:n}){const[a,r]=I.useState(""),{starredCharts:i,isStarred:c,toggleStar:l}=s.useStarredChartsStore(),{data:d=[],isLoading:o}=s.useCustomVisualsQuery(),{setCardType:x,setCardPreferences:p,setIsDevMode:m}=s.useEditorStore(f=>f.actions),u=s.useEditorStore(f=>f.card),{setCardCustomCfg:N,setCustomCardPreferences:b,setQueryConfig:h,replaceFrameCards:y,clearModeDrafts:T,initializeModeDrafts:C}=s.useEditorActions(),B=I.useMemo(()=>{if(!a)return Ls;const f=a.toLowerCase();return Ls.filter(M=>M.name.toLowerCase().includes(f))},[a]),O=I.useMemo(()=>{const f=d.filter(j=>j.componentType==="chart"&&j.pluginType!=="standard");if(!a)return f;const M=a.toLowerCase();return f.filter(j=>j.name.toLowerCase().includes(M))},[d,a]),L=f=>{N(null),p({}),x(f),["custom","text","map"].includes(f)&&(m(!0),h(void 0)),t==null||t(f),n==null||n()},g=f=>{N(null),p({}),h(void 0);const M=s.resolveMultiInputTypeFromVisual(f);if(M==="multiple"&&f.slots&&f.slots.length>0){T();const k=s.createCardsFromSlots(f.slots,f,u);y(k),k[0]&&C(k[0]),n==null||n();return}else x("custom"),b({type:"component",visualType:M,url:f.url,componentName:f.name,icon:f.icon,pluginChartType:f.chartType,minInputs:f.minInputs,maxInputs:f.maxInputs});t==null||t("custom",f),n==null||n()},w=f=>{const M={type:"default",id:f.id,name:f.name};l(M)},E=f=>{const M={type:"custom",id:f.name,url:f.url,icon:f.icon,name:f.name};l(M)};return e.jsxs("div",{className:"flex flex-col",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$1,{placeholder:"Search charts...",value:a,onChange:f=>r(f.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:[B.length>0&&e.jsx("div",{className:"mb-3",children:e.jsx("div",{className:"grid grid-cols-3 gap-2",children:B.map(f=>e.jsx(Ds,{chartType:f.id,chartName:f.name,isCustom:!1,isStarred:c("default",f.id),onSelect:()=>L(f.id),onToggleStar:()=>w(f)},f.id))})}),O.length>0&&e.jsxs(e.Fragment,{children:[B.length>0?e.jsx(s.Separator,{className:"my-3"}):null,e.jsxs("div",{children:[e.jsx("span",{className:"mb-2 block text-xs font-medium text-muted-foreground",children:"Custom Charts"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:O.map((f,M)=>e.jsx(Ds,{chartName:f.name,isCustom:!0,pluginName:f.pluginName,isStarred:c("custom",f.name),onSelect:()=>g(f),onToggleStar:()=>E(f)},`${f.url}-${f.name}-${M}`))})]})]}),o&&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 charts..."})]}),B.length===0&&O.length===0&&!o&&e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No charts found"})]})]})}function Na({selectedChart:t,onChartChange:n}){var g,w,E,f;const a=s.useEditorStore(M=>M.card),r=s.useEditorStore(M=>M.frame),i=s.useEditorStore(M=>M.isDevMode),{replaceFrameCards:c,clearModeDrafts:l,initializeModeDrafts:d,setIsDevMode:o}=s.useEditorActions(),x=I.useMemo(()=>s.findCustomVisualConfigCard(r,a),[r,a]),{manifest:p}=s.useCustomVisual(((g=x==null?void 0:x.customCardPreferences)==null?void 0:g.url)||""),m=I.useMemo(()=>{var M;return(M=p==null?void 0:p.visuals)==null?void 0:M.find(j=>{var k;return j.name===((k=x==null?void 0:x.customCardPreferences)==null?void 0:k.componentName)})},[p,(w=x==null?void 0:x.customCardPreferences)==null?void 0:w.componentName]),u=s.resolveMultiInputType(x,m)==="multiple",N=ye.useEffectiveEditorCardType(),b=u?N:t??a.type,h=(E=a==null?void 0:a.customCardPreferences)==null?void 0:E.componentName,y=(f=x==null?void 0:x.customCardPreferences)==null?void 0:f.componentName,T=u&&!!y,C=I.useMemo(()=>{const M=s.chartTypes.find(j=>j.id===b);return M?M.label:b==="custom"?h||"Custom Visual":"Select chart type"},[b,h]),B=I.useMemo(()=>{const M=s.chartTypes.find(j=>j.id===b);if(M){const j=M.icon;return e.jsx(j,{className:"h-4 w-4"})}if(b==="custom"&&h){const j=s.getAutoDetectedChartIcon(h);return j||e.jsx(s.ChartIcon,{chartName:h,isCustom:!0,className:"h-4 w-4"})}return e.jsx(Wt,{className:"h-4 w-4"})},[b,h]);return{displayChartType:b,displayLabel:C,displayIcon:B,showBadge:T,badgeLabel:y,isMultiInputContext:u,handleChartSelect:M=>{n==null||n(M)},handleClearCustomVisual:M=>{if(M.stopPropagation(),u){const k={...a,sql:"",python:"",config:void 0,queryConfig:void 0,customCfg:void 0,preferences:{}},P=s.useEditorStore.getState().frame.cards.map(v=>v.id===k.id?k:v);c(P),l(),d(k),i&&o(!0);return}const j={...a,type:"bar",sql:"",python:"",config:void 0,queryConfig:void 0,customCfg:void 0,preferences:{},customCardPreferences:void 0,title:"Chart",tabTitle:"Chart",description:void 0,info:void 0};c([j]),l(),d(j),i&&o(!0),n==null||n("bar")}}}function os({selectedChart:t,onChartChange:n,variant:a="ghost",className:r}){const[i,c]=I.useState(!1),{displayLabel:l,displayIcon:d,showBadge:o,badgeLabel:x,handleChartSelect:p,handleClearCustomVisual:m}=Na({selectedChart:t,onChartChange:n});return e.jsxs("div",{className:s.cn("relative w-full",r),children:[e.jsxs(s.Popover,{open:i,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:a,role:"combobox","aria-expanded":i,className:"w-full justify-between gap-2",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[d,e.jsx("span",{className:"truncate",children:l})]}),e.jsx(s.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[360px] p-3",align:"start",onOpenAutoFocus:u=>u.preventDefault(),children:e.jsx(va,{onChartSelect:u=>p(u),onClose:()=>c(!1)})})]}),o&&e.jsxs("div",{className:"absolute right-10 top-1/2 z-10 flex max-w-[140px] -translate-y-1/2 items-center gap-1 rounded-full border bg-background py-0.5 pl-2 pr-1 text-[10px] text-muted-foreground shadow-sm",title:x,children:[e.jsx(s.Layers,{className:"h-2.5 w-2.5 shrink-0"}),e.jsx("span",{className:"truncate",children:x}),e.jsx("button",{onClick:m,className:"rounded-full p-0.5 hover:bg-muted",title:"Clear custom visual",children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]})]})}function Ca(){const t=s.useEditorStore(o=>{var x,p;return(p=(x=o.card.preferences)==null?void 0:x.chartOptions)==null?void 0:p.indexAxis}),n=s.useEditorStore(o=>o.card.type),{setChartOrientation:a,setCardPreferences:r}=s.useEditorStore(o=>o.actions),i=o=>{if(a(o),n!=="bullet")return;const x=o==="y"?"horizontal":"vertical",p=s.useEditorStore.getState().card.preferences,m={...p||{},bulletConfig:{...(p==null?void 0:p.bulletConfig)||{},orientation:x}};r(m)};function c(){const o=t??"x",x=()=>{i(o==="x"?"y":"x")};return e.jsx(s.IconButton,{onClick:x,tooltip:"Chart Orientation",children:o==="x"?e.jsx(Ye,{className:"size-4"}):e.jsx(Je,{className:"size-4"})})}function l(){const o=()=>{i(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(Ye,{className:"size-4"}):e.jsx(Je,{className:"size-4"})})}function d(){const o=t??"y",x=()=>{i(o==="y"?"x":"y")};return e.jsx(s.IconButton,{onClick:x,tooltip:"Chart Orientation",children:o==="y"?e.jsx(Je,{className:"size-4"}):e.jsx(Ye,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?l():n==="bullet"?d():c()})}function Sa({className:t}){var N,b,h,y,T,C,B,O,L,g;const n=s.useEditorStore(w=>w.card),{setCardPreferences:a,updateCardInFrame:r,setCard:i}=s.useEditorActions(),[c,l]=I.useState(!1),d=((b=(N=n.preferences)==null?void 0:N.displayOptions)==null?void 0:b.showFilterInfo)??!0,o=((y=(h=n.preferences)==null?void 0:h.displayOptions)==null?void 0:y.showCardToolbar)??!0,x=((C=(T=n.preferences)==null?void 0:T.displayOptions)==null?void 0:C.showChrome)??!0,p=((O=(B=n.preferences)==null?void 0:B.displayOptions)==null?void 0:O.allowScroll)??!0,m=((g=(L=n.preferences)==null?void 0:L.displayOptions)==null?void 0:g.showInlineFilterBar)??!0,u=(w,E)=>{var j;const f={...n.preferences,displayOptions:{...(j=n.preferences)==null?void 0:j.displayOptions,[w]:E}};a(f);const M={...n,preferences:f};i(M),r(M)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:c,onOpenChange:l,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(Qs,{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:d,onCheckedChange:w=>{u("showFilterInfo",w)},onSelect:w=>w.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:w=>{u("showCardToolbar",w)},onSelect:w=>w.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:x,onCheckedChange:w=>{u("showChrome",w)},onSelect:w=>w.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:p,onCheckedChange:w=>{u("allowScroll",w)},onSelect:w=>w.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:m,onCheckedChange:w=>{u("showInlineFilterBar",w)},onSelect:w=>w.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 wa(){const[t,n]=I.useState(!1),a=s.useEditorStore(m=>m.card),r=s.useEditorStore(m=>m.selectedConnectionId),{setCard:i}=s.useEditorActions(),c=s.useDashboardStore(m=>m.actions.removeCardInlineFilterValue),l=(a==null?void 0:a.inlineFilters)||[];function d(m){var g,w,E,f,M;const u=((E=(w=(g=a==null?void 0:a.dataSource)==null?void 0:g.selectedEntities)==null?void 0:w[0])==null?void 0:E.database)||"",N=m.qualifiedFieldName||m.name;if(l.find(j=>j.column===N))return;const h=m.qualifiedFieldName?m.qualifiedFieldName.split(".").slice(0,-1).join("."):m.qualifiedEntityName||m.entityName,T=s.fmt(m.name),C=s.buildFilterFieldMeta(m),B=s.buildFilterSemanticContext(a==null?void 0:a.dataSource,{connectionId:r||((f=a==null?void 0:a.dataSource)==null?void 0:f.connectionId),connectionType:(M=a==null?void 0:a.dataSource)==null?void 0:M.connectionType}),O=s.isCalculatedFilterField(C),L={id:s.v4(),column:N,title:m.label||m.name,dataType:m.dataType,table:m.entityName||"",database:u,connectionId:r||"",operation:"in",sql:O?"":s.getDefaultFilterSql(m.dataType,h,T),fieldMeta:C,semanticContext:B,width:250};i({...a,inlineFilters:[...l,L]})}function o(m){const u=l.filter(N=>N.id!==m);i({...a,inlineFilters:u}),c(a.id,m)}function x(m,u){const N=l.map(b=>b.id===m?{...b,...u}:b);i({...a,inlineFilters:N})}return["bar","line","pie","doughnut","table","detailTable","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":l.length>0}),children:[e.jsx(Ut,{className:"h-4 w-4"}),l.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:l.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:d,inlineFilters:l})})})}),l.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:l.map(m=>e.jsx(Ta,{filter:m,onUpdate:u=>x(m.id,u),onRemove:()=>o(m.id)},m.id))})]})]})})]})}):null}function Ta({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 rt(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var l,d;return(d=(l=c.card)==null?void 0:l.preferences)==null?void 0:d.chartOptions}),a=s.getChartGridStyle(n),{setChartGrid:r}=s.useEditorActions();function i(){const c=["xy","none","x","y"],d=(c.indexOf(a)+1)%c.length;r(c[d])}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(Ca,{})}),!["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:i,children:[(a==="xy"||!a)&&e.jsx(s.Grid3x3,{className:"size-4"}),a==="x"&&e.jsx(Hs,{className:"size-4"}),a==="y"&&e.jsx(rs,{className:"size-4"}),a==="none"&&e.jsx(s.Square,{className:"size-4"})]}),e.jsx(wa,{}),e.jsx(Sa,{})]})}function Ea({isPreviewMode:t,onPreviewToggle:n,configCard:a}){var P,v,A,S,R;const r=s.useEditorStore(F=>F.frame),i=s.useEditorStore(F=>F.card),{setFrame:c,setActiveTabCardId:l,setCard:d,updateCardInFrame:o,clearModeDrafts:x,initializeModeDrafts:p}=s.useEditorActions(),{manifest:m}=s.useCustomVisual(((P=a==null?void 0:a.customCardPreferences)==null?void 0:P.url)||""),u=(v=m==null?void 0:m.visuals)==null?void 0:v.find(F=>{var z;return F.name===((z=a==null?void 0:a.customCardPreferences)==null?void 0:z.componentName)}),b=s.resolveMultiInputType(a,u)==="multiple",h=(u==null?void 0:u.minInputs)??((A=a==null?void 0:a.customCardPreferences)==null?void 0:A.minInputs)??1,y=(u==null?void 0:u.maxInputs)??((S=a==null?void 0:a.customCardPreferences)==null?void 0:S.maxInputs),T=I.useMemo(()=>s.getCustomVisualInputCards({frame:r,configCard:a,isMultiInputVisual:b}),[r,a,b]),C=b?T.filter(Boolean).length:r.cards.length,B=y?C<y:!0,O=C>Math.max(h||1,1),L=!!((R=a==null?void 0:a.customCardPreferences)!=null&&R.dataInputCardIds),g=(F,z)=>{F.dataTransfer.setData("tabIndex",z.toString())},w=F=>{F.preventDefault()},E=(F,z)=>{const G=F.dataTransfer.getData("tabIndex");if(G===z.toString())return;const V=Array.from(r.cards),[U]=V.splice(parseInt(G),1);V.splice(z,0,U),c({...r,cards:V})};function f(F){const z=(a==null?void 0:a.id)===F;if(!(L&&z?r.cards.length>1:O))return;let V=r.cards.filter(Z=>Z.id!==F);b&&!L&&(V=s.reindexSlotCards(V));const U=V[0],Q={...r,cards:V,activeCardId:U.id},J=F===i.id;J&&x(),c(Q),l(U.id),d(U),J&&p(U)}function M(F,z){if(!B)return;const G={...r,cards:[...r.cards,z],activeCardId:F.id};c(G),l(z.id)}function j(){if(b&&(a==null?void 0:a.id)===i.id){k(i);return}const F={...i,id:s.v4(),title:`${i.title} Copy`,tabTitle:`${i.tabTitle||i.title} Copy`,customCardPreferences:i.customCardPreferences?{...i.customCardPreferences,slotIndex:b?Math.max(-1,...T.map((z,G)=>s.getSlotIndexForCard(z,G)))+1:i.customCardPreferences.slotIndex}:void 0};M(i,F)}function k(F){var J;if(!B)return;let z=b?"table":"bar",G="Title",V="";const U=b?Math.max(-1,...T.map((Z,q)=>s.getSlotIndexForCard(Z,q)))+1:C;if(b&&((J=u==null?void 0:u.slots)!=null&&J.length)){const Z=s.getSlotDefinitionForIndex(u.slots,U);Z&&(z=s.getSlotExpectedChartType(Z),G=Z.label||`Tab ${U+1}`,V=Z.description||"")}const Q={dataSource:F.dataSource,connectionId:F.connectionId,lastSelectedDatabase:F.lastSelectedDatabase,lastSelectedSchema:F.lastSelectedSchema,lastSelectedTable:F.lastSelectedTable,lastSelectedDatamodelId:F.lastSelectedDatamodelId,id:s.v4(),title:G,tabTitle:G,description:V,preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:z,sql:"",data:[],mode:"explorer",...b&&{customCardPreferences:{slotIndex:U}}};M(F,Q)}function D(F,z){return F.cards.length===1&&(z.displayTab===!0||z.displayTab===void 0)||F.activeCardId!==z.id&&(z.displayTab===!0||z.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const G=z.displayTab===void 0?!1:!z.displayTab;d({...z,displayTab:G}),o({...z,displayTab:G})},children:z.displayTab===!0||z.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(s.EyeOff,{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:[r.cards.map((F,z)=>{var J,Z;const G=b?s.getSlotIndexForCard(F,z):-1,V=b&&((J=u==null?void 0:u.slots)!=null&&J.length)&&G>=0?s.getSlotDefinitionForIndex(u.slots,G):null,U=V?(Array.isArray(V.expectedType)?V.expectedType[0]:V.expectedType)||"table":F.type,Q=b&&((Z=u==null?void 0:u.slots)==null?void 0:Z.length)&&u.slots.every(q=>typeof q.position=="number"||typeof q.position=="string"&&!q.position.includes("+"));return e.jsxs(s.TabsTrigger,{draggable:!b,onDragStart:b?void 0:q=>g(q,z),onDragOver:b?void 0:w,onDrop:b?void 0:q=>E(q,z),className:"",value:F.id,children:[b&&V?e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:s.getChartIconByType(U,"size-3.5")}),e.jsx("span",{children:V.label||`Tab ${G+1}`})]})}),e.jsx(s.TooltipContent,{side:"bottom",className:"w-64 p-3 text-left",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium",children:V.label}),V.description&&e.jsx("p",{className:"whitespace-normal break-words text-xs text-muted-foreground",children:V.description}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[V.expectedType&&e.jsx("span",{className:"inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground",children:Array.isArray(V.expectedType)?V.expectedType.join(" / "):V.expectedType}),V.required&&e.jsx("span",{className:"inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground",children:"Required"})]})]})})]})}):e.jsxs(e.Fragment,{children:[D(r,F),e.jsx(s.Editable,{enabled:r.activeCardId===F.id,text:F.tabTitle||F.title,onSave:q=>{d({...i,tabTitle:q}),o({...i,tabTitle:q})},children:F.tabTitle||F.title},F.id)]}),r.activeCardId===F.id&&!Q&&e.jsx(s.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:q=>{q.stopPropagation(),j()}}),r.activeCardId===F.id&&(L&&(a==null?void 0:a.id)===F.id?r.cards.length>1:O)&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>f(F.id)})]},F.id)}),e.jsx(s.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>k(i),disabled:!B,children:e.jsx(s.Plus,{className:"h-4 w-4"})}),b&&e.jsxs(s.Toggle,{pressed:t,onPressedChange:n,size:"sm",className:"ml-2 h-8 gap-1 px-2 data-[state=on]:bg-background data-[state=on]:text-foreground","aria-label":"Toggle preview",children:[t?e.jsx(s.EyeOff,{className:"h-4 w-4"}):e.jsx(s.Eye,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Preview"})]})]})})}function ns(){var ge,je,ve,Ne,Ie;const t=s.useEditorStore(X=>X.frame),n=s.useEditorStore(X=>X.card),[a,r]=I.useState(!1),i=I.useMemo(()=>s.findCustomVisualConfigCard(t,n),[t,n]),c=s.useEditorStore(X=>X.isSqlRunning);s.useEditorStore(X=>X.isDevMode);const{setFrame:l,setActiveTabCardId:d,setCard:o,setRunSql:x,mergeDraftsIntoCard:p,clearModeDrafts:m,initializeModeDrafts:u}=s.useEditorActions(),[N,b]=I.useState({}),[h,y]=I.useState(()=>new Set),{theme:T}=s.useTheme(),C=s.useDashboardStore(X=>X.themeStyle),{authToken:B}=s.useSemaphorContext(),O=s.getTokenParams(B==null?void 0:B.accessToken),L={mode:T||"system",colors:((je=(ge=C==null?void 0:C.chart)==null?void 0:ge.dataset)==null?void 0:je.backgroundColor)||[]},{getCard:g,manifest:w,isLoading:E}=s.useCustomVisual(((ve=i==null?void 0:i.customCardPreferences)==null?void 0:ve.url)||""),f=(Ne=i==null?void 0:i.customCardPreferences)==null?void 0:Ne.componentName,M=f?g(f):null,j=(Ie=w==null?void 0:w.visuals)==null?void 0:Ie.find(X=>X.name===f),k=s.resolveMultiInputType(i,j),D=a&&k==="multiple"&&!!i,P=I.useMemo(()=>s.getCustomVisualInputCards({frame:t,configCard:i,isMultiInputVisual:!0}).map(oe=>(oe==null?void 0:oe.id)===n.id?n:oe),[t,i,n]),v=I.useMemo(()=>s.buildSlotOrderedCards(P),[P]),A=I.useMemo(()=>{const X=P.findIndex(oe=>(oe==null?void 0:oe.id)===n.id);return X<0?-1:s.getSlotIndexForCard(n,X)},[P,n]),S=I.useMemo(()=>!i||k!=="multiple"||A<0?n.type:s.getEffectiveCardTypeForSlot(n,A,j==null?void 0:j.slots)??n.type,[i,k,A,n,j==null?void 0:j.slots]),R=I.useMemo(()=>D?{...n,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:S!==n.type?{...n,type:S}:n,[n,S,D]),{data:F,isLoading:z,isFetching:G,isError:V}=s.useDashboardCardQuery(R),U=I.useCallback((X,oe)=>{const ue=s.normalizeMultiInputPayload(oe);b(xe=>({...xe,[X]:ue}))},[]),Q=I.useCallback((X,oe)=>{y(ue=>{const xe=new Set(ue);return oe?xe.add(X):xe.delete(X),xe})},[]),J=h.size>0,Z=s.useInteractionStore(X=>X.interactionStates),q=s.useDashboardStore(X=>{var oe;return(oe=X.dashboard)==null?void 0:oe.id}),Y=s.useDashboardStore(X=>X.dashboard.filters),se=s.useDashboardStore(X=>X.filterValues),ne=s.useDashboardStore(X=>X.selectedSheetId),_=s.useDashboardStore(X=>X.inlineFilterValuesMap[(i==null?void 0:i.id)||""]),W=I.useMemo(()=>i?s.buildInlineFilterNodes({card:i,sheetId:ne||"",inlineFilterValues:_}):[],[i,ne,_]),{cardFilters:le,cardFilterValues:he}=I.useMemo(()=>i?s.calculateContextAwareFilters({card:i,interactionStates:Z,currentDashboardId:q,filters:Y,filterValues:se,selectedSheetId:ne}):{cardFilters:[],cardFilterValues:[]},[i,Z,q,Y,se,ne]);function $(X){const oe=t.cards.find(ue=>ue.id===X);oe&&(p(),H(X),d(X),m(),u(oe))}function H(X){const oe=s.useEditorStore.getState().card,ue=s.useEditorStore.getState().frame,xe={...ue,cards:ue.cards.map(Ce=>Ce.id===oe.id?oe:Ce),activeCardId:X};l(xe);const we=xe.cards.find(Ce=>Ce.id===X);we.sql&&x(!0),o(we)}function ae(){if(E)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading manifest"})});if(!M)return e.jsx("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"Select a component to preview the multi-input visual."});const oe=v.map((ue,xe)=>s.getEffectiveCardTypeForSlot(ue,xe,j==null?void 0:j.slots));return e.jsxs("div",{className:"relative flex h-full flex-col px-6",children:[P.map((ue,xe)=>{if(!ue)return null;const we=s.getSlotIndexForCard(ue,xe),Ce=s.getEffectiveCardTypeForSlot(ue,we,j==null?void 0:j.slots);return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:Q,onDataChange:U,card:ue,effectiveCardType:Ce},`${ue.id}-${we}`)}),J&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading preview"})}),e.jsx("div",{className:s.cn("flex h-full min-h-0 flex-1 flex-col gap-2",J&&"opacity-50"),children:e.jsx(I.Suspense,{fallback:e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted"})}),children:e.jsx(M,{editing:!0,...s.buildMultiInputCustomVisualProps({configCard:i,slotOrderedCards:v,slotTypes:oe,multiInputData:N,params:O,theme:L,filters:le,filterValues:[...he||[],..._||[]],inlineFilters:W})})})})]})}function ie(){var X;return D?ae():n.type==="kpi"?z||G?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.jsxs("div",{className:"w-1/2 space-y-3",children:[e.jsx("div",{className:"rounded-md border border-border",children:e.jsx(s.KPICard,{card:n,data:F==null?void 0:F.records,isPending:z||G,isError:V,comparisonMetadata:(X=F==null?void 0:F.metadata)==null?void 0:X.comparisonMetadata})}),s.isCardSummaryVisibleOnCard(n)&&e.jsx(s.CardSummary,{card:n,mode:"editor"})]})}):n.type==="text"?z||G?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:c,card:n,data:F==null?void 0:F.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(nt,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:$,value:t.activeCardId,className:"flex grow flex-col gap-2",children:[D?e.jsx("div",{className:"mt-0 grow",children:ie()}):t.cards.map(X=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:X.id,children:ie()},X.id)),e.jsx(Ea,{isPreviewMode:D,onPreviewToggle:r,configCard:i})]})}function Ms({children:t}){var R;const n=s.useEditorStore(F=>F.frame),a=s.useEditorStore(F=>F.card),r=s.useEditorStore(F=>F.isDevMode),i=s.useEditorStore(F=>F.isShowingVisual),c=s.useDashboardStore(F=>F.isVisualEditing),l=s.useEditorStore(F=>F.pythonStdOut),d=s.useEditorStore(F=>F.actions.setRunSql),o=ye.useEffectiveEditorCardType(),{setFrame:x,setCard:p,setActiveTabCardId:m,runAssistant:u,setCardPreferences:N,mergeDraftsIntoCard:b,clearModeDrafts:h,initializeModeDrafts:y}=s.useEditorActions(),T=I.useMemo(()=>o!==a.type?{...a,type:o}:a,[a,o]),{data:C,isLoading:B,isFetching:O,errorMessage:L,errorSql:g,refetch:w,pagination:E}=s.useDashboardCardQuery(T),{handleDebugWithAssistant:f}=at(L,g),M=I.useMemo(()=>(C==null?void 0:C.records)||[],[C==null?void 0:C.records]),[j,k]=I.useState(!1);I.useEffect(()=>{O||k(!1)},[O]);function D(F,z){var U,Q;const G={...a,paginationConfig:{page:F+1,pageSize:z}};p(G);const V={...n,cards:n.cards.map(J=>J.id===a.id?G:J)};x(V),a.sql&&((Q=(U=a.preferences)==null?void 0:U.tablePrefs)!=null&&Q.enableDevModePagination)&&d(!0)}function P(F){var U,Q,J,Z,q;const z=s.sortStateToSortByColumns(F,(U=a.config)==null?void 0:U.metricColumns,(Q=a.config)==null?void 0:Q.groupByColumns,(J=a.config)==null?void 0:J.detailColumns),G={...a,config:{...a.config||{},sortByColumns:z}};p(G);const V={...n,cards:n.cards.map(Y=>Y.id===a.id?G:Y)};x(V),a.sql&&((q=(Z=a.preferences)==null?void 0:Z.tablePrefs)!=null&&q.enableDevModePagination)&&d(!0)}function v(){const F=JSON.stringify(C==null?void 0:C.records,null,2),z=new Blob([F],{type:"application/json"}),G=URL.createObjectURL(z),V=document.createElement("a");V.href=G,V.download=`${a.title}.json`,V.click()}function A(){const z=[Object.keys(C==null?void 0:C.records.reduce((Q,J)=>({...Q,...J}),{})).join(","),...((C==null?void 0:C.records)||[]).map(Q=>Object.values(Q).join(","))].join(`
178
+ `),G=new Blob([z],{type:"text/csv"}),V=URL.createObjectURL(G),U=document.createElement("a");U.href=V,U.download=`${a.title}.csv`,U.click()}function S(){const F=`Can you get the documentation for ${a.type} chart?`;u(F)}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:[i&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx("div",{className:"w-[260px]",children:e.jsx(os,{variant:"outline"})}),c&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:S,children:e.jsx(Rt,{className:"size-4"})}),!["table","detailTable","custom"].includes(a.type)&&c&&e.jsx(ba,{})]}),!i&&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:A,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:v,children:e.jsx(Pt,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(C==null?void 0:C.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:B||O,onClick:()=>{k(!0),w()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":j})})}),e.jsx(rt,{})]}),r&&e.jsx(ka,{})]}),i?e.jsx(ns,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[l&&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:l&&e.jsx(Ia,{})}),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":l}),children:[(C==null?void 0:C.records)&&(C==null?void 0:C.records.length)>0&&e.jsx(s.TableVisual,{card:a,data:M,comparisonMetadata:(R=C==null?void 0:C.metadata)==null?void 0:R.comparisonMetadata,paginationMetadata:E,onPaginationChange:D,onSortChange:P,isLoading:B||O}),L&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ls,{error:L,errorSql:g||a.sql||a.python,onDebugWithAssistant:f,showFeedbackButton:!1})})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function Ia(){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 ka(){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 Se({value:t,onCommit:n,type:a="text",placeholder:r,className:i}){const[c,l]=I.useState(t),d=I.useRef(!1);I.useEffect(()=>{l(t)},[t]);const o=()=>{if(d.current){d.current=!1;return}c!==t&&n(c)},x=p=>{if(p.key==="Enter"){p.currentTarget.blur();return}p.key==="Escape"&&(d.current=!0,l(t),p.currentTarget.blur())};return e.jsx(s.Input,{type:a,placeholder:r,value:c,onChange:p=>l(p.target.value),onBlur:o,onKeyDown:x,className:i})}function De({defaultValue:t,label:n,options:a,value:r,onValueChange:i,className:c,icon:l,showPlaceholderLabel:d=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:i,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",c),children:e.jsxs("div",{className:"flex items-center gap-2",children:[l&&e.jsx("span",{children:l}),d&&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))]})})]})}function Aa(t,n){return s.getSlotDefinitionForIndex(t,n)||null}function Be(t){if(typeof t=="number")return`Tab ${t+1}`;const n=t.match(/^(\d+)-(\d+)$/);if(n){const[,r,i]=n;return`Tabs ${Number(r)+1}-${Number(i)+1}`}const a=t.match(/^(\d+)\+$/);return a?`Tabs ${Number(a[1])+1}+`:`Tab ${t}`}function Da(t){return t?Array.isArray(t)?t:[t]:[]}function We(t){var r,i;if(!t)return!1;if(t.type==="text")return!!((r=t.description)!=null&&r.trim());const n=!!((i=t.sql)!=null&&i.trim()),a=s.hasValidCardConfig(t.config);return n||a}function La({slots:t,cards:n,minInputs:a}){const r=[],i=n.filter(Boolean).length;return a&&i<a&&r.push({type:"too-few-inputs",message:`This visual requires at least ${a} tab${a===1?"":"s"}.`}),!t||t.length===0||(t.forEach(c=>{if(!c.required)return;if(typeof c.position=="number"){const o=n[c.position];We(o)||r.push({type:"missing-required",message:`${Be(c.position)} ("${c.label}") is required but has no data configured.`});return}const l=c.position.match(/^(\d+)-(\d+)$/);if(l){const[,o,x]=l.map(Number);for(let p=o;p<=x;p+=1){const m=n[p];if(!We(m)){r.push({type:"missing-required",message:`${Be(p)} ("${c.label}") is required but has no data configured.`});break}}return}const d=c.position.match(/^(\d+)\+$/);if(d){const o=Number(d[1]);if(n.length<=o){r.push({type:"missing-required",message:`${Be(o)} ("${c.label}") is required but has no data configured.`});return}for(let x=o;x<n.length;x+=1){const p=n[x];if(!We(p)){r.push({type:"missing-required",message:`${Be(x)} ("${c.label}") is required but has no data configured.`});break}}}}),n.forEach((c,l)=>{if(!c)return;const d=Aa(t,l);if(!d||!d.expectedType)return;const o=Da(d.expectedType);o.length!==0&&(o.includes(c.type)||r.push({type:"wrong-type",message:`${Be(l)} ("${d.label}") expects ${o.join(", ")}, but is configured as ${c.type}.`}))})),r}const Ma={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 lt(){var k,D,P;const t=s.useEditorStore(v=>v.card.customCardPreferences),{data:n}=s.usePluginQuery(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(v=>v.card),i=s.useEditorStore(v=>v.frame),{setCustomCardPreferences:c}=s.useEditorActions(),l=I.useMemo(()=>s.findCustomVisualConfigCard(i,r),[i,r]),d=l==null?void 0:l.customCardPreferences,{components:o,manifest:x}=s.useCustomVisual((d==null?void 0:d.url)||(t==null?void 0:t.url)||""),p=(k=x==null?void 0:x.visuals)==null?void 0:k.find(v=>v.name===((d==null?void 0:d.componentName)||(t==null?void 0:t.componentName))),u=s.resolveMultiInputType(l||r,p)==="multiple",N=!!l&&l.id===r.id,b=(p==null?void 0:p.minInputs)??((D=l==null?void 0:l.customCardPreferences)==null?void 0:D.minInputs),h=(p==null?void 0:p.maxInputs)??((P=l==null?void 0:l.customCardPreferences)==null?void 0:P.maxInputs),y=I.useMemo(()=>s.getCustomVisualInputCards({frame:i,configCard:l||r,isMultiInputVisual:u}),[i,l,r,u]),T=I.useMemo(()=>s.buildSlotOrderedCards(y),[y]),C=I.useMemo(()=>T.map((v,A)=>{if(!v)return null;const S=s.getSlotIndexForCard(v,A),R=s.getEffectiveCardTypeForSlot(v,S,p==null?void 0:p.slots);return{...v,type:R??v.type}}),[T,p==null?void 0:p.slots]),B=I.useMemo(()=>La({slots:p==null?void 0:p.slots,cards:C,minInputs:b}),[p==null?void 0:p.slots,C,b]),O=I.useMemo(()=>{const v=y.findIndex(A=>(A==null?void 0:A.id)===r.id);return v<0?-1:s.getSlotIndexForCard(r,v)},[y,r]);function L(v){if(typeof v=="number")return`Tab ${v+1}`;const A=v.match(/^(\d+)-(\d+)$/);if(A){const[,R,F]=A;return`Tabs ${Number(R)+1}-${Number(F)+1}`}const S=v.match(/^(\d+)\+$/);return S?`Tabs ${Number(S[1])+1}+`:`Tab ${v}`}function g(v){return v?(Array.isArray(v)?v:[v]).join(", "):null}function w(v,A,S=[],R="",F,z,G){const V=E({key:A,defaultValue:R,settingsValue:z,sourceCard:G});return v==="input"?e.jsx(Se,{className:`h-8 w-full ${s.removeRing}`,value:String(V??""),onCommit:U=>{f({key:A,value:U,settingsField:F,settingsValue:z,sourceCard:G})}},A):v==="select"?e.jsx(De,{className:"h-8 w-full",label:"",options:S,value:String(V!==void 0?V:R??""),onValueChange:U=>{f({key:A,value:U,settingsField:F,settingsValue:z,sourceCard:G})}}):null}function E({key:v,defaultValue:A,settingsValue:S,sourceCard:R}){const F=S==null?void 0:S[v];return F!==void 0?F:v==="title"&&(R==null?void 0:R.title)!==void 0?R.title:v==="description"&&(R==null?void 0:R.description)!==void 0?R.description:A}function f({key:v,value:A,settingsField:S,settingsValue:R,sourceCard:F}){const z={...R||{}},G=v==="title"&&(F==null?void 0:F.title)!==void 0,V=v==="description"&&(F==null?void 0:F.description)!==void 0;G&&A===String((F==null?void 0:F.title)??"")||V&&A===String((F==null?void 0:F.description)??"")?delete z[v]:z[v]=A,c({...t||{},[S]:z})}function M({settingsSchema:v,settingsField:A,settingsValue:S,sourceCard:R,headerLabel:F}){const z=Object.entries(v||{});return e.jsxs("div",{className:"space-y-3",children:[F&&e.jsx(s.Label,{children:F}),z.map(([G,V])=>{var U;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:V.title}),((U=V.docs)==null?void 0:U.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:V.docs.description})})]})})]}),w(V.ui,G,V.options,V.defaultValue,A,S,R)]},G)})]})}function j(){return e.jsxs(e.Fragment,{children:[u&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Slot Guide"}),e.jsx("div",{className:"space-y-3 rounded-md border border-border bg-muted/40 px-3 py-2 text-xs",children:p!=null&&p.slots&&p.slots.length>0?e.jsx("div",{className:"space-y-3",children:p.slots.map((v,A)=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-foreground",children:[e.jsx("span",{className:"font-medium",children:L(v.position)}),e.jsx("span",{className:"text-muted-foreground",children:"•"}),e.jsx("span",{className:"font-medium",children:v.label})]}),v.description&&e.jsx("p",{className:"text-muted-foreground",children:v.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-muted-foreground",children:[g(v.expectedType)&&e.jsxs("span",{children:["Expected: ",g(v.expectedType)]}),v.required&&e.jsx("span",{children:"Required"})]})]},`${v.label}-${A}`))}):e.jsxs("div",{className:"space-y-1 text-muted-foreground",children:[e.jsx("p",{children:"This visual renders all tabs in a flexible layout. Add as many tabs as needed."}),(b||h)&&e.jsxs("p",{children:[b?`Min ${b} tabs`:"",b&&h?" • ":"",h?`Max ${h} tabs`:""]})]})})]}),u&&B.length>0&&e.jsx(s.Alert,{className:"border-yellow-500/40 bg-yellow-500/10 text-yellow-900 dark:text-yellow-100",children:e.jsx(s.AlertDescription,{children:e.jsx("ul",{className:"list-disc space-y-1 pl-4 text-xs",children:B.map((v,A)=>e.jsx("li",{children:v.message},`${v.type}-${A}`))})})}),p&&!u&&p.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:M({settingsSchema:p.settings,settingsField:"settings",settingsValue:t==null?void 0:t.settings,sourceCard:r})})}),p&&u&&(p.settings||p.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[N&&p.settings&&e.jsx("div",{className:"px-2",children:M({settingsSchema:p.settings,settingsField:"settings",settingsValue:t==null?void 0:t.settings,sourceCard:l||r,headerLabel:"Global Settings"})}),p.slotSettings&&e.jsx("div",{className:"px-2",children:M({settingsSchema:p.slotSettings,settingsField:"slotSettings",settingsValue:t==null?void 0:t.slotSettings,sourceCard:r,headerLabel:(()=>{const v=r.tabTitle||r.title,A=O>=0?O:0,S=N?"Slot 0":`Slot ${A}`;return v?`${S}: ${v} Settings`:`${S} Settings`})()})})]})]})}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:[(!u||N)&&e.jsx(De,{icon:e.jsx(_s,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(d==null?void 0:d.url)||"",onValueChange:v=>c({...t||{url:"",componentName:""},url:v})}),u&&!N&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Switch to the config tab to change the plugin or component."})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&(!u||N)&&e.jsx(e.Fragment,{children:o&&e.jsx(De,{icon:e.jsx(Bt,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(o==null?void 0:o.map(v=>({value:v.name,label:v.name})))||[],value:t.componentName||"",onValueChange:v=>{var R;const A=(R=x==null?void 0:x.visuals)==null?void 0:R.find(F=>F.name===v),S=o==null?void 0:o.find(F=>F.name===v);c({...t,componentName:v,visualType:(A==null?void 0:A.visualType)||(S==null?void 0:S.type)||"single",minInputs:A==null?void 0:A.minInputs,maxInputs:A==null?void 0:A.maxInputs,pluginChartType:A==null?void 0:A.chartType})}})})]})})]}),((d==null?void 0:d.componentName)||(t==null?void 0:t.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:(p==null?void 0:p.name)||"Settings"}),(p==null?void 0:p.docs)&&e.jsxs(s.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,onClick:v=>v.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:[p.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:p.docs.description}),p.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:Ma,children:p.docs.dataSchema})})]}),(()=>{var A;const v=(A=p.docs)==null?void 0:A.useCases;return!v||v.length===0?null: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:v.map((S,R)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:S})]},R))})]})})()]})})]})]})}),e.jsx(s.AccordionContent,{children:j()})]})]})}function Oa({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(l,d,o){const x=[...t];x[l]={...x[l],[d]:o},n(x)}function i(l){const d=[...t];d.splice(l,1),n(d)}function c(){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:c,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((l,d)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:o=>r(d,"start",o.target.value),value:l.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:l.end,onChange:o=>r(d,"end",o.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:o=>r(d,"color",o.target.value),value:l.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:()=>i(d),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},d))]})}function Fa(){var p,m,u,N,b;const t=s.useEditorStore(h=>h.card.preferences),n=s.useEditorStore(h=>h.actions.setCardPreferences),a=s.useEditorStore(h=>h.card),r=s.hasValidCardConfig(a.config),i=s.useEditorStore(h=>h.actions.setNumberFormat);s.useEditorStore(h=>{var y,T;return(T=(y=h.card.preferences)==null?void 0:y.formatNumber)==null?void 0:T.decimalPlaces});const c=s.useEditorStore(h=>{var y,T;return(T=(y=h.card.preferences)==null?void 0:y.formatNumber)==null?void 0:T.locale}),l=s.useEditorStore(h=>{var y,T;return(T=(y=h.card.preferences)==null?void 0:y.formatNumber)==null?void 0:T.currency});s.useEditorStore(h=>h.actions.setFilterOnClickField);const d=s.useEditorStore(h=>{var y,T;return(T=(y=h.card.preferences)==null?void 0:y.formatNumber)==null?void 0:T.colorRanges})||[],o=s.useEditorStore(h=>h.actions.setColorRanges),x=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(h=>h.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((p=t==null?void 0:t.formatNumber)!=null&&p.enabled),onCheckedChange:h=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:h}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((m=t==null?void 0:t.formatNumber)==null?void 0:m.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:c||"none",onValueChange:h=>{var y,T,C;return i(((y=t==null?void 0:t.formatNumber)==null?void 0:y.decimalPlaces)||0,((T=t==null?void 0:t.formatNumber)==null?void 0:T.currency)||"",h,((C=t==null?void 0:t.formatNumber)==null?void 0:C.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(h=>e.jsx(s.SelectItem,{value:h.locale,children:h.locale},h.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:l||"none",onValueChange:h=>{var y,T,C;console.log("currency",h),i(((y=t==null?void 0:t.formatNumber)==null?void 0:y.decimalPlaces)||0,h==="none"?"":h,((T=t==null?void 0:t.formatNumber)==null?void 0:T.locale)||"",((C=t==null?void 0:t.formatNumber)==null?void 0:C.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"),x.map(h=>e.jsx(s.SelectItem,{value:h,children:h},h))]})})]})]})]}),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:((N=(u=t==null?void 0:t.formatNumber)==null?void 0:u.decimalPlaces)==null?void 0:N.toString())||"0",onValueChange:h=>{var y,T,C;return i(Number(h),((y=t==null?void 0:t.formatNumber)==null?void 0:y.currency)||"",((T=t==null?void 0:t.formatNumber)==null?void 0:T.locale)||"",((C=t==null?void 0:t.formatNumber)==null?void 0:C.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(h=>e.jsx(s.SelectItem,{value:h,children:h},h))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((b=t==null?void 0:t.formatNumber)==null?void 0:b.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:h=>{var y,T,C;return i(((y=t==null?void 0:t.formatNumber)==null?void 0:y.decimalPlaces)||0,((T=t==null?void 0:t.formatNumber)==null?void 0:T.currency)||"",((C=t==null?void 0:t.formatNumber)==null?void 0:C.locale)||"",h.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(Oa,{colorRanges:d,setColorRanges:o})]})]})}const Ra={combo:{label:"Combo Chart",query:"SELECT x-axis, metric-1, metric-2, ... FROM table",fields:[{name:"x-axis",type:"category",description:"dimension"},{name:"metric-1, metric-2",type:"number",description:"can be bar, line, or area"}],description:"Combo charts allow mixing bar and line series with optional dual Y-axis for metrics with different scales.",docsUrl:"https://docs.semaphor.cloud/docs/charts/combo"},area:{label:"Area Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date, city"},{name:"Y-axis",type:"number",description:"e.g., sales, population"}],description:"Area charts display quantitative data with filled areas under the line.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bar-line-area"},stackedArea:{label:"Stacked Area Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date, city"},{name:"Y-axis",type:"number",description:"e.g., sales, population"}],description:"Stacked area charts show how multiple series contribute to a total over time.",docsUrl:"https://docs.semaphor.cloud/docs/charts/stacked"},bar:{label:"Bar Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., city, product"},{name:"Y-axis",type:"number",description:"e.g., sales, count"}],description:"Bar charts compare values across categories using horizontal or vertical bars.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bar-line-area"},line:{label:"Line Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date, month"},{name:"Y-axis",type:"number",description:"e.g., revenue, count"}],description:"Line charts show trends over time or continuous data.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bar-line-area"},stackedBar:{label:"Stacked Bar Chart",query:"SELECT x-axis, stack-by, y-axis FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., month"},{name:"Stack-by",type:"category",description:"e.g., product type"},{name:"Y-axis",type:"number",description:"e.g., sales"}],description:"Stacked bar charts show how parts contribute to a whole across categories.",docsUrl:"https://docs.semaphor.cloud/docs/charts/stacked"},stackedLine:{label:"Stacked Line Chart",query:"SELECT x-axis, stack-by, y-axis FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date"},{name:"Stack-by",type:"category",description:"e.g., region"},{name:"Y-axis",type:"number",description:"e.g., revenue"}],description:"Stacked line charts show cumulative trends over time.",docsUrl:"https://docs.semaphor.cloud/docs/charts/stacked"},pie:{label:"Pie Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., product, region"},{name:"Measure",type:"number",description:"e.g., sales, count"}],description:"Pie charts show proportions of a whole.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},doughnut:{label:"Doughnut Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., product, region"},{name:"Measure",type:"number",description:"e.g., sales, count"}],description:"Doughnut charts show proportions with a hollow center.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},polarArea:{label:"Polar Area Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., skill, metric"},{name:"Measure",type:"number",description:"e.g., score, value"}],description:"Polar area charts compare values using sectors of equal angle but varying radius.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},radar:{label:"Radar Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., attribute, skill"},{name:"Measure",type:"number",description:"e.g., score, rating"}],description:"Radar charts display multivariate data on axes starting from the same point.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},funnel:{label:"Funnel Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., stage name"},{name:"Measure",type:"number",description:"e.g., count, value"}],description:"Funnel charts visualize progressive reduction of data through stages.",docsUrl:"https://docs.semaphor.cloud/docs/charts/funnel"},bubble:{label:"Bubble Chart",query:"SELECT label, [group], x-axis, y-axis, radius FROM table",fields:[{name:"Label",type:"category",description:"e.g., city"},{name:"Group",type:"category",description:"e.g., region",optional:!0},{name:"X-axis",type:"number",description:"e.g., population"},{name:"Y-axis",type:"number",description:"e.g., income"},{name:"Radius",type:"number",description:"e.g., area"}],description:"Bubble charts display three dimensions of data using position and size.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bubble"},scatter:{label:"Scatter Chart",query:"SELECT label, [group], x-axis, y-axis FROM table",fields:[{name:"Label",type:"category",description:"e.g., item name"},{name:"Group",type:"category",description:"e.g., type",optional:!0},{name:"X-axis",type:"number",description:"e.g., price"},{name:"Y-axis",type:"number",description:"e.g., quantity"}],description:"Scatter charts show relationships between two numeric variables.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bubble"},tornado:{label:"Tornado Chart",query:"SELECT dimension, cohort, metric FROM table",fields:[{name:"Dimension",type:"category",description:"e.g., age group"},{name:"Cohort",type:"category",description:"e.g., gender"},{name:"Metric",type:"number",description:"e.g., population"}],description:"Tornado charts compare two groups across categories using back-to-back bars.",docsUrl:"https://docs.semaphor.cloud/docs/charts/tornado"},pyramid:{label:"Pyramid Chart",query:"SELECT dimension, cohort, metric FROM table",fields:[{name:"Dimension",type:"category",description:"e.g., age group"},{name:"Cohort",type:"category",description:"e.g., gender"},{name:"Metric",type:"number",description:"e.g., population"}],description:"Population pyramids show age and gender distribution.",docsUrl:"https://docs.semaphor.cloud/docs/charts/tornado"},range:{label:"Range Chart",query:"SELECT y-axis, label, range-from, range-to, range-value FROM table",fields:[{name:"Y-axis",type:"category",description:"e.g., category"},{name:"Label",type:"category",description:"e.g., range name"},{name:"Range-from",type:"number",description:"start value"},{name:"Range-to",type:"number",description:"end value"},{name:"Range-value",type:"number",description:"e.g., midpoint"}],description:"Range charts display data ranges with start and end values.",docsUrl:"https://docs.semaphor.cloud/docs/charts/range"},heatmap:{label:"Heatmap",query:"SELECT x-axis, y-axis, value FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., day"},{name:"Y-axis",type:"category",description:"e.g., hour"},{name:"Value",type:"number",description:"e.g., count, intensity"}],description:"Heatmaps visualize data density using color intensity.",docsUrl:"https://docs.semaphor.cloud/docs/charts/heatmap"},bullet:{label:"Bullet Chart",query:"SELECT label, actual, target, [ranges] FROM table",fields:[{name:"Label",type:"category",description:"e.g., metric name"},{name:"Actual",type:"number",description:"current value"},{name:"Target",type:"number",description:"goal value"},{name:"Ranges",type:"number",description:"threshold values",optional:!0}],description:"Bullet charts compare actual performance against targets.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bullet"},text:{label:"Text Visual",query:"SELECT text FROM table LIMIT 1",fields:[{name:"Text",type:"string",description:"content to display"}],description:"Text visuals display dynamic text content from your data.",docsUrl:"https://docs.semaphor.cloud/docs/charts/text"},kpi:{label:"KPI",query:"SELECT current, previous FROM table",fields:[{name:"Current",type:"number",description:"current value"},{name:"Previous",type:"number",description:"comparison value"}],description:"KPI visuals display key performance indicators with comparison values.",docsUrl:"https://docs.semaphor.cloud/docs/charts/kpi"},map:{label:"Map Chart",query:"SELECT country, value FROM table",fields:[{name:"Country/Region",type:"category",description:"geographic identifier"},{name:"Value",type:"number",description:"e.g., population, sales"}],description:"Map charts visualize geographic data using color intensity.",docsUrl:"https://docs.semaphor.cloud/docs/charts/map"},table:{label:"Table",query:"SELECT column1, column2, ... FROM table",fields:[{name:"Columns",type:"category",description:"any data columns"}],description:"Tables display data in rows and columns.",docsUrl:"https://docs.semaphor.cloud/docs/charts/table"},detailTable:{label:"Detail Table",query:"SELECT column1, column2, ... FROM table ORDER BY column1 DESC",fields:[{name:"Columns",type:"category",description:"columns to display (no aggregation)"}],description:"Detail tables display raw records without aggregation. Ideal for event logs, transaction history, and audit trails.",docsUrl:"https://docs.semaphor.cloud/docs/charts/detail-table"}};function is(t){return Ra[t]}function Ba({chartType:t,showDocsLink:n=!0}){const a=is(t);return a?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Query Format"}),e.jsx("code",{className:"block rounded-md bg-muted/50 px-3 py-2 font-mono text-xs text-foreground",children:a.query})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Fields"}),e.jsx("div",{className:"rounded-md border",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Field"}),e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Type"}),e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Description"})]})}),e.jsx("tbody",{children:a.fields.map((r,i)=>e.jsxs("tr",{className:i<a.fields.length-1?"border-b":"",children:[e.jsxs("td",{className:"px-2.5 py-1.5 font-medium text-foreground",children:[r.name,r.optional&&e.jsx("span",{className:"ml-1 text-muted-foreground",children:"?"})]}),e.jsx("td",{className:"px-2.5 py-1.5 font-mono text-muted-foreground",children:r.type}),e.jsx("td",{className:"px-2.5 py-1.5 text-muted-foreground",children:r.description||"—"})]},r.name))})]})})]}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:a.description}),n&&a.docsUrl&&e.jsxs("a",{href:a.docsUrl,target:"_blank",rel:"noopener noreferrer",onClick:r=>r.stopPropagation(),className:"inline-flex items-center gap-1.5 text-xs font-medium text-primary hover:underline",children:["View documentation",e.jsx(s.ExternalLink,{className:"h-3 w-3"})]})]}):null}function Pa({chartType:t}){return is(t)?e.jsxs(s.HoverCard,{openDelay:200,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded bg-muted px-2 py-0.5 font-mono text-[10px] font-semibold uppercase tracking-wider text-muted-foreground transition-colors hover:bg-muted/80 hover:text-foreground",children:"SQL"})}),e.jsx(s.HoverCardContent,{className:"w-80 p-4",side:"left",align:"start",sideOffset:8,children:e.jsx(Ba,{chartType:t})})]}):null}function $e({chartType:t,suffix:n="Configuration"}){const a=is(t),r=(a==null?void 0:a.label)||t;return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-sm font-medium",children:[r," ",n]}),e.jsx(Pa,{chartType:t})]})}function Va(){return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx($e,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(Fa,{})})]})}function Os({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})]})}function ot(){const[t,n]=I.useState([]),a=s.useEditorStore(x=>x.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:i}=s.useEditorStore(x=>x.actions),c=s.useEditorStore(x=>x.queryResultColumns);s.useEditorStore(x=>{var p;return(p=x.card.preferences)==null?void 0:p.filterOnClickColumnIndex}),I.useEffect(()=>{c&&n(new Array(c.length).fill(!1))},[c]);function l(x,p){var m,u;p?a!=null&&a.onClickFilter&&((m=a==null?void 0:a.onClickFilter)==null?void 0:m.length)>0?i({...a,onClickFilter:[...a.onClickFilter,{columnIndex:x,expression:""}]}):i({...a,onClickFilter:[{columnIndex:x,expression:""}]}):(i({...a,onClickFilter:(u=a==null?void 0:a.onClickFilter)==null?void 0:u.filter(N=>N.columnIndex!==x)}),n(N=>{const b=[...N];return b[x]=!1,b}))}function d(x,p){var u;const m=(u=a==null?void 0:a.onClickFilter)==null?void 0:u.map(N=>N.columnIndex===x?{...N,expression:p.target.value}:N);i({...a,onClickFilter:m})}function o(x){var p,m,u,N;if(t!=null&&t[x]||(m=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(b=>b.columnIndex===x))!=null&&m.expression)return e.jsx(s.Input,{value:(N=(u=a==null?void 0:a.onClickFilter)==null?void 0:u.find(b=>b.columnIndex===x))==null?void 0:N.expression,onChange:b=>d(x,b),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:c==null?void 0:c.map((x,p)=>{var m,u;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:!!((m=a==null?void 0:a.onClickFilter)!=null&&m.find(N=>N.columnIndex===p)),onCheckedChange:N=>l(p,N)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:x}),e.jsx("div",{className:"flex items-center gap-2",children:((u=a==null?void 0:a.onClickFilter)==null?void 0:u.find(N=>N.columnIndex===p))&&e.jsx(s.Pencil,{onClick:()=>{n(N=>{const b=[...N];return b[p]=!N[p],b})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),o(p)]})},x)})})}const za=[{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"}],$a=["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"],qa=$a.map(t=>({label:t,value:t}));function Ka(){var o,x,p,m,u,N,b,h,y,T,C,B,O,L,g,w,E,f;const t=s.useEditorStore(M=>M.card),n=(x=(o=t==null?void 0:t.preferences)==null?void 0:o.mapVisualOptions)==null?void 0:x.topoJsonUrl,[a,r]=I.useState(((m=(p=t==null?void 0:t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:m.customTopoJsonUrl)||""),{setCardPreferences:i}=s.useEditorActions(),{data:c}=s.useTopoJson(t),l=Object.keys((c==null?void 0:c.objects)||{}).map(M=>({label:M,value:M}))||[],d=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx($e,{chartType:"map"}),e.jsx(Os,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(De,{className:"h-9",options:d,onValueChange:M=>{console.log("value",M),i({...t.preferences,mapVisualOptions:{topoJsonUrl:M}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:M=>{r(M.target.value)},onBlur:()=>{var M;console.log("onBlur",a),i({...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"}),c&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(De,{className:"h-9",options:l,value:((N=(u=t.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:N.objectKey)||"",label:"Map Object",onValueChange:M=>{var j;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,objectKey:M}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(De,{className:"h-9",options:za,value:((h=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:h.projection)||"",label:"Projection",onValueChange:M=>{var j;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,projection:M}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(De,{className:"h-9",options:qa,value:((T=(y=t.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:T.colorScale)||"",label:"Select Color Scale",onValueChange:M=>{var j;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,colorScale:M}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Os,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((B=(C=t.preferences)==null?void 0:C.mapVisualOptions)==null?void 0:B.projectionScale)||1,onChange:M=>{var j;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,projectionScale:Number(M.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((g=(L=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:L.projectionOffset)==null?void 0:g[0])||0,onChange:M=>{var j,k,D,P;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,projectionOffset:[Number(M.target.value),((P=(D=(k=t.preferences)==null?void 0:k.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:P[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((f=(E=(w=t.preferences)==null?void 0:w.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:f[1])||0,onChange:M=>{var j,k,D,P;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,projectionOffset:[((P=(D=(k=t.preferences)==null?void 0:k.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:P[0])||0,Number(M.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(ot,{})]})}function it({color:t,onColorChange:n,onClose:a}){const[r,i]=I.useState(0),[c,l]=I.useState(100),[d,o]=I.useState(50),[x,p]=I.useState(t);I.useEffect(()=>{const y=Fs(t);if(y){const T=Rs(y.r,y.g,y.b);i(T.h),l(T.s),o(T.l),p(t)}},[t]);const m=y=>{i(y),N(y,c,d)},u=y=>{const T=y.currentTarget.getBoundingClientRect(),C=Math.max(0,Math.min(1,(y.clientX-T.left)/T.width)),B=Math.max(0,Math.min(1,(y.clientY-T.top)/T.height)),O=C*100,L=(1-B)*100;l(O),o(L),N(r,O,L)},N=(y,T,C)=>{const B=Ua(y,T,C),O=Ga(B.r,B.g,B.b);p(O)},b=y=>{if(p(y),/^#[0-9A-Fa-f]{6}$/.test(y)){const T=Fs(y);if(T){const C=Rs(T.r,T.g,T.b);i(C.h),l(C.s),o(C.l)}}},h=()=>{/^#[0-9A-Fa-f]{6}$/.test(x)&&(n(x),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:u,onMouseMove:y=>{y.buttons===1&&u(y)},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:`${c}%`,top:`${100-d}%`,backgroundColor:x}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:y=>m(Number(y.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,{value:x,onChange:y=>b(y.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:x}}),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:h,children:"OK"})]})]})}function Fs(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 Ga(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function Rs(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),i=Math.min(t,n,a);let c=0,l=0;const d=(r+i)/2;if(r!==i){const o=r-i;switch(l=d>.5?o/(2-r-i):o/(r+i),r){case t:c=((n-a)/o+(n<a?6:0))/6;break;case n:c=((a-t)/o+2)/6;break;case a:c=((t-n)/o+4)/6;break}}return{h:Math.round(c*360),s:Math.round(l*100),l:Math.round(d*100)}}function Ua(t,n,a){t/=360,n/=100,a/=100;let r,i,c;if(n===0)r=i=c=a;else{const l=(x,p,m)=>(m<0&&(m+=1),m>1&&(m-=1),m<.16666666666666666?x+(p-x)*6*m:m<.5?p:m<.6666666666666666?x+(p-x)*(.6666666666666666-m)*6:x),d=a<.5?a*(1+n):a+n-a*n,o=2*a-d;r=l(o,d,t+1/3),i=l(o,d,t),c=l(o,d,t-1/3)}return{r:Math.round(r*255),g:Math.round(i*255),b:Math.round(c*255)}}const Bs=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],_a=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Le({value:t,onChange:n,label:a}){const[r,i]=I.useState(!1),[c,l]=I.useState(!1),d=()=>{const o=Bs.find(x=>x.value===t);return o?o.color:t.startsWith("#")?t:Bs[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:i,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:d()},"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:_a.map(o=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",d()===o?"border-gray-900":"border-transparent"),style:{backgroundColor:o},onClick:()=>{n(o),i(!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:()=>{l(!0),i(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),c&&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:()=>l(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(it,{color:d(),onColorChange:o=>{n(o),l(!1)},onClose:()=>l(!1)})})]})]})}const Ha=["auto","number","currency","percent","scientific","date"],Ja=[{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"}],Ya=[{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"}],Qa=t=>t.charAt(0).toUpperCase()+t.slice(1);function qe({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const i=t.type||"auto",c=(d,o)=>{n({...t,[d]:o})},l=()=>i==="currency"?2:i==="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:i,onValueChange:d=>c("type",d),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ha.map(d=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:d==="auto"?"Auto (Default)":Qa(d)},d))})]})]}),i!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(i)&&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,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??l(),onChange:d=>c("decimalPlaces",parseInt(d.target.value)||0),className:"h-8 text-xs"})})]}),i==="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:d=>c("currency",d),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ja.map(d=>e.jsx(s.SelectItem,{value:d.value,className:"text-xs",children:d.label},d.value))})]})]}),["number","currency"].includes(i)&&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:d=>c("useSuffix",d)})]}),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:d=>c("locale",d),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ya.map(d=>e.jsx(s.SelectItem,{value:d.value,className:"text-xs",children:d.label},d.value))})]})]}),i==="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,{placeholder:"e.g., $",value:t.prefix||"",onChange:d=>c("prefix",d.target.value),className:"h-8 text-xs"})})]}),i==="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,{placeholder:"e.g., units",value:t.suffix||"",onChange:d=>c("suffix",d.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(i)&&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:d=>c("negativeInParentheses",d)})]}),i==="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,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:d=>c("multiplyBy",d.target.value?parseFloat(d.target.value):void 0),className:"h-8 text-xs"})})]}),i==="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,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:d=>c("dateFormat",d.target.value),className:"h-8 text-xs"})})]})]})]})}function Wa(){const t=s.useDashboardStore(d=>d.dashboard.filters),n=s.useEditorStore(d=>d.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useColumns(),{assignFilter:i}=s.useAssignFilter();function c(d){const o=i(d,"frame");a({...n,filterId:o})}const l=t==null?void 0:t.find(d=>d.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(Xa,{onSelect:c,columns:r}),l&&e.jsx(s.FilterHeader,{filter:l})]})}function Xa({columns:t,onSelect:n}){var l;const[a,r]=as.useState(!1),[i,c]=as.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:[i?((l=t.find(d=>d.name===i))==null?void 0:l.label)||i:"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 column found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(d=>e.jsxs(s.CommandItem,{value:d.name,onSelect:o=>{const x=o===i?"":o;c(x),r(!1),x&&n(d)},children:[d.label||d.name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",i===d.name?"opacity-100":"opacity-0")})]},d.id))})]})]})})]})}const Za=[{value:"difference",label:"Difference"},{value:"change",label:"Change (%)"},{value:"change_difference",label:"Change + Difference"},{value:"ratio",label:"Ratio"}],en=[{value:"arrow_badge",label:"Arrow + Badge"},{value:"arrow",label:"Arrow Only"},{value:"badge",label:"Badge Only"},{value:"none",label:"None"}];function sn({cardType:t="table"}){var p,m,u,N,b;const n=s.useEditorStore(h=>h.card),a=s.useEditorStore(h=>{var y;return(y=h.card)==null?void 0:y.preferences}),r=s.useEditorStore(h=>h.actions.setCardPreferences),c=(((p=n.config)==null?void 0:p.metricColumns)||[]).some(h=>h.comparisonType&&h.comparisonType!=="none"),l=((m=a==null?void 0:a.tableVisualOptions)==null?void 0:m.metricComparison)||{},d=h=>{r({...a,tableVisualOptions:{...a==null?void 0:a.tableVisualOptions,metricComparison:{...l,...h}}})},o={increase:((u=l.colors)==null?void 0:u.increase)||"green",decrease:((N=l.colors)==null?void 0:N.decrease)||"red",neutral:((b=l.colors)==null?void 0:b.neutral)||"neutral"},x=h=>{r({...a,allowDownload:h})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsxs(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:[c&&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(Ys,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison Settings"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated As"}),e.jsxs(s.Select,{value:l.calculatedAs||"change_difference",onValueChange:h=>d({calculatedAs:h}),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Za.map(h=>e.jsx(s.SelectItem,{value:h.value,className:"text-xs",children:h.label},h.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Number Format"}),e.jsx(qe,{formatOptions:l.formatOptions||{},onFormatOptionsChange:h=>d({formatOptions:h}),showTitle:!1})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator Style"}),e.jsxs(s.Select,{value:l.indicatorStyle||"arrow_badge",onValueChange:h=>d({indicatorStyle:h}),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:en.map(h=>e.jsx(s.SelectItem,{value:h.value,className:"text-xs",children:h.label},h.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Colors"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Le,{value:o.increase,onChange:h=>d({colors:{...o,increase:h}}),label:"Increase"}),e.jsx(Le,{value:o.decrease,onChange:h=>d({colors:{...o,decrease:h}}),label:"Decrease"}),e.jsx(Le,{value:o.neutral,onChange:h=>d({colors:{...o,neutral:h}}),label:"No Change"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Lower is Better"}),e.jsx(s.Checkbox,{checked:l.lowerIsBetter||!1,onCheckedChange:h=>d({lowerIsBetter:!!h})})]})]})]}),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(ot,{}),e.jsx(Wa,{})]})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:x,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 tn(){var r;const t=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:n}=s.useEditorStore(i=>i.actions);function a(i){n({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:i==="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 an(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx($e,{chartType:"text"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Text Type"}),e.jsx(tn,{})]})]})}const nn=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function rn(){var L,g,w,E,f,M,j,k,D,P;const t=s.useEditorStore(v=>v.card),n=s.useEditorStore(v=>{var A;return(A=v.card)==null?void 0:A.preferences}),a=ye.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:i}=s.useEditorActions(),c=I.useMemo(()=>a!==t.type?{...t,type:a}:t,[t,a]),{data:l}=s.useDashboardCardQuery(c),[d,o]=I.useState({}),[x,p]=I.useState(null),[m,u]=I.useState(null),N=I.useMemo(()=>{var R,F,z,G,V,U,Q;if(!(l!=null&&l.records)||l.records.length===0)return[];const v=a==="stackedBar"||a==="stackedLine",A=a==="bar"||a==="line"||a==="horizontalBar"||a==="bullet"||a==="combo"||a==="area"||a==="stackedArea",S=((R=t==null?void 0:t.config)==null?void 0:R.pivotByColumns)&&t.config.pivotByColumns.length>0;if((v||A)&&S){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const J=new Set;return l.pivotSchema.forEach(Z=>{Z.alias&&J.add(Z.alias)}),Array.from(J)}if(l.records.length>0){const J=l.records[0],Z=Object.keys(J),q=new Set;(F=t==null?void 0:t.config)!=null&&F.groupByColumns&&t.config.groupByColumns.forEach(ne=>{q.add(ne.label||ne.name),q.add(ne.alias||ne.name)});const Y=new Set;return(z=t==null?void 0:t.config)!=null&&z.metricColumns&&t.config.metricColumns.forEach(ne=>{const _=ne.alias||ne.name;Y.add(_),Y.add(`${_}_count`),Y.add(`${_}_sum`),Y.add(`${_}_avg`),Y.add(`${_}_min`),Y.add(`${_}_max`);const W=ne.entityName||ne.qualifiedEntityName;W&&(Y.add(`${W}_${_}`),Y.add(`${W}_${_}_count`))}),Z.filter(ne=>!q.has(ne)&&!Y.has(ne))}}if((A||v)&&!S&&((V=(G=t==null?void 0:t.config)==null?void 0:G.metricColumns)!=null&&V.length))return t.config.metricColumns.map(J=>J.alias||J.label||J.name);if((Q=(U=t==null?void 0:t.config)==null?void 0:U.groupByColumns)!=null&&Q.length){const J=t.config.groupByColumns[0],Z=J.label||J.name,q=new Set;return l.records.forEach(Y=>{const se=Y[Z];se!=null&&q.add(String(se))}),Array.from(q)}return[]},[l,(L=t==null?void 0:t.config)==null?void 0:L.groupByColumns,(g=t==null?void 0:t.config)==null?void 0:g.pivotByColumns,(w=t==null?void 0:t.config)==null?void 0:w.metricColumns,t==null?void 0:t.type]),b=I.useMemo(()=>s.getDefaultChartColors(),[]);I.useEffect(()=>{const v={};N.forEach((A,S)=>{v[A]=s.getColorForValue(A,S,n==null?void 0:n.colorConfig)}),o(v)},[N,n==null?void 0:n.colorConfig,b]);const h=(v,A)=>{const S={...d,[v]:A};o(S);const R={...n||{},colorConfig:{segments:S}};r(R);const F={...t,preferences:R};i(F)},y=(v,A)=>{var V;const S=b[A%b.length],{[v]:R,...F}=((V=n==null?void 0:n.colorConfig)==null?void 0:V.segments)||{},z={...n||{},colorConfig:{segments:F}};r(z);const G={...t,preferences:z};i(G),o(U=>({...U,[v]:S}))};if(!N.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((f=(E=t==null?void 0:t.config)==null?void 0:E.groupByColumns)==null?void 0:f.length)||((j=(M=t==null?void 0:t.config)==null?void 0:M.pivotByColumns)==null?void 0:j.length):(D=(k=t==null?void 0:t.config)==null?void 0:k.groupByColumns)==null?void 0:D.length)||["table","kpi","text","custom","heatmap"].includes(a))return null;const B=()=>{const v={...n||{},colorConfig:{segments:{}}};r(v);const A={...t,preferences:v};i(A);const S={};N.forEach((R,F)=>{S[R]=s.getColorForValue(R,F,void 0)}),o(S)},O=Object.keys(((P=n==null?void 0:n.colorConfig)==null?void 0:P.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(Jt,{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:O&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:B,children:[e.jsx(Is,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:N.map((v,A)=>{const S=s.isDefaultColor(d[v],A),R=!S;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:x===v,onOpenChange:F=>p(F?v: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[v]}})}),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:b.slice(0,10).map((F,z)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",d[v]===F?"border-gray-900":"border-transparent"),style:{backgroundColor:F},onClick:()=>{h(v,F),p(null)},children:[z===A%b.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:F})]},`default-${z}`))})]}),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:nn.map((F,z)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",d[v]===F?"border-2 border-gray-900":F==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:F},onClick:()=>{h(v,F),p(null)},children:e.jsx("span",{className:"sr-only",children:F})},`preset-${z}`))})]}),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:()=>{u({value:v,color:d[v]}),p(null)},children:"Custom color"}),!S&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{y(v,A),p(null)},children:[e.jsx(Is,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:v}),R&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},v)})}),m&&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:()=>u(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(it,{color:m.color,onColorChange:v=>{h(m.value,v),u(null)},onClose:()=>u(null)})})]})]})})]})}function Te({value:t,onSave:n,placeholder:a="",type:r="text",className:i=""}){const[c,l]=I.useState(t??""),[d,o]=I.useState(!1);I.useEffect(()=>{l(t??"")},[t]);const x=()=>{n(c),o(!1)},p=()=>{l(t??""),o(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${i}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:d?c:t??"",onChange:m=>{l(m.target.value),o(!0)},onFocus:()=>o(!0),onClick:m=>m.stopPropagation(),className:"h-8 text-xs",onPointerDown:m=>m.stopPropagation(),onKeyDown:m=>{m.stopPropagation(),m.key==="Enter"&&d&&c!==t?x():m.key==="Escape"&&p()},"aria-label":a||"Edit field"}),d&&c!==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:x,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:p,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function Xe({axis:t,label:n,type:a,config:r,onChange:i,defaultTitle:c,hidePosition:l}){var N,b,h,y,T,C,B,O,L,g,w,E,f,M;const d=(j,k)=>{i({...r??{},[j]:k})},o=(j,k)=>{var A,S,R,F;const D=j==="enabled"&&k===!0,P=(A=r==null?void 0:r.name)==null?void 0:A.text,v=D&&!P&&c;i({...r??{},name:{...r==null?void 0:r.name,enabled:j==="enabled"?k:((S=r==null?void 0:r.name)==null?void 0:S.enabled)??!1,text:j==="text"?k:v?c:P,fontSize:j==="fontSize"?k:(R=r==null?void 0:r.name)==null?void 0:R.fontSize,fontWeight:j==="fontWeight"?k:(F=r==null?void 0:r.name)==null?void 0:F.fontWeight}})},x=(j,k)=>{var D,P;i({...r??{},labels:{enabled:j==="enabled"?k:((D=r==null?void 0:r.labels)==null?void 0:D.enabled)??!0,rotation:j==="rotation"?k:(P=r==null?void 0:r.labels)==null?void 0:P.rotation}})},p=(j,k)=>{i({...r??{},scale:{...r==null?void 0:r.scale,[j]:k===""?"auto":Number(k)}})},m=t==="x"?["auto","top","bottom"]:["auto","left","right"],u=["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:j=>d("enabled",j),onClick:j=>j.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 gap-2",children:[e.jsx(s.Checkbox,{id:`${t}-title-enabled`,checked:((N=r==null?void 0:r.name)==null?void 0:N.enabled)??!1,onCheckedChange:j=>o("enabled",j===!0)}),e.jsx(s.Label,{htmlFor:`${t}-title-enabled`,className:"text-xs font-medium cursor-pointer",children:"TITLE"})]}),((b=r==null?void 0:r.name)==null?void 0:b.enabled)&&e.jsxs("div",{className:"space-y-2 pl-6",children:[e.jsx(Te,{placeholder:`${n} title`,value:((h=r==null?void 0:r.name)==null?void 0:h.text)||"",onSave:j=>o("text",j),className:""}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Size"}),e.jsx("div",{className:"w-14",children:e.jsx(Te,{type:"number",placeholder:"12",value:String(((y=r==null?void 0:r.name)==null?void 0:y.fontSize)||12),onSave:j=>o("fontSize",Number(j)||12),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Weight"}),e.jsxs(s.Select,{value:((T=r==null?void 0:r.name)==null?void 0:T.fontWeight)||"normal",onValueChange:j=>o("fontWeight",j),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:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]})]})]})]}),!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:(r==null?void 0:r.position)||"auto",onValueChange:j=>d("position",j),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(j=>e.jsx(s.SelectItem,{value:j,className:"text-xs",children:j==="auto"?"Auto (Default)":s.titleCase(j)},j))})]})]}),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:((C=r==null?void 0:r.labels)==null?void 0:C.enabled)!==!1,onCheckedChange:j=>x("enabled",j)})]}),((B=r==null?void 0:r.labels)==null?void 0:B.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(((O=r==null?void 0:r.labels)==null?void 0:O.rotation)||"auto"),onValueChange:j=>x("rotation",j==="auto"?"auto":Number(j)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(j=>e.jsx(s.SelectItem,{value:j,className:"text-xs",children:j==="auto"?"Auto (Default)":`${j}°`},j))})]})]})]}),a==="value"&&e.jsx(qe,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:j=>i({...r,formatOptions:j}),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(Te,{type:"number",placeholder:"auto",value:((L=r==null?void 0:r.scale)==null?void 0:L.min)==="auto"||((g=r==null?void 0:r.scale)==null?void 0:g.min)===void 0?"":String(r.scale.min),onSave:j=>p("min",j),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(Te,{type:"number",placeholder:"auto",value:((w=r==null?void 0:r.scale)==null?void 0:w.max)==="auto"||((E=r==null?void 0:r.scale)==null?void 0:E.max)===void 0?"":String(r.scale.max),onSave:j=>p("max",j),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(Te,{type:"number",placeholder:"auto",value:((f=r==null?void 0:r.scale)==null?void 0:f.stepSize)==="auto"||((M=r==null?void 0:r.scale)==null?void 0:M.stepSize)===void 0?"":String(r.scale.stepSize),onSave:j=>p("stepSize",j),className:""})})]})]})]})]})]})}function Ze(t,n,a){var c,l,d;if(t==="x"){const o=(l=(c=n==null?void 0:n.config)==null?void 0:c.groupByColumns)==null?void 0:l[0];return(o==null?void 0:o.label)||(o==null?void 0:o.name)||""}const r=((d=n==null?void 0:n.config)==null?void 0:d.metricColumns)||[],i=(a==null?void 0:a.datasetOptions)||[];if(t==="y"){const o=r.filter((x,p)=>{const m=i.find(u=>u.idx===p);return!m||m.yAxisId!=="y2"});return o.length===1&&(o[0].label||o[0].name)||""}if(t==="y2"){const o=r.filter((x,p)=>{const m=i.find(u=>u.idx===p);return(m==null?void 0:m.yAxisId)==="y2"});return o.length===1&&(o[0].label||o[0].name)||""}return""}function ln(){const t=s.useEditorStore(o=>o.card),n=s.useEditorStore(o=>{var x;return(x=o.card)==null?void 0:x.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),i=ye.useEffectiveEditorCardType();if(!t||["tornado","pyramid","kpi","treemap"].includes(i))return null;const c=s.AxisConfigurator.getAxisInfo(i,n);if(!c.hasXAxis&&!c.hasYAxis)return null;const l=(o,x)=>{let p;o==="x"?p="xAxisConfig":o==="y"?p="yAxisConfig":p="secondaryYAxisConfig";const m={...n||{},[p]:x};a(m);const u={...t,preferences:m};r(u)},d=c.hasY2Axis&&i==="combo";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(Qs,{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:[c.hasXAxis&&e.jsx(Xe,{axis:"x",label:"X-Axis",type:c.xAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(i,"x"),n==null?void 0:n.xAxisConfig),onChange:o=>l("x",o),defaultTitle:Ze("x",t,n)}),c.hasYAxis&&e.jsx(Xe,{axis:"y",label:d?"Y-Axis (Left)":"Y-Axis",type:c.yAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(i,"y"),n==null?void 0:n.yAxisConfig),onChange:o=>l("y",o),defaultTitle:Ze("y",t,n)}),d&&e.jsx(Xe,{axis:"y2",label:"Y2-Axis (Right)",type:"value",config:s.mergeAxisConfig({enabled:!0,position:"right"},n==null?void 0:n.secondaryYAxisConfig),onChange:o=>l("y2",o),defaultTitle:Ze("y2",t,n),hidePosition:!0})]})})]})}function on(){const t=s.useEditorStore(m=>m.card),n=ye.useEffectiveEditorCardType(),a=s.useEditorStore(m=>{var u,N,b,h;return(h=(b=(N=(u=m.card)==null?void 0:u.preferences)==null?void 0:N.chartOptions)==null?void 0:b.plugins)==null?void 0:h.legend}),{setLegendOptions:r}=s.useEditorActions();if(!t||!s.chartSupportsLegend(n))return null;const i=s.getDefaultLegendConfig(n),c=(i==null?void 0:i.display)??!0,l=(i==null?void 0:i.position)??"top",d=(i==null?void 0:i.align)??"center",o=(m,u)=>{const N={...a,[m]:u};r(N)},x=["top","bottom","left","right"],p=["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($t,{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:(a==null?void 0:a.display)??c,onCheckedChange:m=>o("display",m)})]}),((a==null?void 0:a.display)??c)&&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:(a==null?void 0:a.position)||l,onValueChange:m=>o("position",m),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:x.map(m=>e.jsx(s.SelectItem,{value:m,className:"text-xs",children:s.titleCase(m)},m))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(a==null?void 0:a.align)||d,onValueChange:m=>o("align",m),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:p.map(m=>e.jsx(s.SelectItem,{value:m,className:"text-xs",children:s.titleCase(m)},m))})]})]})]})]})})]})}function cn(){var A,S,R,F,z,G,V,U,Q,J,Z;const t=s.useEditorStore(q=>q.card),n=ye.useEffectiveEditorCardType(),a=s.useEditorStore(q=>{var Y,se;return(se=(Y=q.card)==null?void 0:Y.preferences)==null?void 0:se.dataLabelsConfig}),r=s.useEditorStore(q=>{var Y;return(Y=q.card)==null?void 0:Y.preferences}),{setCardPreferences:i,updateCardInFrame:c}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(n))return null;const l=n==="bullet"?((A=r==null?void 0:r.bulletConfig)==null?void 0:A.orientation)??(((S=r==null?void 0:r.chartOptions)==null?void 0:S.indexAxis)==="x"?"vertical":"horizontal"):void 0,d=l!=null?l==="horizontal":((R=r==null?void 0:r.chartOptions)==null?void 0:R.indexAxis)==="y",o=n==="stackedBar"||n==="stackedLine",x=n==="pie"||n==="doughnut"||n==="polarArea"||n==="funnel",p=!x,m=n==="bubble"||n==="scatter",u=(z=(F=r==null?void 0:r.chartOptions)==null?void 0:F.plugins)==null?void 0:z.datalabels,N=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),b=s.getDefaultDataLabelsConfig(n,t.preferences),h=a??b,y=(b==null?void 0:b.enabled)??N??!1,T=(a==null?void 0:a.enabled)!==void 0?a.enabled:y,C=(q,Y)=>{const _={...b??{},...a??{},[q]:Y};q==="enabled"&&(_.display=Y,Y&&m&&!_.position&&(_.position="bottom")),q==="position"&&m&&(_.position="bottom");const W={...t.preferences||{},dataLabelsConfig:_};i(W);const le={...t,preferences:W};c(le)},B=(q,Y)=>{const se=a??{},_={...b??{},...se,font:{...se.font||{},[q]:Y}},W={...t.preferences||{},dataLabelsConfig:_};i(W);const le={...t,preferences:W};c(le)},O=(q,Y)=>{const se=a??{},_={...b??{},...se,formatOptions:{...se.formatOptions||{},[q]:Y}},W={...t.preferences||{},dataLabelsConfig:_};i(W);const le={...t,preferences:W};c(le)},L=()=>{const q=n;return q==="stackedBar"||q==="stackedLine"||q==="pie"||q==="doughnut"?"center":d?"right":"top"},g=n!=="treemap"&&n!=="heatmap",w=n!=="treemap",E=L();let f=[];if(g)if(m)f=["bottom"];else if(o||x)f=["center"];else{const q=d?["center","left","right"]:["center","top","bottom"];f=["auto",...n==="bullet"?q:q.filter(se=>se!==E),"custom"]}const M=()=>s.titleCase(E),j=["center","start","end"],k=["center","start","end","top","bottom"],D=p?["auto","number","currency","percent","none"]:["number","currency","percent","none"],P=[{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"}],v=[{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(sa,{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:T,onCheckedChange:q=>C("enabled",q)})]}),T&&e.jsxs(e.Fragment,{children:[g&&!o&&!x&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:m?(h==null?void 0:h.position)||"bottom":(h==null?void 0:h.position)||"auto",onValueChange:q=>C("position",q),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map(q=>e.jsx(s.SelectItem,{value:q,className:"text-xs",children:q==="auto"?M():q==="custom"?"Custom (Advanced)":s.titleCase(q)},q))})]})]}),o&&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:(a==null?void 0:a.showTotal)??!1,onCheckedChange:q=>C("showTotal",q)})]}),(h==null?void 0:h.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:(h==null?void 0:h.anchor)||"center",onValueChange:q=>C("anchor",q),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:j.map(q=>e.jsx(s.SelectItem,{value:q,className:"text-xs",children:s.titleCase(q)},q))})]})]}),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((h==null?void 0:h.align)||"center"),onValueChange:q=>C("align",q),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:k.map(q=>e.jsx(s.SelectItem,{value:q,className:"text-xs",children:s.titleCase(q)},q))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(h==null?void 0:h.format)||(p?"auto":"none"),onValueChange:q=>C("format",q),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:D.map(q=>e.jsx(s.SelectItem,{value:q,className:"text-xs",children:q==="auto"&&p?"Auto (Use Axis)":q==="none"?"None (Raw Value)":s.titleCase(q)},q))})]})]}),(h==null?void 0:h.format)&&!["auto","none"].includes(h.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(h.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(Te,{type:"number",placeholder:"0",value:String(((G=h==null?void 0:h.formatOptions)==null?void 0:G.decimalPlaces)??(h.format==="currency"?2:h.format==="percent"?1:0)),onSave:q=>O("decimalPlaces",Number(q)),className:""})})]}),h.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:((V=h==null?void 0:h.formatOptions)==null?void 0:V.currency)||"USD",onValueChange:q=>O("currency",q),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:P.map(q=>e.jsx(s.SelectItem,{value:q.value,className:"text-xs",children:q.label},q.value))})]})]}),["number","currency"].includes(h.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:((U=h==null?void 0:h.formatOptions)==null?void 0:U.useSuffix)??!1,onCheckedChange:q=>O("useSuffix",q)})]}),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:((Q=h==null?void 0:h.formatOptions)==null?void 0:Q.locale)||"en-US",onValueChange:q=>O("locale",q),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:v.map(q=>e.jsx(s.SelectItem,{value:q.value,className:"text-xs",children:q.label},q.value))})]})]})]}),w&&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(Te,{type:"number",placeholder:"12",value:String(((J=h==null?void 0:h.font)==null?void 0:J.size)||12),onSave:q=>B("size",Number(q)),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:((Z=h==null?void 0:h.font)==null?void 0:Z.weight)||"normal",onValueChange:q=>B("weight",q),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:(h==null?void 0:h.color)==="auto"||!(h!=null&&h.color)?"auto":"custom",onValueChange:q=>{q==="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(Te,{type:"number",placeholder:"0",value:String((h==null?void 0:h.rotation)||0),onSave:q=>C("rotation",Number(q)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const Ps={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%
179
+ 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 dn(){var u,N,b,h,y,T,C,B,O,L;const t=s.useEditorStore(g=>g.card),{setCardPreferences:n}=s.useEditorActions(),a=ye.useEffectiveEditorCardType(),r=((u=t.config)==null?void 0:u.metricColumns)||[],i=((N=t.config)==null?void 0:N.groupByColumns)||[],c=r.length===2&&i.length===0,l=r.some(g=>g.comparisonType&&g.comparisonType!=="none");if(!(a==="kpi"&&(c||l)))return null;const o=((h=(b=t.preferences)==null?void 0:b.kpiVisualOptions)==null?void 0:h.metricComparison)||{},x=g=>{var E;const w={...t.preferences,kpiVisualOptions:{...(E=t.preferences)==null?void 0:E.kpiVisualOptions,metricComparison:{...o,...g}}};n(w)},p=l||o.enabled,m=r.some(g=>g.comparisonType==="previous_period"||g.comparisonType==="same_period_last_year"||g.comparisonType==="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(Ys,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[c&&r.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:o.enabled||!1,onCheckedChange:g=>x({enabled:g,...g&&!o.calculationType?{calculationType:"difference"}:{}})})]}),p&&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 g=o.calculationType||"difference",w=Ps[g];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:w==null?void 0:w.label}),e.jsx("p",{children:w==null?void 0:w.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:w==null?void 0:w.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",w==null?void 0:w.example]})]})})()})]})]}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:g=>x({calculationType:g}),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(Ps).map(([g,w])=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:w.label},g))})]})]}),e.jsx(qe,{formatOptions:o.formatOptions||{},onFormatOptionsChange:g=>x({formatOptions:g}),showTitle:!0,title:"COMPARISON FORMAT"}),(m||c)&&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"}),c&&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:o.position||"right",onValueChange:g=>x({position:g}),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:o.showArrow!==!1,onCheckedChange:g=>x({showArrow:g})}),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:o.showColor!==!1,onCheckedChange:g=>x({showColor:g})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Le,{value:((y=o.colorConfig)==null?void 0:y.increase)||"green",onChange:g=>x({colorConfig:{...o.colorConfig,increase:g}}),label:"Primary > Secondary"}),e.jsx(Le,{value:((T=o.colorConfig)==null?void 0:T.decrease)||"red",onChange:g=>x({colorConfig:{...o.colorConfig,decrease:g}}),label:"Primary < Secondary"}),e.jsx(Le,{value:((C=o.colorConfig)==null?void 0:C.noChange)||"neutral",onChange:g=>x({colorConfig:{...o.colorConfig,noChange:g}}),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:o.conditionalLabel||!1,onCheckedChange:g=>x({conditionalLabel:g})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.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,{id:"label-increase",type:"text",value:((B=o.conditionalLabels)==null?void 0:B.increase)??"Increase",onChange:g=>x({conditionalLabels:{...o.conditionalLabels,increase:g.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,{id:"label-decrease",type:"text",value:((O=o.conditionalLabels)==null?void 0:O.decrease)??"Decrease",onChange:g=>x({conditionalLabels:{...o.conditionalLabels,decrease:g.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,{id:"label-no-change",type:"text",value:((L=o.conditionalLabels)==null?void 0:L.noChange)??"No change",onChange:g=>x({conditionalLabels:{...o.conditionalLabels,noChange:g.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,{id:"label-name",type:"text",value:o.labelName??"",onChange:g=>x({labelName:g.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function un(){var c,l;const t=s.useEditorStore(d=>d.card),{setCardPreferences:n}=s.useEditorActions();if(ye.useEffectiveEditorCardType()!=="kpi")return null;const r=((l=(c=t.preferences)==null?void 0:c.kpiVisualOptions)==null?void 0:l.formatOptions)||{},i=d=>{var x;const o={...t.preferences,kpiVisualOptions:{...(x=t.preferences)==null?void 0:x.kpiVisualOptions,formatOptions:d}};n(o)};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(qe,{formatOptions:r,onFormatOptionsChange:i,showTitle:!1})})]})}function mn(){var c;const t=s.useEditorStore(l=>{var d;return(d=l.card)==null?void 0:d.type}),n=s.useEditorStore(l=>{var d;return(d=l.card)==null?void 0:d.preferences}),{setCardPreferences:a}=s.useEditorActions();if(t!=="treemap")return null;const r=((c=n==null?void 0:n.chartOptions)==null?void 0:c.treemapColorMode)??"branch",i=l=>{const d={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,treemapColorMode:l}};a(d)};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:l=>i(l??"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."})]})]})]})})]})}const xn=Object.keys(s.HEATMAP_PRESET_PALETTES);function hn(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var N;return(N=u.card)==null?void 0:N.preferences}),{setCardPreferences:a}=s.useEditorActions(),r=(t==null?void 0:t.type)==="heatmap",i=(n==null?void 0:n.heatmapConfig)||{},c=i.colorPalette??"green",l=i.legendPosition??"bottom",d=I.useMemo(()=>i.colorRange&&i.colorRange[0]&&i.colorRange[1]?[i.colorRange[0],i.colorRange[1]]:[...s.DEFAULT_HEATMAP_CUSTOM_RANGE],[i.colorRange]),o=u=>{const N={...i,...u};N.colorPalette!=="custom"?delete N.colorRange:(!N.colorRange||!N.colorRange[0]||!N.colorRange[1])&&(N.colorRange=[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]),a({...n||{},heatmapConfig:N})},x=u=>{o({colorPalette:u,colorRange:u==="custom"?i.colorRange??[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},p=(u,N)=>{const b=[...d];b[u]=N,o({colorPalette:"custom",colorRange:b})},m=u=>{o({legendPosition:u})};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:c,onValueChange:u=>x(u??"blue"),className:"space-y-3",children:[xn.map(u=>{const N=s.HEATMAP_PRESET_PALETTES[u];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-${u}`,value:u}),e.jsxs(s.Label,{htmlFor:`heatmap-${u}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:N.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${N.start}, ${N.end})`}})]})]},u)}),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"})]}),c==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(Le,{value:d[0],onChange:u=>p(0,u),label:"Start color"}),e.jsx(Le,{value:d[1],onChange:u=>p(1,u),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:l,onValueChange:u=>m(u??"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(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:u[0].toUpperCase()+u.slice(1)},u))})]})]})]})]}):null}const Vs=["poor","satisfactory","good"];function zs(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 pn(){var D,P;const t=s.useEditorStore(v=>v.card.preferences),n=s.useEditorStore(v=>v.card),a=s.useEditorStore(v=>v.isDevMode),{setCardPreferences:r,setChartOrientation:i}=s.useEditorActions(),c=I.useMemo(()=>(t==null?void 0:t.bulletConfig)||{},[t==null?void 0:t.bulletConfig]),d=s.hasValidCardConfig(n==null?void 0:n.config)&&!a,[o,x]=I.useState(c.showRanges??!1),[p,m]=I.useState(c.rangesArePercentages??!1),u=c.disableAutoComparative?!1:c.comparativeMetricKey!==void 0||!d,[N,b]=I.useState(u);I.useEffect(()=>{x(c.showRanges??!1)},[c.showRanges]),I.useEffect(()=>{m(c.rangesArePercentages??!1)},[c.rangesArePercentages]);const h=c.targetValue===void 0?"":String(c.targetValue);I.useEffect(()=>{const v=c.disableAutoComparative?!1:c.comparativeMetricKey!==void 0||!d;b(v)},[c.disableAutoComparative,c.comparativeMetricKey,d]);const y=I.useMemo(()=>{var v,A;return((A=(v=n==null?void 0:n.config)==null?void 0:v.metricColumns)==null?void 0:A.map(S=>{const R=S.label||S.name||S.alias||"";return{value:R,label:R}}))||[]},[(D=n==null?void 0:n.config)==null?void 0:D.metricColumns]);I.useEffect(()=>{var V,U;if(!t||y.length===0)return;const v={};let A=!1;const S=(V=y[1])==null?void 0:V.value;!c.targetMetricKey&&S&&(v.targetMetricKey=S,A=!0);const R=(U=y[2])==null?void 0:U.value;!c.comparativeMetricKey&&!c.disableAutoComparative&&R&&(v.comparativeMetricKey=R,A=!0);const F=y.slice(3),z={...c.rangeKeys||{}};let G=!1;if(Vs.forEach((Q,J)=>{!z[Q]&&F[J]&&(z[Q]=F[J].value,G=!0)}),G&&(v.rangeKeys=z,A=!0,c.showRanges===void 0&&(v.showRanges=!0)),A){const Q=zs({...c,...v});r({...t,bulletConfig:Q})}},[y,c,t,r]);const T=v=>{const A=zs({...c,...v});r({...t,bulletConfig:A})},C=(v,A)=>{const S={...c.rangeKeys||{},[v]:A.trim()};A.trim()||delete S[v],T({rangeKeys:Object.keys(S).length>0?S:void 0})},B=(v,A)=>{const S=A===""?void 0:Number(A),R={...c.ranges||{}};S===void 0||Number.isNaN(S)?delete R[v]:R[v]=S,T({ranges:Object.keys(R).length?R:void 0})},O=v=>{if(v===""){T({targetValue:void 0});return}const A=Number(v);T({targetValue:Number.isNaN(A)?void 0:A})},L=(v,A)=>{const S=A.trim(),R={...c.rangeLabels||{}};S?R[v]=S:delete R[v],T({rangeLabels:Object.keys(R).length>0?R:void 0})},g=v=>{x(v),T({showRanges:v})},w=v=>{m(v),T({rangesArePercentages:v})},E=c.orientation||(((P=t==null?void 0:t.chartOptions)==null?void 0:P.indexAxis)==="y"?"horizontal":"vertical"),f=v=>{T({orientation:v}),i(v==="horizontal"?"y":"x")},M=[{value:"__none",label:"None"},...y.map(v=>({value:v.value,label:v.label}))],j=M,k=v=>{if(b(v),!v){T({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!d){T({disableAutoComparative:!1});return}if(c.comparativeMetricKey)T({disableAutoComparative:!1});else{const A=y.find(S=>S.value!==c.targetMetricKey);T({comparativeMetricKey:A==null?void 0:A.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:E,onValueChange:v=>f(v),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"})]})]})]}),d&&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:c.targetMetricKey||"__none",onValueChange:v=>T({targetMetricKey:v==="__none"?void 0:v}),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"}),y.map(v=>e.jsx(s.SelectItem,{value:v.value,className:"text-xs",children:v.label},v.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),d?e.jsxs(s.Select,{value:c.comparativeMetricKey||"__none",onValueChange:v=>T({comparativeMetricKey:v==="__none"?void 0:v,disableAutoComparative:v==="__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(v=>e.jsx(s.SelectItem,{value:v.value,className:"text-xs",children:v.label},v.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:N,onCheckedChange:v=>k(v)})]}),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(Se,{type:"number",className:"h-8 text-xs",value:h,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:g})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:p,disabled:!o,onChange:v=>w(v.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:Vs.map(v=>{var A,S,R,F,z;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:[v," LABEL"]}),e.jsx(Se,{placeholder:`Display label (${v})`,value:((A=c.rangeLabels)==null?void 0:A[v])||"",onCommit:G=>L(v,G),className:"h-8 text-xs"})]}),d?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[v," COLUMN"]}),e.jsxs(s.Select,{value:((S=c.rangeKeys)==null?void 0:S[v])||"__none",onValueChange:G=>{G==="__none"?C(v,""):C(v,G)},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select column"})}),e.jsx(s.SelectContent,{children:j.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:[v," COLUMN KEY"]}),e.jsx(Se,{placeholder:"Column key",value:((R=c.rangeKeys)==null?void 0:R[v])||"",onCommit:G=>C(v,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:[v," VALUE"]}),e.jsx(Se,{type:"number",placeholder:p?"0.80":"Static value",value:((F=c.ranges)==null?void 0:F[v])===void 0?"":String((z=c.ranges)==null?void 0:z[v]),onCommit:G=>B(v,G),className:"h-8 text-xs"})]})]},v)})})]})]})]})}function $s(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 fn(){var L,g,w,E,f,M,j,k,D,P,v,A;const t=s.useEditorStore(S=>S.card.preferences),n=s.useEditorStore(S=>S.card),a=ye.useEffectiveEditorCardType(),r=s.useEditorStore(S=>S.isDevMode),{setCardPreferences:i,updateCardInFrame:c}=s.useEditorActions(),l=a==="bubble",d=a==="scatter",o=I.useMemo(()=>(t==null?void 0:t.bubbleScatterConfig)||{},[t==null?void 0:t.bubbleScatterConfig]),p=s.hasValidCardConfig(n==null?void 0:n.config)&&!r,m=I.useMemo(()=>{var S,R;return((R=(S=n==null?void 0:n.config)==null?void 0:S.metricColumns)==null?void 0:R.map(F=>{const z=F.label||F.name||F.alias||"";return{value:z,label:z}}))||[]},[(L=n==null?void 0:n.config)==null?void 0:L.metricColumns]),u=I.useMemo(()=>{var S,R;return((R=(S=n==null?void 0:n.config)==null?void 0:S.groupByColumns)==null?void 0:R.map(F=>{const z=F.label||F.name||F.alias||"";return{value:z,label:z}}))||[]},[(g=n==null?void 0:n.config)==null?void 0:g.groupByColumns]),N=I.useMemo(()=>o.enableGrouping!==void 0?o.enableGrouping:!r&&u.length>=2,[o.enableGrouping,r,u.length]),[b,h]=I.useState(N);I.useEffect(()=>{h(N)},[N]);const y=S=>{const R={...t||{},bubbleScatterConfig:S};i(R),n&&c({...n,preferences:R})},T=S=>{i(S),n&&c({...n,preferences:S})};I.useEffect(()=>{if(!t||m.length===0)return;const S={};let R=!1;if(!o.xMetricKey&&m[0]&&(S.xMetricKey=m[0].value,R=!0),!o.yMetricKey&&m[1]&&(S.yMetricKey=m[1].value,R=!0),l&&!o.radiusMetricKey&&m[2]&&(S.radiusMetricKey=m[2].value,R=!0),!o.labelKey&&u[0]&&(S.labelKey=u[0].value,R=!0),N&&!o.groupKey&&u[1]&&(S.groupKey=u[1].value,S.enableGrouping=!0,R=!0),R){const F=$s({...o,...S});y(F)}},[m,u,o,t,i,l,N]);const C=S=>{const R=$s({...o,...S});y(R)},B=S=>{h(S),C({enableGrouping:S,groupKey:S?o.groupKey:void 0})};if(!l&&!d)return null;const O=l?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:[l?"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"}),p?e.jsxs(s.Select,{value:o.labelKey||"",onValueChange:S=>C({labelKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select label column"})}),e.jsx(s.SelectContent,{children:u.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for labels",value:o.labelKey||"",onCommit:S=>C({labelKey:S})})]}),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:b,onCheckedChange:B})]}),b&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Group By"}),p?e.jsxs(s.Select,{value:o.groupKey||"",onValueChange:S=>C({groupKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select group column"})}),e.jsx(s.SelectContent,{children:u.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:o.groupKey||"",onCommit:S=>C({groupKey:S})})]})]}),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"}),p?e.jsxs(s.Select,{value:o.xMetricKey||"",onValueChange:S=>C({xMetricKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select X metric"})}),e.jsx(s.SelectContent,{children:m.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:o.xMetricKey||"",onCommit:S=>C({xMetricKey:S})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Axis"}),p?e.jsxs(s.Select,{value:o.yMetricKey||"",onValueChange:S=>C({yMetricKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(s.SelectContent,{children:m.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:o.yMetricKey||"",onCommit:S=>C({yMetricKey:S})})]}),l&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Radius"}),p?e.jsxs(s.Select,{value:o.radiusMetricKey||"",onValueChange:S=>C({radiusMetricKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(s.SelectContent,{children:m.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for radius",value:o.radiusMetricKey||"",onCommit:S=>C({radiusMetricKey:S})})]})]}),l&&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:S=>C({radiusScale:S}),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(Se,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((w=o.minRadius)==null?void 0:w.toString())||"",onCommit:S=>C({minRadius:S?Number(S):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Max Radius"}),e.jsx(Se,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((E=o.maxRadius)==null?void 0:E.toString())||"",onCommit:S=>C({maxRadius:S?Number(S):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:([S])=>C({fixedRadius:S}),min:3,max:30,step:1,className:"py-2"})]})]}),d&&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:([S])=>C({fixedRadius:S}),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=(f=t==null?void 0:t.xAxisConfig)==null?void 0:f.name)==null?void 0:M.enabled)??!1,onCheckedChange:S=>{var z,G,V,U;const R=o.xMetricKey||"X Axis",F=o.yMetricKey||"Y Axis";T({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{enabled:S,text:((G=(z=t==null?void 0:t.xAxisConfig)==null?void 0:z.name)==null?void 0:G.text)||R}},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{enabled:S,text:((U=(V=t==null?void 0:t.yAxisConfig)==null?void 0:V.name)==null?void 0:U.text)||F}}})}})]}),((k=(j=t==null?void 0:t.xAxisConfig)==null?void 0:j.name)==null?void 0:k.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(Se,{className:"h-8 text-xs",placeholder:o.xMetricKey||"X Axis",value:((P=(D=t==null?void 0:t.xAxisConfig)==null?void 0:D.name)==null?void 0:P.text)||"",onCommit:S=>{var R;T({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{...(R=t==null?void 0:t.xAxisConfig)==null?void 0:R.name,enabled:!0,text:S||o.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Title"}),e.jsx(Se,{className:"h-8 text-xs",placeholder:o.yMetricKey||"Y Axis",value:((A=(v=t==null?void 0:t.yAxisConfig)==null?void 0:v.name)==null?void 0:A.text)||"",onCommit:S=>{var R;T({...t??{},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{...(R=t==null?void 0:t.yAxisConfig)==null?void 0:R.name,enabled:!0,text:S||o.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const gn=[{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 jn(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var N;return(N=u.card)==null?void 0:N.preferences}),{setCardPreferences:a}=s.useEditorActions(),r=(t==null?void 0:t.type)==="funnel",i=(n==null?void 0:n.funnelConfig)||{},c=i.percentMode??"percentOfTotal",l=i.shrinkFraction??1,d=i.labelThreshold??0,o=u=>{const N={...i,...u};a({...n||{},funnelConfig:N})},x=u=>{o({percentMode:u})},p=u=>{o({shrinkFraction:u[0]})},m=u=>{o({labelThreshold:u[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:c,onValueChange:u=>x(u),className:"space-y-2",children:gn.map(u=>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-${u.value}`,value:u.value,className:"mt-0.5"}),e.jsxs(s.Label,{htmlFor:`funnel-${u.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})]},u.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:[l],onValueChange:p,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(l*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:[d],onValueChange:m,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:d===0?"Showing all labels":`Hide labels below ${d}%`})]})]})]}):null}function Ke(){const t=s.useEditorStore(c=>c.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(c=>!s.METADATA_KEYS.includes(c));let i=r;if(["stackedBar","stackedLine"].includes(t.type)){const c=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:l}=s.getKeys(c);i=l.slice(1)}return{transformedMetricKeys:i,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}const bn=[{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"}],yn=[{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)"}],vn=["center","start","end"],Nn=["center","start","end","top","bottom"];function Ge({config:t,onChange:n,isHorizontal:a=!1,showAutoFormat:r=!0,positionOptions:i,showAppearance:c=!0}){var b,h,y,T,C,B;const l=i??(a?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),d=r?["auto","number","currency","percent","none"]:["number","currency","percent","none"],o=(O,L)=>{const g={...t,[O]:L};n(g)},x=(O,L)=>{const g={...t,font:{...(t==null?void 0:t.font)||{},[O]:L}};n(g)},p=(O,L)=>{const g={...t,formatOptions:{...(t==null?void 0:t.formatOptions)||{},[O]:L}};n(g)},m=()=>a?"Right":"Top",u=t||{},N=u.format||(r?"auto":"number");return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:u.position||"auto",onValueChange:O=>o("position",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:l.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:O==="auto"?m():O==="custom"?"Custom (Advanced)":s.titleCase(O)},O))})]})]}),u.position==="custom"&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Anchor"}),e.jsxs(s.Select,{value:u.anchor||"center",onValueChange:O=>o("anchor",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:vn.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:s.titleCase(O)},O))})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Align"}),e.jsxs(s.Select,{value:String(u.align||"center"),onValueChange:O=>o("align",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Nn.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:s.titleCase(O)},O))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Format"}),e.jsxs(s.Select,{value:N,onValueChange:O=>o("format",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:O==="auto"&&r?"Auto (Use Axis)":O==="none"?"None (Raw Value)":s.titleCase(O)},O))})]})]}),!["auto","none"].includes(N)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[["number","currency","percent"].includes(N)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Decimals"}),e.jsx("div",{className:"w-16",children:e.jsx(Te,{type:"number",placeholder:"0",value:String(((b=u.formatOptions)==null?void 0:b.decimalPlaces)??(N==="currency"?2:N==="percent"?1:0)),onSave:O=>p("decimalPlaces",Number(O)),className:""})})]}),N==="currency"&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Currency"}),e.jsxs(s.Select,{value:((h=u.formatOptions)==null?void 0:h.currency)||"USD",onValueChange:O=>p("currency",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:bn.map(O=>e.jsx(s.SelectItem,{value:O.value,className:"text-xs",children:O.label},O.value))})]})]}),["number","currency"].includes(N)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((y=u.formatOptions)==null?void 0:y.useSuffix)??!1,onCheckedChange:O=>p("useSuffix",O)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Locale"}),e.jsxs(s.Select,{value:((T=u.formatOptions)==null?void 0:T.locale)||"en-US",onValueChange:O=>p("locale",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:yn.map(O=>e.jsx(s.SelectItem,{value:O.value,className:"text-xs",children:O.label},O.value))})]})]})]}),c&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Appearance"}),e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Size"}),e.jsx("div",{className:"w-16",children:e.jsx(Te,{type:"number",placeholder:"12",value:String(((C=u.font)==null?void 0:C.size)||12),onSave:O=>x("size",Number(O)),className:""})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Weight"}),e.jsxs(s.Select,{value:((B=u.font)==null?void 0:B.weight)||"normal",onValueChange:O=>x("weight",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-24 text-xs",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 justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Color"}),e.jsxs(s.Select,{value:u.color==="auto"||!u.color?"auto":"custom",onValueChange:O=>{O==="auto"&&o("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Rotation"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-12",children:e.jsx(Te,{type:"number",placeholder:"0",value:String(u.rotation||0),onSave:O=>o("rotation",Number(O)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const Cn=[{type:"bar",icon:s.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:s.ChartLine,label:"Line"}],Sn=[0,1,2,3,4,5,6,8,10],wn=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],Tn=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function En(){return s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type})!=="combo"?null:e.jsxs(s.AccordionItem,{value:"combo-series",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.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(In,{})})]})}function In(){const{transformedMetricKeys:t}=Ke();return t.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:t.map((n,a)=>e.jsx(kn,{metricKey:n,idx:a},n))})}function kn({metricKey:t,idx:n}){var T;const[a,r]=I.useState(!1),i=s.useEditorStore(C=>{var B;return(B=C.card)==null?void 0:B.preferences}),c=s.useEditorStore(C=>{var B,O;return(O=(B=C.card)==null?void 0:B.preferences)==null?void 0:O.datasetOptions}),l=c==null?void 0:c.find(C=>C.idx===n),{setCardPreferences:d}=s.useEditorStore(C=>C.actions),o=(l==null?void 0:l.type)||"bar",x=(l==null?void 0:l.yAxisId)||"y",p=((T=l==null?void 0:l.dataLabels)==null?void 0:T.enabled)??!1,m=o==="line"?s.ChartLine:s.ChartColumnIncreasing;function u(C){const B={idx:n,type:o,yAxisId:x,dataLabels:l==null?void 0:l.dataLabels,...C};if(!l)d({...i||{},datasetOptions:[...c||[],B]});else{const O=c==null?void 0:c.map(L=>L.idx===n?{...L,...B}:L);d({...i||{},datasetOptions:O})}}function N(C){u({type:C})}function b(C){u({yAxisId:C})}function h(C){u({dataLabels:{...l==null?void 0:l.dataLabels,enabled:C}})}function y(C){u({dataLabels:C})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsxs("span",{className:s.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(m,{className:"h-3 w-3"}),o==="line"?"Line":"Bar"]}),e.jsx("span",{className:s.cn("rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:x==="y2"?"Y2":"Y1"})]})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"flex items-end gap-4",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Chart Type"}),e.jsx("div",{className:"flex gap-2",children:Cn.map(({type:C,icon:B,label:O})=>{const L=o===C;return e.jsxs("button",{onClick:()=>N(C),className:s.cn("flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs transition-colors",L?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:[e.jsx(B,{className:"h-4 w-4"}),e.jsx("span",{children:O})]},C)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Axis"}),e.jsxs(s.Select,{value:x,onValueChange:C=>b(C),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"y",className:"text-xs",children:"Y1 (Left)"}),e.jsx(s.SelectItem,{value:"y2",className:"text-xs",children:"Y2 (Right)"})]})]})]})]}),o==="line"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(s.Select,{value:(l==null?void 0:l.lineStyle)||"solid",onValueChange:C=>u({lineStyle:C}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Tn.map(({value:C,label:B})=>e.jsx(s.SelectItem,{value:C,className:"text-xs",children:B},C))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(s.Select,{value:String((l==null?void 0:l.pointRadius)??3),onValueChange:C=>u({pointRadius:Number(C)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Sn.map(C=>e.jsx(s.SelectItem,{value:String(C),className:"text-xs",children:C===0?"None":C},C))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(s.Select,{value:(l==null?void 0:l.pointStyle)||"circle",onValueChange:C=>u({pointStyle:C}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:wn.map(({value:C,label:B})=>e.jsx(s.SelectItem,{value:C,className:"text-xs",children:B},C))})]})]})]})]}),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 text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:p,onCheckedChange:h})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Ge,{config:l==null?void 0:l.dataLabels,onChange:y,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const es=[{value:"origin",label:"Origin (X-axis)",description:"Fill to the X-axis (y=0)"},{value:"start",label:"Start (Top)",description:"Fill to the top of chart area"},{value:"end",label:"End (Bottom)",description:"Fill to the bottom of chart area"},{value:"-1",label:"Previous Series",description:"Fill to the series below"},{value:"+1",label:"Next Series",description:"Fill to the series above"},{value:"false",label:"No Fill (Line)",description:"Show as line without fill"}],An=[0,1,2,3,4,5,6,8,10],Dn=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],Ln=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Mn(t){return t==null?"origin":t===!1?"false":t}function On(){const t=s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type});return t!=="area"&&t!=="stackedArea"?null:e.jsxs(s.AccordionItem,{value:"area-series",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.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(Fn,{})})]})}function Fn(){const{transformedMetricKeys:t}=Ke();return t.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:t.map((n,a)=>e.jsx(Rn,{metricKey:n,idx:a},n))})}function Rn({metricKey:t,idx:n}){var h;const[a,r]=I.useState(!1),i=s.useEditorStore(y=>{var T;return(T=y.card)==null?void 0:T.preferences}),c=s.useEditorStore(y=>{var T,C;return(C=(T=y.card)==null?void 0:T.preferences)==null?void 0:C.datasetOptions}),l=c==null?void 0:c.find(y=>y.idx===n),{setCardPreferences:d}=s.useEditorStore(y=>y.actions),o=Mn(l==null?void 0:l.fill),x=((h=l==null?void 0:l.dataLabels)==null?void 0:h.enabled)??!1,p=es.find(y=>y.value===o)||es[0];function m(y){const T={idx:n,fill:o,dataLabels:l==null?void 0:l.dataLabels,...y};if(!l)d({...i||{},datasetOptions:[...c||[],T]});else{const C=c==null?void 0:c.map(B=>B.idx===n?{...B,...T}:B);d({...i||{},datasetOptions:C})}}function u(y){m({fill:y==="false"?!1:y})}function N(y){m({dataLabels:{...l==null?void 0:l.dataLabels,enabled:y}})}function b(y){m({dataLabels:y})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:s.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(s.ChartArea,{className:"h-3 w-3"}),p.label.split(" ")[0]]})})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Fill Target"}),e.jsxs(s.Select,{value:o,onValueChange:y=>u(y),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:es.map(y=>e.jsx(s.SelectItem,{value:y.value,className:"text-xs",children:e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{children:y.label})})},y.value))})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(s.Select,{value:(l==null?void 0:l.lineStyle)||"solid",onValueChange:y=>m({lineStyle:y}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ln.map(({value:y,label:T})=>e.jsx(s.SelectItem,{value:y,className:"text-xs",children:T},y))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(s.Select,{value:String((l==null?void 0:l.pointRadius)??3),onValueChange:y=>m({pointRadius:Number(y)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:An.map(y=>e.jsx(s.SelectItem,{value:String(y),className:"text-xs",children:y===0?"None":y},y))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(s.Select,{value:(l==null?void 0:l.pointStyle)||"circle",onValueChange:y=>m({pointStyle:y}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Dn.map(({value:y,label:T})=>e.jsx(s.SelectItem,{value:y,className:"text-xs",children:T},y))})]})]})]})]}),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 text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:x,onCheckedChange:N})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Ge,{config:l==null?void 0:l.dataLabels,onChange:b,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Bn=[0,1,2,3,4,5,6,8,10],Pn=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],ss=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Vn(){return s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type})!=="line"?null:e.jsxs(s.AccordionItem,{value:"line-series",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.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(zn,{})})]})}function zn(){const{transformedMetricKeys:t}=Ke();return t.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:t.map((n,a)=>e.jsx($n,{metricKey:n,idx:a},n))})}function $n({metricKey:t,idx:n}){var y;const[a,r]=I.useState(!1),i=s.useEditorStore(T=>{var C;return(C=T.card)==null?void 0:C.preferences}),c=s.useEditorStore(T=>{var C,B;return(B=(C=T.card)==null?void 0:C.preferences)==null?void 0:B.datasetOptions}),l=c==null?void 0:c.find(T=>T.idx===n),{setCardPreferences:d}=s.useEditorStore(T=>T.actions),o=(l==null?void 0:l.lineStyle)||"solid",x=(l==null?void 0:l.pointRadius)??3,p=(l==null?void 0:l.pointStyle)||"circle",m=((y=l==null?void 0:l.dataLabels)==null?void 0:y.enabled)??!1,u=ss.find(T=>T.value===o)||ss[0];function N(T){const C={idx:n,lineStyle:o,pointRadius:x,pointStyle:p,dataLabels:l==null?void 0:l.dataLabels,...T};if(!l)d({...i||{},datasetOptions:[...c||[],C]});else{const B=c==null?void 0:c.map(O=>O.idx===n?{...O,...C}:O);d({...i||{},datasetOptions:B})}}function b(T){N({dataLabels:{...l==null?void 0:l.dataLabels,enabled:T}})}function h(T){N({dataLabels:T})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:s.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(s.TrendingUp,{className:"h-3 w-3"}),u.label.split(" ")[0]]})})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(s.Select,{value:o,onValueChange:T=>N({lineStyle:T}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:ss.map(({value:T,label:C})=>e.jsx(s.SelectItem,{value:T,className:"text-xs",children:C},T))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(s.Select,{value:String(x),onValueChange:T=>N({pointRadius:Number(T)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Bn.map(T=>e.jsx(s.SelectItem,{value:String(T),className:"text-xs",children:T===0?"None":T},T))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(s.Select,{value:p,onValueChange:T=>N({pointStyle:T}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Pn.map(({value:T,label:C})=>e.jsx(s.SelectItem,{value:T,className:"text-xs",children:C},T))})]})]})]})]}),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 text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:m,onCheckedChange:b})]}),m&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Ge,{config:l==null?void 0:l.dataLabels,onChange:h,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const qn=[0,2,4,6,8,10,12,16,20];function Kn(){const t=s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type});return!t||!["bar","horizontalBar","stackedBar"].includes(t)?null:e.jsxs(s.AccordionItem,{value:"bar-series",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.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(Gn,{})})]})}function Gn(){const{transformedMetricKeys:t}=Ke();return t.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:t.map((n,a)=>e.jsx(Un,{metricKey:n,idx:a},n))})}function Un({metricKey:t,idx:n}){var b;const[a,r]=I.useState(!1),i=s.useEditorStore(h=>{var y;return(y=h.card)==null?void 0:y.type}),c=s.useEditorStore(h=>{var y;return(y=h.card)==null?void 0:y.preferences}),l=s.useEditorStore(h=>{var y,T;return(T=(y=h.card)==null?void 0:y.preferences)==null?void 0:T.datasetOptions}),d=l==null?void 0:l.find(h=>h.idx===n),{setCardPreferences:o}=s.useEditorStore(h=>h.actions),x=(d==null?void 0:d.borderRadius)??0,p=((b=d==null?void 0:d.dataLabels)==null?void 0:b.enabled)??!1;function m(h){const y={idx:n,borderRadius:x,dataLabels:d==null?void 0:d.dataLabels,...h};if(!d)o({...c||{},datasetOptions:[...l||[],y]});else{const T=l==null?void 0:l.map(C=>C.idx===n?{...C,...y}:C);o({...c||{},datasetOptions:T})}}function u(h){m({dataLabels:{...d==null?void 0:d.dataLabels,enabled:h}})}function N(h){m({dataLabels:h})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:x>0&&e.jsxs("span",{className:s.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(s.ChartColumn,{className:"h-3 w-3"}),"r:",x]})})]})}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Bar Style"}),e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Corner Radius"}),e.jsxs(s.Select,{value:String(x),onValueChange:h=>m({borderRadius:Number(h)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:qn.map(h=>e.jsx(s.SelectItem,{value:String(h),className:"text-xs",children:h===0?"None":`${h}px`},h))})]})]})})]}),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 text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:p,onCheckedChange:u})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Ge,{config:d==null?void 0:d.dataLabels,onChange:N,isHorizontal:i==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const _n=[0,1,2,3,4,5,6,8,10],Hn=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],Jn=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Yn(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var o;return(o=d.card)==null?void 0:o.preferences}),a=ye.useEffectiveEditorCardType(),r=n==null?void 0:n.lineStyleConfig,{setCardPreferences:i,updateCardInFrame:c}=s.useEditorActions();if(!t||!["line","area","stackedArea"].includes(a))return null;const l=(d,o)=>{const x={...n||{},lineStyleConfig:{...r,[d]:o}};i(x),c({...t,preferences:x})};return e.jsxs(s.AccordionItem,{value:"line-style",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(Xt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Line Style"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all series. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Line Pattern"}),e.jsxs(s.Select,{value:(r==null?void 0:r.lineStyle)||"solid",onValueChange:d=>l("lineStyle",d),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Jn.map(({value:d,label:o})=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Point Size"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.pointRadius)??3),onValueChange:d=>l("pointRadius",Number(d)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:_n.map(d=>e.jsx(s.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":d},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Point Shape"}),e.jsxs(s.Select,{value:(r==null?void 0:r.pointStyle)||"circle",onValueChange:d=>l("pointStyle",d),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Hn.map(({value:d,label:o})=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]})]})})]})}const Qn=[0,2,4,6,8,10,12,16,20],Wn=[{value:"0.5",label:"50%"},{value:"0.6",label:"60%"},{value:"0.7",label:"70%"},{value:"0.8",label:"80%"},{value:"0.9",label:"90%"},{value:"1",label:"100%"}],Xn=[{value:"0.5",label:"50%"},{value:"0.6",label:"60%"},{value:"0.7",label:"70%"},{value:"0.8",label:"80%"},{value:"0.9",label:"90%"},{value:"1",label:"100%"}];function Zn(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var o;return(o=d.card)==null?void 0:o.preferences}),a=ye.useEffectiveEditorCardType(),r=n==null?void 0:n.barStyleConfig,{setCardPreferences:i,updateCardInFrame:c}=s.useEditorActions();if(!t||!["bar","horizontalBar","stackedBar"].includes(a))return null;const l=(d,o)=>{const x={...n||{},barStyleConfig:{...r,[d]:o}};i(x),c({...t,preferences:x})};return e.jsxs(s.AccordionItem,{value:"bar-style",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.ChartColumn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bar Style"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all bars. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Corner Radius"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.borderRadius)??0),onValueChange:d=>l("borderRadius",Number(d)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Qn.map(d=>e.jsx(s.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":`${d}px`},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Bar Width"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.barPercentage)??.9),onValueChange:d=>l("barPercentage",Number(d)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Wn.map(({value:d,label:o})=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Category Width"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.categoryPercentage)??.8),onValueChange:d=>l("categoryPercentage",Number(d)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Xn.map(({value:d,label:o})=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]})]})})]})}function er(){const t=s.useEditorStore(a=>{var r,i;return(i=(r=a==null?void 0:a.card)==null?void 0:r.preferences)==null?void 0:i.sortChart}),{setSortChart:n}=s.useEditorActions();return e.jsxs(s.AccordionItem,{value:"stacked-sort",children:[e.jsx(s.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.ArrowUpDown,{className:"h-4 w-4"}),"Sort"]})}),e.jsx(s.AccordionContent,{className:"space-y-4 px-1",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort Order"}),e.jsx(De,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"Ascending",value:"asc"},{label:"Descending",value:"desc"}],value:t||"none",onValueChange:a=>{n(a)}})]})})]})}const sr=["kpi"],qs={none:"None",previous_period:"Previous Period",same_period_last_year:"Same Period Last Year",start_vs_end:"Start vs End",target:"Target"},ts=2;function Re(t){return typeof t=="string"?t.trim().toLowerCase():((t==null?void 0:t.id)||(t==null?void 0:t.qualifiedFieldName)||(t==null?void 0:t.name)||(t==null?void 0:t.label)||"").trim().toLowerCase()}function tr(t){if(!(t!=null&&t.name)||!(t!=null&&t.dataType)||t.role==="metric")return!1;const n=s.getDataType(t.dataType);return["date","string","boolean"].includes(n)}function ar(t){return{...t,role:"groupby"}}function nr(){var C,B,O,L;const t=s.useEditorStore(g=>g.card),n=s.useEditorStore(g=>g.actions.updateCardConfig),a=ye.useEffectiveEditorCardType(),{scopedFields:r}=s.useScopedFields(),i=((C=t.config)==null?void 0:C.metricColumns)||[],c=((B=t.config)==null?void 0:B.summary)||{},l=c.breakdownDimensions||[],d=sr.includes(a),o=i.length>0,x=c.enabled===!0,p=d&&o,m=((O=t.config)==null?void 0:O.comparisonType)||((L=i.find(g=>g.comparisonType&&g.comparisonType!=="none"))==null?void 0:L.comparisonType)||"none",u=qs[m]||qs.none,N=Array.from(new Map(r.filter(tr).map(g=>[Re(g),ar(g)])).values()),b=new Set(N.map(g=>Re(g))),h=new Set(l.map(g=>Re(g)).filter(g=>g&&b.has(g)));if(!d)return null;const y=g=>{n(t.id,{summary:{...c,...g}})},T=(g,w)=>{const E=Re(g),f=N.filter(j=>h.has(Re(j))),M=w?h.has(E)?f:[...f,g].slice(0,ts):f.filter(j=>Re(j)!==E);y({breakdownDimensions:M})};return e.jsxs(s.AccordionItem,{value:"summary",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.FileText,{className:"h-4 w-4"}),e.jsx("span",{children:"Summary"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{htmlFor:"summary-enabled",className:"text-xs",children:"Enable Summary"}),!o&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Add at least one metric to enable summary."})]}),e.jsx(s.SmallSwitch,{id:"summary-enabled",checked:x,disabled:!p,onCheckedChange:g=>{if(!g){y({enabled:!1,showOnCard:!1,includeInDashboardSummary:!1});return}y({enabled:!0,showOnCard:c.showOnCard??!0,includeInDashboardSummary:c.includeInDashboardSummary??!0,anomalyEnabled:c.anomalyEnabled??!0})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Comparison"}),e.jsxs("p",{className:"rounded-md border border-border bg-muted/40 px-2 py-1.5 text-xs",children:["Using: ",u]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparison is configured from card/metric comparison settings."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"summary-show-on-card",className:"text-xs",children:"Show summary on card"}),e.jsx(s.SmallSwitch,{id:"summary-show-on-card",checked:c.showOnCard===!0,disabled:!x,onCheckedChange:g=>y({showOnCard:g})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"summary-include-rollup",className:"text-xs",children:"Include in dashboard summary"}),e.jsx(s.SmallSwitch,{id:"summary-include-rollup",checked:c.includeInDashboardSummary===!0,disabled:!x,onCheckedChange:g=>y({includeInDashboardSummary:g})})]}),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 uppercase text-muted-foreground",children:"Breakdown Dimensions"}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[l.length,"/",ts]})]}),N.length===0?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"No dimension fields available for breakdown."}):e.jsx("div",{className:"max-h-40 space-y-2 overflow-y-auto rounded-md border border-border p-2",children:N.map(g=>{const w=Re(g),E=h.has(w),f=h.size>=ts,M=!x||!E&&f;return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(s.Checkbox,{id:`summary-breakdown-${w}`,checked:E,disabled:M,onCheckedChange:j=>T(g,j===!0)}),e.jsx(s.Label,{htmlFor:`summary-breakdown-${w}`,className:"cursor-pointer text-xs",children:g.label||g.name})]},w)})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"summary-anomaly",className:"text-xs",children:"Detect anomalies"}),e.jsx(s.SmallSwitch,{id:"summary-anomaly",checked:c.anomalyEnabled!==!1,disabled:!x,onCheckedChange:g=>y({anomalyEnabled:g})})]})]})]})}function ct({mode:t}){const n=s.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type});return e.jsxs(e.Fragment,{children:[n==="combo"&&e.jsx(En,{}),(n==="area"||n==="stackedArea")&&e.jsx(On,{}),n==="line"&&e.jsx(Vn,{}),(n==="bar"||n==="horizontalBar"||n==="stackedBar")&&e.jsx(Kn,{}),e.jsx(Yn,{}),e.jsx(Zn,{}),e.jsx(mn,{}),t==="config"&&e.jsx(un,{}),t==="config"&&e.jsx(dn,{}),t==="config"&&e.jsx(nr,{}),e.jsx(hn,{}),n==="bullet"&&e.jsx(pn,{}),n==="funnel"&&e.jsx(jn,{}),(n==="bubble"||n==="scatter")&&e.jsx(fn,{}),(n==="stackedBar"||n==="stackedLine")&&e.jsx(er,{}),e.jsx(rn,{}),e.jsx(ln,{}),e.jsx(on,{}),e.jsx(cn,{})]})}function rr(){const t=s.useEditorStore(a=>a.card),n=t==null?void 0:t.type;return n?e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx($e,{chartType:n}),e.jsx(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:e.jsx(ct,{mode:"dev"})})]}):null}function lr(){const t=s.useEditorStore(a=>a.card.type);function n(){switch(t){case"kpi":return e.jsx(Va,{});case"table":return e.jsx(sn,{});case"map":return e.jsx(Ka,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(lt,{})});case"text":return e.jsx(an,{});default:return e.jsx(rr,{})}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function or(){const t=I.useRef(null),n=I.useRef(null),a=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog);return I.useEffect(()=>{var i,c,l,d;r?((i=t.current)==null||i.resize(0),(c=n.current)==null||c.resize(0)):((l=t.current)==null||l.resize(25),(d=n.current)==null||d.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(ma,{})}),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(lr,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Ms,{})})]}):e.jsx(Ms,{})})]})}function ir(t){var he;s.useAIInteractionStore($=>$.currentAIContext);const[n,a]=I.useState(""),[r,i]=I.useState(null),{authToken:c,tokenProps:l}=s.useSemaphorContext(),d=s.useEditorStore($=>{var H;return(H=$==null?void 0:$.card)==null?void 0:H.sql}),o=s.useEditorStore($=>$.isDevMode),x=s.useEditorStore($=>{var H;return(H=$==null?void 0:$.card)==null?void 0:H.python}),{setCardPython:p,setCardSql:m,setRunSql:u,switchCardType:N,setQueryConfig:b}=s.useEditorActions(),h=s.useEditorStore($=>$.currentAssitantScope)||[],y=s.useEditorStore($=>$.userInputForAI),T=s.useEditorStore($=>$.triggerAIRun),C=s.useEditorStore($=>$.card),B=s.useEditorStore($=>$.selectedDatabaseName),O=s.useEditorStore($=>$.selectedTableName),L=s.useEditorStore($=>$.selectedConnectionId),g=s.useEditorStore($=>$.selectedSchemaName),w=s.useDashboardStore($=>$.dashboard.aiScopeTables),{errorMessage:E,refetch:f,data:M}=s.useDashboardCardQuery(C),{setTriggerAIRun:j,setCurrentAssitantScope:k,setCardConfig:D}=s.useEditorActions(),{selectedDatamodelName:P,connectionType:v,selectedDatamodelId:A}=s.useEditorAside(),S=(he=s.useDashboardQuery().data)==null?void 0:he.assistantProfileId,{messages:R,setMessages:F,regenerate:z,error:G,sendMessage:V,status:U,addToolResult:Q,stop:J,clearError:Z}=s.useChat({transport:new s.DefaultChatTransport({api:`${l.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${c==null?void 0:c.accessToken}`}),body:()=>{const $=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:S,isDevMode:o,aiContext:$.currentAIContext,reasoningEffort:$.reasoningEffort,showReasoning:$.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:$,body:H})=>({body:{...H,messages:s.cleanupIncompleteMessages($)}})}),onError:$=>{var H;if($.name==="AbortError"||(H=$.message)!=null&&H.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",$)},onToolCall:q,onFinish({isAbort:$,isDisconnect:H,isError:ae}){a(""),console.log($?"[Editor Assistant] Stream aborted by user":H?"[Editor Assistant] Stream disconnected (network error)":ae?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});I.useEffect(()=>{T&&y&&(V({role:"user",parts:[{type:"text",text:y}]}),j(!1))},[T,y,V,j]);async function q({toolCall:$}){var H,ae,ie,ge,je,ve,Ne,Ie,X,oe,ue,xe,we,Ce,Me,Oe;if(["createChartFromSql","createForecast"].includes($.toolName)){const te=((H=$.input)==null?void 0:H.sql)??((ae=$.args)==null?void 0:ae.sql),me=((ie=$.input)==null?void 0:ie.python)??((ge=$.args)==null?void 0:ge.python),pe=((je=$.input)==null?void 0:je.chartType)??((ve=$.args)==null?void 0:ve.chartType);N(pe),m(te),p(me),u(!0),Q({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if($.toolName==="getUserSql"){if(!d){Q({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",message:"No SQL found"}});return}Q({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",sql:d,python:x||""}})}else if($.toolName==="generateQueryConfig"){a("Generating query config...");const te=((Ne=$.input)==null?void 0:Ne.chartType)??((Ie=$.args)==null?void 0:Ie.chartType),me=((X=$.input)==null?void 0:X.queryConfig)??((oe=$.args)==null?void 0:oe.queryConfig);((ue=$.input)==null?void 0:ue.cardConfig)??((xe=$.args)==null||xe.cardConfig),N(te),D(me),m(void 0),p(void 0);const pe=await f();if((we=pe==null?void 0:pe.data)!=null&&we.error){Q({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",queryConfig:me,message:(Ce=pe==null?void 0:pe.data)==null?void 0:Ce.error.message}});return}if((Me=pe==null?void 0:pe.data)!=null&&Me.records){Q({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:me,message:"The data has been visualized"}});return}Q({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:me,message:"The data has been visualized",records:(Oe=pe==null?void 0:pe.data)==null?void 0:Oe.records}})}else a("Analyzing...")}function Y($){const H=s.removeFromScopeArray(h,$);se(H)}function se($){const H=s.sanitizeAIScope($);k(H),F(ae=>[...ae,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(H)}`}]}])}function ne(){const $={databaseName:B||"",schemaName:g||"",tableName:O||"",datamodelId:A||"",datamodelName:s.resolveDatamodelName(P),connectionId:L||"",connectionType:v||""},H=s.dedup([...h,$]);se(H)}function _(){const $={databaseName:B||"",schemaName:g||"",tableName:O||"",datamodelName:s.resolveDatamodelName(P),connectionId:L||"",connectionType:v||"",datamodelId:A||""};if(!s.isInAiScopeArray([...w||[],...h],$)||h.length===0){const ae=s.dedup([...w||[],...h,$]).filter(ie=>ie.connectionId===$.connectionId);se(ae)}}const W=!["ready","error"].includes(U),le=s.getErrorMessage(G);return{messages:R,setMessages:F,sendMessage:V,regenerate:z,isLoading:W,handleSetAIScope:_,handleAddCurrentTableToScope:ne,removeFromCurrentSelections:Y,currentAssitantScope:h,setCurrentAssitantScope:k,stop:J,status:U,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:le,clearError:Z}}const cr=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Ks({isFullscreen:t,onFullscreenChange:n,fullscreenContainer:a}){const r=I.useRef(null),[i,c]=I.useState(!1),[l,d]=I.useState(s.isDevEnv),[o,x]=I.useState(!1),[p,m]=I.useState(!1),[u,N]=I.useState(!1),b=t??u,h=s.useCurrentAIContext(),{setCurrentAIContext:y}=s.useAIActions(),{clearQueue:T}=s.useQueueActions(),{clearFileAttachments:C}=s.useFileActions(),B=s.useFileAttachments("editor"),O=s.useDashboardStore(te=>te.dashboard.aiContext),L=s.useEditorStore(te=>te.card.dataSource),g=s.useEditorStore(te=>te.actions.setCardSql),w=s.useEditorStore(te=>te.actions.setRunSql),E=s.useEditorStore(te=>te.showAIDialog),f=s.useDashboardStore(te=>te.handleOpenAssistantProfile),{setShowAIDialog:M,setCardPython:j}=s.useEditorActions(),{setDataSource:k}=s.useEditorActions(),{assistantProfile:D}=s.useAssistantProfile(),{messages:P,setMessages:v,sendMessage:A,isLoading:S,stop:R,status:F,llmUsage:z,errorMessage:G,clearError:V}=ir(),[U,Q]=I.useState(""),J=te=>{Q(te.target.value)},Z=te=>{te.preventDefault();const me=U.trim();if(!me&&B.length===0)return;const pe=[];me&&pe.push({type:"text",text:me}),B.forEach(Fe=>{Fe.data&&pe.push({type:"file",mediaType:Fe.type,filename:Fe.name,url:`data:${Fe.type};base64,${Fe.data}`})}),A({role:"user",parts:pe}),Q(""),C("editor"),H({force:!0})},{visibleMessages:q,hasMoreMessages:Y,totalMessageCount:se,loadMoreMessages:ne,resetMessageWindow:_}=s.useMessageWindow(P,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:W,isAtBottom:le,hasNewMessages:he,newMessageCount:$,scrollToBottom:H,handleScroll:ae,resetNewMessageCount:ie}=s.useAutoScroll(q,{threshold:50,behavior:"smooth",isStreaming:S});I.useEffect(()=>{var te;E&&((te=r.current)==null||te.focus(),y({selectedEntities:(L==null?void 0:L.selectedEntities)||[]}))},[E,L,y]),s.useAutoSubmitQueue({assistantType:"editor",status:F,isLoading:S,sendMessage:A});const{hasActiveTools:ge}=s.useActiveToolStatus(P),je=I.useCallback(te=>{n==null||n(te),t===void 0&&N(te)},[t,n]);I.useEffect(()=>{if(!b)return;function te(me){me.key==="Escape"&&je(!1)}return window.addEventListener("keydown",te),()=>{window.removeEventListener("keydown",te)}},[b,je]);const ve=I.useCallback(te=>{A({role:"user",parts:[{type:"text",text:te}]}),H({force:!0})},[A,H]),Ne=I.useCallback(async()=>{const te=JSON.stringify(P??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(te),s.ue.success("Conversation copied")}catch(me){console.error("Failed to copy conversation",me),s.ue.error("Unable to copy conversation")}},[P]),Ie=I.useCallback(()=>{je(!b)},[b,je]);function X(te,me){me==="sql"?(g(te),w(!0)):me==="python"&&(j(te),w(!0))}function oe(){h.selectedEntities.length===0&&y({selectedEntities:(O==null?void 0:O.selectedEntities)||[]})}function ue(te){oe();const me={role:"user",parts:[{type:"text",text:te.title+" "+te.subtitle}]};A(me)}function xe(te){oe(),A({role:"user",parts:[{type:"text",text:te}]})}function we(){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:i,onCheckedChange:c,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:d,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:x,children:"System Message"})]})]})}function Ce(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Me=(U==null?void 0:U.length)===0&&(P==null?void 0:P.filter(te=>te.role==="user").length)===0,Oe=e.jsxs("div",{"data-role":"editor-assistant",className:s.cn("flex h-full w-full flex-col justify-between px-6 py-4",b&&"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:[Ce(),f&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:f,children:(D==null?void 0:D.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[we(),l&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Ne,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:b?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:Ie,children:b?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:()=>{v([]),T("editor"),V(),_()},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:W,className:"mt-2 flex w-full grow basis-0",onScroll:ae,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:ne,className:"text-xs",children:["Load ",Math.min(5,se-q.length)," ","more messages (",se-q.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:q,showTools:l,handleRun:X,showSystemMessage:o,onQuickReply:ve,disableQuickReplies:S}),!ge&&e.jsx(s.AssistantStatus,{status:F,errorMessage:G})]})}),E&&!le&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{H({force:!0}),ie()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),he&&$>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:[Me&&!D&&e.jsx(s.Placeholders,{onClick:ue,placeholders:cr}),e.jsx("div",{children:Me&&D&&e.jsx(s.SeedQuestions,{seedQuestions:D.seedQuestions||[],handleSeedQuestionClick:xe})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:Q,stop:R,input:U,handleInputChange:J,handleSubmit:te=>{oe(),Z(te),H({force:!0})},isLoading:S,status:F,assistantType:"editor",onFocus:()=>{}})]}),z&&i&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",z.inputTokens," prompt tokens, ",z.outputTokens," ","completion tokens, ",z.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(L==null?void 0:L.selectedEntities)||[],open:p,onOpenChange:m,dataSource:L||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return b&&a?Lt.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:Oe})}),a):Oe}function dr(t,n,a){if(!n)return!1;const r=n.qualifiedFieldName,i=n.qualifiedEntityName,c=i&&n.name?`${i}.${n.name}`:r;return t.some(l=>{if(!(s.getDataType(l.dataType||"")==="date"))return!1;const o=s.getSelectedDateFilterColumn(l,a),x=o.split("."),p=x[x.length-1]||o,m=x.length>1?x.slice(0,-1).join("."):void 0,u=l.qualifiedTableName||m,N=u?`${u}.${p}`:void 0;return r?N?N===c||N.endsWith(`.${r}`):p===n.name:N?N===c:p===n.name})}const cs=({dataType:t})=>s.getFieldIconComponent(t);function ur({aliasTemplate:t,onAliasTemplateChange:n}){var o;const[a,r]=I.useState(t),[i,c]=I.useState(!1),l=(o=s.useEditorStore(x=>{var p;return(p=x.card.config)==null?void 0:p.pivotByColumns}))==null?void 0:o[0],d=l?`e.g. Min Sales in {{${l.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$1,{placeholder:d,value:i?a:t,onChange:x=>{r(x.target.value),c(!0)},onFocus:()=>c(!0),onPointerDown:x=>x.stopPropagation(),className:"h-8 text-xs",onKeyDown:x=>{x.key==="Enter"&&i&&a!==t?(n(a),c(!1)):x.key==="Escape"&&(r(t),c(!1))},"aria-label":"Edit alias template"}),i&&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),c(!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),c(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function mr({valueAliases:t,onValueAliasesChange:n}){const[a,r]=I.useState(null),[i,c]=I.useState(""),[l,d]=I.useState(""),o=()=>{n({...t,"":""})},x=m=>{const u={...t};delete u[m],n(u)},p=m=>{const u={...t};delete u[m],u[i]=l,n(u),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(([m,u],N)=>e.jsx("div",{className:"flex items-center gap-2",children:a===m?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:i,onChange:b=>c(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?p(m):b.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:l,onChange:b=>d(b.target.value),className:"h-8 w-24 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.key==="Enter"?p(m):b.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:()=>p(m),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$1,{placeholder:"Value key",value:m,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),c(m),d(u)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:u,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),c(m),d(u)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>x(m),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},m+N)),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 xr({idx:t}){var d;const n=s.useEditorStore(o=>{var x;return(x=o.card)==null?void 0:x.preferences}),a=s.useEditorStore(o=>{var x;return(x=o.card.preferences)==null?void 0:x.datasetOptions}),r=s.useEditorStore(o=>o.actions.setCardPreferences),i=(d=n==null?void 0:n.chartOptions)==null?void 0:d.indexAxis,c=a==null?void 0:a.find(o=>o.idx===t);function l(o,x){(o==="end"||o==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const p={display:o!=="none",align:o,anchor:o,clamp:!0};if(!c)r({...n,datasetOptions:[...a||[],{idx:x,datalabels:p}]});else{const m={...c};m.datalabels=p;const u=a==null?void 0:a.map(N=>N.idx===x?m:N);r({...n,datasetOptions:u})}}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:()=>l("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>l("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Gt,{className:s.cn("h-4 w-4",{"rotate-90":i==="y"})})}),e.jsx("button",{onClick:()=>l("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ht,{className:s.cn("h-4 w-4",{"rotate-90":i==="y"})})}),e.jsx("button",{onClick:()=>l("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(_t,{className:s.cn("h-4 w-4",{"rotate-90":i==="y"})})})]})})]})}function ds({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 hr(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function pr({col:t,idx:n,className:a,iconClassName:r,children:i}){const c=s.useEditorStore(p=>{var m;return(m=p.card)==null?void 0:m.preferences}),l=s.useEditorStore(p=>{var m,u;return(u=(m=p.card)==null?void 0:m.preferences)==null?void 0:u.datasetOptions}),d=l==null?void 0:l.find(p=>p.idx===n),{setCardPreferences:o}=s.useEditorStore(p=>p.actions);function x(p){if(!d)o({...c,datasetOptions:[...l||[],{idx:n,type:p==="area"?"line":p,fill:p==="area"?"origin":""}]});else{const m={...d};m.type=p==="area"?"line":p,m.fill=p==="area"?"origin":"";const u=l==null?void 0:l.map(N=>N.idx===n?m:N);o({...c,datasetOptions:u})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[i||e.jsx(ds,{className:"max-w-[100px]",title:t,children:hr(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>x("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>x("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>x("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(xr,{idx:n})]})]})}function fr(){const t=s.useEditorStore(d=>d.card.type),n=s.useEditorStore(d=>d.isDevMode),a=s.useEditorStore(d=>d.card.preferences),{setCardPreferences:r}=s.useEditorStore(d=>d.actions);function i(d){var p;const o={datalabels:{display:d!=="none",align:d,anchor:d,clamp:!0}},x={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(p=a==null?void 0:a.chartOptions)==null?void 0:p.plugins,...o}}};r(x)}function c(){var d,o,x;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((x=(o=(d=a==null?void 0:a.chartOptions)==null?void 0:d.plugins)==null?void 0:o.datalabels)==null?void 0:x.anchor)||"none",onValueChange:i,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 l(){var d,o,x;return e.jsx("div",{children:e.jsxs(s.Select,{value:((x=(o=(d=a==null?void 0:a.chartOptions)==null?void 0:d.plugins)==null?void 0:o.datalabels)==null?void 0:x.anchor)||"none",onValueChange:i,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?c():l()})}function gr({column:t}){const n=s.useEditorStore(o=>o.card.type),a=s.useEditorStore(o=>{var x,p;return(p=(x=o.card)==null?void 0:x.config)==null?void 0:p.metricColumns}),r=(a==null?void 0:a.map(o=>o.label))||[],i=r==null?void 0:r.find(o=>o===t.label||o===t.name),c=i?r.indexOf(i):-1;function l(){return e.jsx("div",{className:"pr-1",children:i&&e.jsx(pr,{idx:c,col:i,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function d(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(fr,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&l(),["pie","doughnut"].includes(n)&&d()]})}function jr({field:t,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:i}=s.useSemaphorContext(),c=s.useEditorStore(x=>x.card),l=c==null?void 0:c.dataSource,d=["attribute-values",t.entityName,t.name,n,a],o=s.useQuery({queryKey:d,queryFn:async()=>{if(!(l!=null&&l.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const x={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},p={connection_id:l.connectionId,cardConfig:x,cardDataSource:l,cache_config:s.getCacheConfig({card:c})};console.log("requestBody",p);const m=await s.postRequestRegular(`${i.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",p);if(m!=null&&m.error)return console.error("Error fetching attribute values:",m.error),[];const u=t.name;return((m==null?void 0:m.records)||[]).map(b=>{const h=b[u]||b[t.alias||u]||b[t.label];return{id:h||"",value:h||"",label:String(h||"(empty)")}})}catch(x){return console.error("Error fetching attribute values:",x),[]}},enabled:!!t&&!!(l!=null&&l.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 dt({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:i,onSave:c}){var B,O;const l=!!i,[d,o]=I.useState(l?"values":"fields"),[x,p]=I.useState(""),[m,u]=I.useState({id:(i==null?void 0:i.id)||s.v4(),field:(i==null?void 0:i.field)||null,selectedValues:i?Array.isArray(i.value)?i.value:[i.value]:[]}),N=a.filter(L=>{var w;return l?!1:!((w=r==null?void 0:r.conditions)==null?void 0:w.some(E=>E.field.id===L.id))&&L.label.toLowerCase().includes(x.toLowerCase())}),b=L=>{u({...m,field:L}),o("values")},h=()=>{if(m.field&&m.selectedValues.length>0){const L={id:m.id,field:m.field,operator:"in",value:m.selectedValues};let g;if(l){const w=((r==null?void 0:r.conditions)||[]).map(E=>E.id===i.id?L:E);g={...r,conditions:w}}else{const w=(r==null?void 0:r.conditions)||[];g={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...w,L],groups:[]}}c(g),n(!1)}},y=()=>{if(!l||!i)return;const L=((r==null?void 0:r.conditions)||[]).filter(g=>g.id!==i.id);if(L.length>0){const g={...r,conditions:L};c(g)}else c(void 0);n(!1)},T=L=>{u({...m,selectedValues:L})},C=()=>{l&&i?(u({id:i.id,field:i.field,selectedValues:Array.isArray(i.value)?i.value:[i.value]}),o("values")):(u({id:s.v4(),field:null,selectedValues:[]}),o("fields")),p("")};return I.useEffect(()=>{t&&C()},[t,l,i]),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:l?`Edit Filter: ${(B=m.field)==null?void 0:B.label}`:d==="fields"?"Select Field to Filter":`Select Values for ${(O=m.field)==null?void 0:O.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!l&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&d==="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(L=>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:[L.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(L.value)?`${L.value.length} values`:String(L.value)})]},L.id))})]}),d==="fields"&&!l?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$1,{placeholder:"Search fields...",value:x,onChange:L=>p(L.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:N.map(L=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>b(L),children:[e.jsx(cs,{dataType:s.getDataType(L.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:L.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[L.entityName,".",L.name]})]})]},L.id))}),N.length===0&&x&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',x,'"']}),N.length===0&&!x&&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(br,{field:m.field,selectedValues:m.selectedValues,onValuesChange:T,onBack:l?void 0:()=>o("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:l?e.jsx(s.Button,{variant:"destructive",onClick:y,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:C,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:h,disabled:!m.field||m.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function br({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[i,c]=I.useState(""),{values:l,isLoading:d,isFetching:o}=jr({field:t,searchQuery:i,limit:500}),x=i?l.filter(u=>String(u.value).toLowerCase().includes(i.toLowerCase())):l,p=u=>{const N=n.includes(u);a(N?n.filter(b=>b!==u):[...n,u])},m=()=>{n.length===x.length&&x.length>0?a([]):a(x.map(u=>u.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$1,{placeholder:"Search values...",value:i,onChange:u=>c(u.target.value),className:"pl-10"})]}),d||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===x.length&&x.length>0,onCheckedChange:m}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",x.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:x.map(u=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>p(u.value),children:[e.jsx(s.Checkbox,{checked:n.includes(u.value),onCheckedChange:()=>p(u.value)}),e.jsx(ds,{className:"text-sm",children:u.label})]},u.id))})]})]})}function yr({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:i,hasPivotColumns:c=!1,cardType:l}){var vs,Ns,Cs,Ss,ws,Ts,Es;const{attributes:d,listeners:o,setNodeRef:x,transform:p,transition:m,isDragging:u}=s.useSortable({id:t.id}),N=s.useEditorStore(K=>K.card),b=s.useEditorStore(K=>K.frame),{scopedFields:h}=s.useScopedFields(),{userContext:y}=s.useCurrentUserInfo(),T=(y==null?void 0:y.type)==="organization",C=(vs=N.dataSource)==null?void 0:vs.semanticDomainId,{promoteMetric:B}=s.usePromoteCalculatedMetricToDomain({domainId:C}),{updateLabel:O,handleAggregationChange:L,handleDateFormatChange:g,handleGranularityChange:w,handleAliasTemplateChange:E,handleValueAliasesChange:f,removeField:M,handleMetricComparisonChange:j,handleKpiShowTrendlineChange:k,handleKpiTrendlineWindowChange:D,handleKpiTrendlineGranularityChange:P,handleMetricTargetValueChange:v}=s.useFieldManagement(N),[A,S]=I.useState(!1),[R,F]=I.useState(!1),[z,G]=I.useState(!1),[V,U]=I.useState(null),[Q,J]=I.useState(t.dateFormat||"YYYY-MM-DD"),[Z,q]=I.useState(t.customFormat||""),[Y,se]=I.useState(!!t.customFormat),[ne,_]=I.useState(t.granularity||"day"),[W,le]=I.useState(t.aliasTemplate||""),[he,$]=I.useState(t.valueAliases||{}),[H,ae]=I.useState((Ns=t.parameters)==null?void 0:Ns.filters),ie=K=>{K==="custom"?se(!0):(se(!1),J(K),(n==="groupBy"||_e)&&g(a,K,"",n))},ge=K=>{q(K),(n==="groupBy"||_e)&&g(a,"custom",K,n)},je=K=>{var re;_(K);const ee=(re=s.getDateFormatOptionsForGranularity(K)[0])==null?void 0:re.value;ee&&!Y&&(J(ee),n==="groupBy"&&g(a,ee,"",n)),n==="groupBy"&&w(a,K)},ve=K=>{le(K),n==="metrics"&&E(a,K)},Ne=K=>{$(K),n==="metrics"&&f(a,K)},Ie=K=>{O(n,a,K)},X=K=>K!=null&&K.startsWith("card-source-")?K.replace("card-source-",""):K,oe=(K,ce,ee)=>{const re=X(K.id),de=X(ce.id);return re&&de&&re===de?!0:K.name===ce.name&&K.role===ce.role},xe=s.isCalculatedMetric(t)?(Cs=b==null?void 0:b.calculatedFields)==null?void 0:Cs.find(K=>oe(K,t)):void 0,we=t.fieldScope==="dashboard"||t.fieldScope===void 0&&!!xe,Ce=t.fieldScope==="domain",Me=Ce?"domain":we?"dashboard":"card",Oe=Ce?t:we&&xe?xe:t,te=K=>{var ce;if(ae(K),n==="metrics"){const ee={...t,parameters:{...t.parameters,filters:K}},re=[...((ce=N.config)==null?void 0:ce.metricColumns)||[]];re[a]=ee,s.useEditorStore.getState().actions.updateCardConfig(N.id,{metricColumns:re})}F(!1)},me=async K=>{await B(K),kt()},pe=()=>{M(n,a)},Fe={transform:s.CSS.Transform.toString(p),transition:m},ms=s.getDataType(t.dataType),Ue=ms==="date",xs=l==="kpi",_e=n==="detailColumns",hs=((Ss=N.config)==null?void 0:Ss.metricColumns)||[],Ve=((ws=N.config)==null?void 0:ws.groupByColumns)||[],ps=s.useDashboardStore(K=>{var ce;return(ce=K.dashboard)==null?void 0:ce.filters})??[],fs=s.useDashboardStore(K=>K.filterValues),mt=s.getDateFormatOptionsForGranularity(ne),xt=!!l&&s.COMPARISON_SUPPORTED_CHART_TYPES.includes(l),ht=l==="kpi"||l==="table",ke=I.useMemo(()=>Ve.find(K=>s.getDataType(K.dataType||"")==="date"),[Ve]),gs=I.useMemo(()=>Ve.some(K=>s.getDataType(K.dataType||"")==="date"),[Ve]),pt=I.useMemo(()=>{var re;if(!ke)return!1;const K=(re=N.config)==null?void 0:re.filters;if(!K)return!1;const ce=de=>{const fe=de.field;return fe?ke.id&&fe.id===ke.id||ke.qualifiedFieldName&&fe.qualifiedFieldName===ke.qualifiedFieldName?!0:fe.name===ke.name:!1},ee=de=>de.conditions.some(be=>s.getDataType(be.field.dataType||"")==="date"&&ce(be))?!0:de.groups.some(be=>ee(be));return ee(K)},[(Ts=N.config)==null?void 0:Ts.filters,ke]),ft=I.useMemo(()=>dr(ps,ke,fs),[ps,fs,ke]),js=pt||ft,gt=I.useMemo(()=>hs.some(K=>K.comparisonType==="start_vs_end"),[hs]),jt=n!=="pivotBy",bt=Ue&&n==="groupBy"&&(!xs||gt),yt=!xs&&Ue&&(n==="groupBy"||_e),vt=l==="kpi"&&Ue&&n==="groupBy",Nt=n==="metrics",bs=xt&&n==="metrics",Ct=()=>{const K=t,ce=n==="metrics"&&s.isCalculatedMetric(K);return e.jsxs("div",{className:"space-y-1",children:[!ce&&e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:ee=>{ee.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}`}),ce&&K.calculatedFormula&&e.jsxs("div",{title:s.formatDisplayFormula(K.calculatedFormula),onPointerDown:ee=>{ee.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:["= ",s.formatDisplayFormula(K.calculatedFormula)]})]})},St=()=>jt?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(Te,{value:t.label??"",onSave:Ie,placeholder:"Display label...",type:"text"})]}):null,ys=()=>bt?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:ne,onValueChange:je,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(K=>e.jsx(s.SelectItem,{className:"text-xs",value:K,children:s.toTitleCase(K)},K))})]})]}):null,wt=()=>yt?e.jsxs(e.Fragment,{children:[ys(),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:Y?"custom":Q,onValueChange:ie,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:mt.map(K=>e.jsx(s.SelectItem,{className:"text-xs",value:K.value,children:K.label},K.value))})]}),Y&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:Z,onChange:K=>{K.stopPropagation(),ge(K.target.value)},onClick:K=>K.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,Tt=()=>{var ce,ee,re,de;const K=vt;return K?e.jsx(e.Fragment,{children:K&&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:((ce=N.config)==null?void 0:ce.showTrendline)||!1,onCheckedChange:k})]})}),((ee=N.config)==null?void 0:ee.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$1,{type:"number",min:"1",max:"365",value:((re=N.config)==null?void 0:re.trendlineWindow)||30,onChange:fe=>{const be=parseInt(fe.target.value)||30;D(be)},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:((de=N.config)==null?void 0:de.trendlineGranularity)||"day",onValueChange:P,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"})]})]})]})]})]})}):null},Et=()=>{if(!Nt)return null;const K=t,ce=s.isCalculatedMetric(K);return e.jsxs(e.Fragment,{children:[ce&&T&&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:()=>G(!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:ee=>{L(a,ee)},disabled:ce,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"})]})]})]})]}),bs&&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:K.comparisonType||"none",onValueChange:ee=>j(a,ee),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"}),(()=>{const ee=!gs||!js,re=gs?js?void 0:"Add a date filter to enable":"Add a date groupBy to enable",de=(fe,be)=>e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.SelectItem,{value:fe,disabled:ee,title:re,children:be})}),ee&&re&&e.jsx(s.TooltipContent,{side:"right",children:re})]})});return e.jsxs(e.Fragment,{children:[de("previous_period","Previous Period"),de("same_period_last_year","Same Period Last Year"),de("start_vs_end","Start vs End")]})})(),ht&&e.jsx(s.SelectItem,{value:"target",children:"Target"})]})]})]}),bs&&K.comparisonType==="target"&&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(s.Input$1,{type:"number",value:K.targetValue!==void 0&&K.targetValue!==null?String(K.targetValue):"",onChange:ee=>{const re=ee.target.value;if(re===""){v(a,void 0);return}const de=Number(re);v(a,Number.isFinite(de)?de:void 0)},className:"h-8 text-xs",placeholder:"Enter target value..."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(H==null?void 0:H.conditions)&&H.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:H.conditions.map(ee=>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:()=>{U(ee),F(!0)},children:[e.jsxs("span",{className:"font-medium",children:[ee.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(ee.value)?ee.value.length===1?String(ee.value[0]):ee.value.length<=2?ee.value.join(", "):`${ee.value.slice(0,2).join(", ")} +${ee.value.length-2}`:String(ee.value)})}),Array.isArray(ee.value)&&ee.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 (",ee.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:ee.value.map((re,de)=>e.jsx("div",{children:String(re)},de))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:re=>{var fe;re.stopPropagation();const de=H.conditions.filter(be=>be.id!==ee.id);if(de.length>0){const be={...H,conditions:de};te(be)}else if(ae(void 0),n==="metrics"){const be={...t,parameters:{...t.parameters,filters:void 0}},Ae=[...((fe=N.config)==null?void 0:fe.metricColumns)||[]];Ae[a]=be,s.useEditorStore.getState().actions.updateCardConfig(N.id,{metricColumns:Ae})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},ee.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{U(null),F(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(gr,{column:t}),c&&e.jsxs(e.Fragment,{children:[e.jsx(ur,{aliasTemplate:W,onAliasTemplateChange:ve}),e.jsx(mr,{valueAliases:he,onValueAliasesChange:Ne})]})]})},{columns:It=[],refetch:kt}=s.useColumns(),At=(H==null?void 0:H.conditions)&&H.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:x,style:Fe,...d,...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 ${u?"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(cs,{dataType:ms}),e.jsx(ds,{className:s.cn("w-[140px] flex-1 text-sm",At&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((Es=H==null?void 0:H.conditions)==null?void 0:Es.length)&&!A&&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:H.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:H.conditions.map(K=>e.jsxs("div",{children:[K.field.label,":"," ",Array.isArray(K.value)?`${K.value.length} values`:String(K.value)]},K.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:K=>{K.stopPropagation(),S(!A)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${A?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:K=>{K.stopPropagation(),i(r==="asc"?"desc":"asc")},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:K=>{K.stopPropagation(),pe()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),A&&e.jsxs("div",{className:"space-y-3",children:[Ct(),St(),l==="kpi"&&ys(),wt(),Tt(),Et()]})]}),R&&e.jsx(dt,{open:R,onOpenChange:K=>{F(K),K||U(null)},availableFields:It,existingFilters:H,editingCondition:V,onSave:K=>{var ce;if(K)te(K);else if(ae(void 0),n==="metrics"){const ee={...t,parameters:{...t.parameters,filters:void 0}},re=[...((ce=N.config)==null?void 0:ce.metricColumns)||[]];re[a]=ee,s.useEditorStore.getState().actions.updateCardConfig(N.id,{metricColumns:re})}U(null)}}),z&&n==="metrics"&&e.jsx(s.CalculatedFieldEditor,{open:z,onOpenChange:G,availableFields:h,existingField:Oe,existingFieldScope:Me,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:K=>{var Ae;if(K.role!=="metric")return;const ce=[...((Ae=N.config)==null?void 0:Ae.metricColumns)||[]];ce[a]=K;const{frame:ee,actions:re}=s.useEditorStore.getState();if(re.updateCardConfig(N.id,{metricColumns:ce}),!s.isCalculatedMetric(K))return;const de=ee.calculatedFields||[],fe=de.findIndex(Ee=>Ee.name===t.name&&Ee.role===t.role);if(fe<0)return;const be=de.map((Ee,ze)=>ze===fe?{...K,id:Ee.id}:Ee);re.updateFrame({calculatedFields:be})},onSaveToDashboard:K=>{var ze;if(K.role!=="metric")return;const{frame:ce,actions:ee}=s.useEditorStore.getState(),re=ce.calculatedFields||[],de=re.findIndex(He=>oe(He,K)),fe=de>=0&&re[de].id!==K.id?{...K,id:re[de].id}:K,be=de>=0?re.map((He,Dt)=>Dt===de?fe:He):[...re,fe];ee.updateFrame({calculatedFields:be});const Ae=[...((ze=N.config)==null?void 0:ze.metricColumns)||[]],Ee=t;Ae[a]={...fe,id:Ee.id,aliasTemplate:Ee.aliasTemplate,valueAliases:Ee.valueAliases,parameters:Ee.parameters,customFormat:Ee.customFormat},ee.updateCardConfig(N.id,{metricColumns:Ae})},onPromoteMetricToDomain:C&&T?me:void 0,domainId:C,cardId:N.id})]})}function vr({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"})]})]})]});case"detailColumns":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields to display as columns in the detail table. No aggregation applied - shows raw values from the database."})]});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 Pe({zone:t,fields:n,label:a,placeholder:r,shouldShow:i,hasPivotColumns:c=!1,activeField:l=null}){const{isOver:d,setNodeRef:o}=s.useDroppable({id:t}),{updateSortByColumn:x}=s.useEditorActions(),p=s.useEditorStore(y=>y.card),m=s.useEditorStore(y=>y.card.type),u=n.length>0,N=I.useMemo(()=>!l||!d?!0:s.validateFieldForChartType(l,t,m).isValid,[l,d,t,m]),b=(y,T)=>{var B;!((B=p.config)!=null&&B.sortByColumns)||p.config.sortByColumns.findIndex(O=>O.id===y)===-1||x(p.id,y,{direction:T})};if(t==="sortBy"&&i===!1)return null;const h=t!=="sortBy"&&m!=="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}),h&&e.jsx(vr,{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":d&&N,"border-red-500 bg-red-50 dark:bg-red-950":d&&!N,"border-muted-foreground/30 bg-muted/40":!d&&u,"min-h-[60px] border-muted-foreground/20 bg-background":!d&&!u}),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,{id:t,items:n.map(y=>y.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((y,T)=>{const B=y.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(yr,{field:y,zone:t,index:T,sortDirection:B,onSortDirectionChange:O=>b(y.id,O),hasPivotColumns:c,cardType:m})})},y.id)})})})})]})}function Nr({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r,detailFields:i,activeField:c}){var Q,J,Z,q;const[l,d]=I.useState(!1),o=s.useEditorStore(Y=>{var se;return!!((se=Y.card.customCardPreferences)!=null&&se.url)}),x=s.useEditorStore(Y=>Y.card),p=s.useEditorStore(Y=>Y.frame),m=s.findCustomVisualConfigCard(p,x),{manifest:u}=s.useCustomVisual(((Q=m==null?void 0:m.customCardPreferences)==null?void 0:Q.url)||""),N=(J=u==null?void 0:u.visuals)==null?void 0:J.find(Y=>{var se;return Y.name===((se=m==null?void 0:m.customCardPreferences)==null?void 0:se.componentName)}),b=s.resolveMultiInputType(m,N)==="multiple",h=b&&!!((Z=m==null?void 0:m.customCardPreferences)!=null&&Z.url),y=s.getConfigSlotExpectedType(N==null?void 0:N.slots),T=s.useEditorStore(Y=>Y.actions.updateCardConfig),C=s.useEditorStore(Y=>Y.actions.updateFrame),{scopedFields:B,refetch:O}=s.useScopedFields(),{userContext:L}=s.useCurrentUserInfo(),g=b&&(m==null?void 0:m.id)===x.id&&y?y:x==null?void 0:x.type,w=g==="detailTable",E=t.length>0||a.length>0||i.length>0,f=!w&&(g!=="kpi"||a.length<=2),M=!w,j=!w&&g!=="kpi",k=g!=="kpi"&&E,D=w,P=w?"Drop fields from Columns":"Drop fields from Rows or Metrics",v=(q=x.dataSource)==null?void 0:q.semanticDomainId,{promoteMetric:A}=s.usePromoteCalculatedMetricToDomain({domainId:v}),S=(L==null?void 0:L.type)==="organization",R=Y=>{const se=p.calculatedFields||[],ne=se.findIndex(H=>H.name===Y.name&&H.role===Y.role),_=ne>=0?{...Y,id:se[ne].id}:Y,W=ne>=0?se.map((H,ae)=>ae===ne?_:H):[...se,_];C({calculatedFields:W});const le=s.getNewField(_,"metrics",a),he=a.findIndex(H=>H.name===le.name&&H.role===le.role),$=he>=0?a.map((H,ae)=>ae===he?{...H,...le,id:H.id}:H):[...a,le];T(x.id,{metricColumns:$})},F=async Y=>{await A(Y),O()},z=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(g),G=j&&!z,V=()=>g==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},U=()=>g==="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:[f&&e.jsx(Pe,{zone:"groupBy",fields:t,label:V().label,placeholder:V().placeholder,activeField:c}),G&&e.jsx(Pe,{zone:"pivotBy",fields:n,label:"Pivot Columns",placeholder:"Drop fields to pivot data",activeField:c}),M&&e.jsx(Pe,{zone:"metrics",fields:a,label:U().label,placeholder:U().placeholder,hasPivotColumns:n.length>0,activeField:c}),D&&e.jsx(Pe,{zone:"detailColumns",fields:i,label:"Columns",placeholder:"Drag columns to display"}),a.length>=1&&S&&e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:()=>d(!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"]}),k&&e.jsx(Pe,{zone:"sortBy",fields:r,label:"Sort By",placeholder:P,activeField:c})]})]}),(!o||h)&&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:"CHART SETTINGS"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsx(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:e.jsx(ct,{mode:"config"})})})]}),(o||h)&&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(_s,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"COMPONENT SETTINGS"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsx(lt,{})})]})]}),e.jsx(s.CalculatedFieldEditor,{open:l,onOpenChange:d,availableFields:B,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:Y=>{Y.role==="metric"&&T(x.id,{metricColumns:[...a,Y]})},onSaveToDashboard:Y=>{Y.role==="metric"&&R(Y)},onPromoteMetricToDomain:v&&S?F:void 0,domainId:v,cardId:x.id})]})}function Cr({onEditJoins:t}){const n=s.useEditorStore(d=>d.card),{autoJoinMetadata:a}=s.useDashboardCardQuery(n);if(!(a!=null&&a.autoResolved))return null;const{resolvedJoinPlan:r}=a,i=(r==null?void 0:r.joins)||[];if(i.length===0)return null;const c=d=>!d||d.length===0?"No conditions":d.map(o=>{var u,N,b,h;const x=`${(u=o.source)==null?void 0:u.entityName}.${(N=o.source)==null?void 0:N.name}`,p=`${(b=o.target)==null?void 0:b.entityName}.${(h=o.target)==null?void 0:h.name}`,m=o.operator||"=";return`${x} ${m} ${p}`}).join(" AND "),l=d=>!d.joinKeyGroups||d.joinKeyGroups.length===0?"No conditions defined":d.joinKeyGroups.length===1?c(d.joinKeyGroups[0].keys):d.joinKeyGroups.map((o,x)=>({id:x,operator:o.operator,condition:c(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(ta,{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:"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:i.length})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:i.map((d,o)=>{const x=l(d),p=Array.isArray(x);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:d.source.name}),e.jsx(s.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:d.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:d.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:p?x.map(m=>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:m.condition}),m.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",m.operator,")"]})]},m.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:x})})})]},d.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 Gs={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 Sr({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:i,sortByFields:c,detailFields:l,activeField:d}){var E,f;const[o,x]=I.useState(()=>Gs.getItem("chart-selector-expanded")==="true"),[p,m]=I.useState(!1),u=s.useEditorStore(M=>M.card),N=s.useEditorStore(M=>M.actions.updateCardConfig),b=a.length>0||r.length>0||i.length>0||l.length>0,{data:h,autoJoinMetadata:y}=s.useDashboardCardQuery(u),T=((E=u==null?void 0:u.config)==null?void 0:E.joinPlan)||(y!=null&&y.autoResolved?y.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),C=((f=u==null?void 0:u.dataSource)==null?void 0:f.selectedEntities)||[],B=M=>{N(u.id,{...u==null?void 0:u.config,joinPlan:M}),m(!1)},O=()=>{N(u.id,{...u==null?void 0:u.config,joinPlan:void 0}),m(!1)},L=()=>{m(!1)},g=()=>{m(!0)};I.useEffect(()=>{Gs.setItem("chart-selector-expanded",String(o))},[o]);const w=()=>{x(M=>!M)};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":o}),children:[e.jsx("div",{className:s.cn("overflow-hidden transition-all duration-300 ease-in-out",o?"max-h-[200px] opacity-100":"max-h-0 opacity-0"),children:o&&e.jsx(os,{selectedChart:t,onChartChange:n,variant:"outline"})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:"flex items-center justify-center",children:e.jsx(s.ChartQuickSelector,{selectedChart:t,onChartChange:n,isDropdownExpanded:o,onToggleDropdown:w})})]}),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:b||h}),children:e.jsx(ye.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(Cr,{onEditJoins:g}),e.jsx(Nr,{groupByFields:a,pivotByFields:r,metricsFields:i,sortByFields:c,detailFields:l,activeField:d})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]}),e.jsx(Xs,{open:p,onOpenChange:m,joinPlan:T,availableDataSources:C,onSave:B,onCancel:L,onRemove:O,children:e.jsx("div",{})})]})}function wr({initialFilters:t,availableFields:n}={}){const[a,r]=I.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(L=>L.card.dataSource);const{columns:i,isLoading:c}=s.useColumns(),d=n||i||[],o={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},x=L=>{const g=w=>{if(w.id===L){const E=d[0]||o,f=s.getDataType(E.dataType)==="date";return{...w,conditions:[...w.conditions,{id:`condition-${Date.now()}`,field:E,operator:f?"between":"=",value:f?[]:""}]}}return{...w,groups:w.groups.map(g)}};r(g(a))},p=L=>{const g=w=>{if(w.id===L){const E=d[0]||o,f=s.getDataType(E.dataType)==="date";return{...w,groups:[...w.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:E,operator:f?"between":"=",value:f?[]:""}],groups:[]}]}}return{...w,groups:w.groups.map(g)}};r(g(a))},m=(L,g)=>{const w=E=>E.id===L?{...E,conditions:E.conditions.filter(f=>f.id!==g)}:{...E,groups:E.groups.map(w)};r(w(a))},u=(L,g)=>{const w=E=>E.id===L?{...E,groups:E.groups.filter(f=>f.id!==g)}:{...E,groups:E.groups.map(w)};r(w(a))},N=(L,g,w,E)=>{if(w==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const f=M=>M.id===L?{...M,conditions:M.conditions.map(j=>j.id===g?{...j,[w]:E}:j)}:{...M,groups:M.groups.map(f)};r(f(a))},b=(L,g,w)=>{const E=f=>f.id===L?{...f,conditions:f.conditions.map(M=>M.id===g?{...M,...w}:M)}:{...f,groups:f.groups.map(E)};r(E(a))},h=(L,g)=>{const w=E=>E.id===L?{...E,logicalOperator:g}:{...E,groups:E.groups.map(w)};r(w(a))},y=(L,g)=>{const w=E=>E.id===L?{...E,negate:g}:{...E,groups:E.groups.map(w)};r(w(a))},T=(L,g,w)=>{const E=f=>f.id===L?{...f,conditions:s.arrayMove(f.conditions,g,w)}:{...f,groups:f.groups.map(E)};r(E(a))},C=(L,g,w)=>{const E=f=>f.id===L?{...f,groups:s.arrayMove(f.groups,g,w)}:{...f,groups:f.groups.map(E)};r(E(a))},B=L=>{if(!L||L.conditions.length===0&&L.groups.length===0)return"-- No filters defined";const g=E=>{let f="";typeof E.field=="object"?f=E.field.entityName?`${E.field.entityName}.${E.field.name}`:E.field.name:f=String(E.field);const M=E.operator;let j=E.value;if(E.field.dataType==="string"&&!["in","not in"].includes(E.operator))typeof j=="string"?j=`'${j}'`:Array.isArray(j)&&(j=`'${j.join(", ")}'`);else if(E.field.dataType==="date"||E.field.dataType==="datetime"||E.field.dataType==="timestamp")if(E.operator==="between"&&Array.isArray(j)&&j.length===2){const k=j[0]?`'${j[0]}'`:"NULL",D=j[1]?`'${j[1]}'`:"NULL";return`${f} BETWEEN ${k} AND ${D}`}else if((E.operator==="in"||E.operator==="not in")&&Array.isArray(j)){const k=j.map(D=>D?`'${D}'`:"NULL").join(", ");return`${f} ${M} (${k})`}else typeof j=="string"||j instanceof Date?j=`'${j}'`:Array.isArray(j)&&j.length>0&&(j=`'${j[0]}'`);else if(["in","not in"].includes(E.operator)){let k=[];Array.isArray(j)?k=j.map(D=>typeof D=="string"?`'${D}'`:String(D)):typeof j=="string"?k=j.split(",").map(D=>{const P=D.trim();return E.field.dataType==="string"?`'${P}'`:P}):typeof j=="number"&&(k=[String(j)]),j=`(${k.join(", ")})`}switch(M){case"contains":return typeof j=="string"?`${f} LIKE '%${j.replace(/'/g,"")}'`:`${f} LIKE '%${String(j)}'`;case"startsWith":return typeof j=="string"?`${f} LIKE '${j.replace(/'/g,"")}%'`:`${f} LIKE '${String(j)}%'`;case"endsWith":return typeof j=="string"?`${f} LIKE '%${j.replace(/'/g,"")}'`:`${f} LIKE '%${String(j)}'`;case"isNull":return`${f} IS NULL`;case"isNotNull":return`${f} IS NOT NULL`;default:return`${f} ${M} ${j}`}},w=E=>{const f=E.conditions.map(g),M=E.groups.map(P=>w(P)),j=[...f,...M].filter(Boolean);if(j.length===0)return"";const k=j.join(` ${E.logicalOperator} `),D=j.length>1?`(${k})`:k;return E.negate?`NOT ${D}`:D};return w(L)},O=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:d,isLoading:c,addCondition:x,addGroup:p,removeCondition:m,removeGroup:u,updateCondition:N,updateConditionFields:b,updateGroupOperator:h,updateGroupNegate:y,reorderConditions:T,reorderGroups:C,generateSQLPreview:B,hasAnyFilters:O}}function Tr({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 Er=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function Ir({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:i="w-64"}){const[c,l]=I.useState(!1),d=I.useMemo(()=>{const o={};return a.forEach(x=>{const p=Er(x);o[p]||(o[p]={}),o[p][x.entityId]||(o[p][x.entityId]=[]),o[p][x.entityId].push(x)}),o},[a]);return e.jsxs(s.Popover,{modal:!0,open:c,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":c,className:s.cn("justify-between",!t&&"text-muted-foreground",i),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Tr,{children:[t.entityName,".",t.name]})}):r,e.jsx(s.ChevronsUpDown,{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(d).map(([o,x])=>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(x).map(([p,m])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[s.getEntityIcon(m[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:m[0].entityName})]}),m.map((u,N)=>e.jsxs(s.CommandItem,{value:u.id,onSelect:()=>{n(u),l(!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)===u.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:u.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:u.description&&e.jsx("span",{children:u.description})})]})]},u.id+N))]},`${o}-${p}`))},o))})]})})]})}function us(t){var h;const n=s.useEditorStore(y=>y.card),{authToken:a,tokenProps:r}=s.useSemaphorContext(),i=s.useEditorStore(y=>y.card.config),c=i==null?void 0:i.joinPlan,l={...t,alias:t.name,label:"value",role:"groupby"},d={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},o={...l,role:"sortby",direction:"asc"},x={joinPlan:c,groupByColumns:[l],metricColumns:[d],sortByColumns:[o]},p=((h=n.dataSource)==null?void 0:h.connectionId)||n.connectionId,{data:m,isPending:u,error:N}=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:p,cardConfig:x,cardDataSource:n.dataSource})}catch(y){console.log(t),console.error("error",y)}},enabled:!!p,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((m==null?void 0:m.records)||[]).map(y=>({label:y.value||"BLANK",value:y.value||"BLANK",count:(y==null?void 0:y.count)||0})),isPending:u,error:N}}function kr({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:i}){const[c,l]=as.useState(!1),{filterValues:d}=us(t),o=p=>{a(n.filter(m=>m!==p))},x=p=>{n.includes(p)?a(n.filter(m=>m!==p)):a([...n,p])};return e.jsx("div",{className:s.cn("w-full",i),children:e.jsxs(s.Popover,{open:c,onOpenChange:l,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":c,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(p=>{const m=d.find(u=>u.value===p);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[m==null?void 0:m.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:u=>{u.key==="Enter"&&o(p)},onMouseDown:u=>{u.preventDefault(),u.stopPropagation()},onClick:u=>{u.stopPropagation(),o(p)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},p)}):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:d.map((p,m)=>e.jsxs(s.CommandItem,{onSelect:()=>x(p.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.includes(p.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:p.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p.count})]})]},p.value+m))})]})]})})]})})}function Ar({field:t,value:n,onChange:a,placeholder:r="Select value...",className:i}){const{filterValues:c,isPending:l,error:d}=us(t);return l?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..."]}):d?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:i||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:c.map((o,x)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:o.value,children:o.label},o.value+x))})]})}function Dr({value:t,operator:n,onChange:a,className:r}){var o,x,p;const{tokenProps:i}=s.useSemaphorContext(),c=((x=(o=i==null?void 0:i.params)==null?void 0:o.calendarContext)==null?void 0:x.tz)||((p=i==null?void 0:i.params)==null?void 0:p.timezone),l=I.useMemo(()=>{if(t){if(n==="between"||n==="not between"){if(Array.isArray(t)&&t.length===2){const m=t[0]?new Date(t[0]):void 0,u=t[1]?new Date(t[1]):void 0;if(m&&u)return{from:m,to:u}}}else if(n==="="||n==="!="){if(!Array.isArray(t)&&t){const m=new Date(t);if(!isNaN(m.getTime()))return{from:m,to:m}}}else if(n===">"||n===">="){if(!Array.isArray(t)&&t){const m=new Date(t);if(!isNaN(m.getTime()))return{from:m,to:void 0}}}else if(n==="<"||n==="<="){if(!Array.isArray(t)&&t){const m=new Date(t);if(!isNaN(m.getTime()))return{from:void 0,to:m}}}else if((n==="in"||n==="not in")&&Array.isArray(t)&&t.length>0){const m=new Date(t[0]),u=t.length>1?new Date(t[t.length-1]):m;if(!isNaN(m.getTime()))return{from:m,to:u}}}},[t,n]),d=m=>{if(!m){a(void 0);return}if(m.from&&m.to)a([m.from.toISOString(),m.to.toISOString()]);else if(m.from){const u=new Date(m.from);u.setHours(23,59,59,999),a([m.from.toISOString(),u.toISOString()])}else if(m.to){const u=new Date(m.to);u.setHours(0,0,0,0),a([u.toISOString(),m.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:l,onChange:d,timezone:c,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const Lr=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Mr=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Or=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Fr=["=","!=","isNull","isNotNull"],Rr=["between","isNull","isNotNull"],Br={"=":"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 Us(t){return Br[t]||s.titleCase(t)}function Pr(t){switch(t){case"string":return Mr;case"number":return Or;case"boolean":return Fr;case"date":return Rr;default:return Lr}}function ut({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:i,onRemoveCondition:c,onUpdateGroupOperator:l,availableFields:d,updateConditionFields:o}){const{attributes:x,listeners:p,setNodeRef:m,transform:u,transition:N,isDragging:b}=s.useSortable({id:t.id}),{isPending:h,error:y}=us(t.field),T={transform:s.CSS.Transform.toString(u),transition:N};return e.jsxs("div",{ref:m,style:T,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${b?"z-50 opacity-50":""}`,children:[e.jsx("div",{...x,...p,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:C=>l(a,C),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(Ir,{value:t.field,onValueChange:C=>{const B=C,O=s.getDataType(B.dataType)==="date";o(a,t.id,{field:B,value:"",operator:O?"between":"="})},availableFields:d,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:C=>{C==="in"||C==="not in"?o(a,t.id,{operator:C,value:[]}):C==="isNull"||C==="isNotNull"?o(a,t.id,{operator:C,value:null}):o(a,t.id,{operator:C,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?Us(t.operator):""})}),e.jsx(s.SelectContent,{children:Pr(s.getDataType(t.field.dataType)).map(C=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:C,children:Us(C)},C))})]}),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"?h?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..."]}):y?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(kr,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(C=>typeof C=="string")?t.value:[],onChange:C=>o(a,t.id,{value:C}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input$1,{value:typeof t.value=="string"?t.value:"",onChange:C=>o(a,t.id,{value:C.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Ar,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:C=>o(a,t.id,{value:C}),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:C=>o(a,t.id,{value:C==="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(Dr,{value:t.value,operator:t.operator,onChange:C=>o(a,t.id,{value:C}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:C=>i(a,t.id,"value",C.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:()=>c(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Vr({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:i,onRemoveGroup:c,onUpdateCondition:l,onUpdateField:d,onRemoveCondition:o,onReorderConditions:x,onReorderGroups:p,onAddCondition:m,onAddGroup:u,availableFields:N,renderFilterGroup:b,updateConditionFields:h}){const{attributes:y,listeners:T,setNodeRef:C,transform:B,transition:O,isDragging:L}=s.useSortable({id:t.id}),g={transform:s.CSS.Transform.toString(B),transition:O},w=f=>{const{active:M,over:j}=f;if(j&&M.id!==j.id){const k=t.conditions.findIndex(P=>P.id===M.id),D=t.conditions.findIndex(P=>P.id===j.id);k!==-1&&D!==-1&&x(t.id,k,D)}},E=f=>{const{active:M,over:j}=f;if(j&&M.id!==j.id&&a){const k=t.groups.findIndex(P=>P.id===M.id),D=t.groups.findIndex(P=>P.id===j.id);k!==-1&&D!==-1&&p(a,k,D)}};return e.jsxs("div",{ref:C,style:g,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${L?"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",{...y,...T,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:()=>i(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:f=>r(t.id,f),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&&c(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:w,children:e.jsx(s.SortableContext,{items:t.conditions.map(f=>f.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((f,M)=>e.jsx(ut,{condition:f,index:M,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:l,onUpdateField:d,onRemoveCondition:o,onUpdateGroupOperator:r,availableFields:N,updateConditionFields:h},f.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:E,children:e.jsx(s.SortableContext,{items:t.groups.map(f=>f.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(f=>b(f,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:()=>m(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:()=>u(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function zr({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:i}){const{currentFilters:c,availableFields:l,isLoading:d,addCondition:o,addGroup:x,removeCondition:p,removeGroup:m,updateCondition:u,updateConditionFields:N,updateGroupOperator:b,updateGroupNegate:h,reorderConditions:y,reorderGroups:T,generateSQLPreview:C,hasAnyFilters:B,setCurrentFilters:O}=wr({initialFilters:t,availableFields:n}),L=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[g,w]=I.useState(!1),E=(j,k,D)=>{const P=v=>v.id===j?{...v,conditions:v.conditions.map(A=>A.id===k?{...A,field:D,dataType:D.dataType}:A)}:{...v,groups:v.groups.map(P)};O(P(c))},f=(j,k=0,D)=>k===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:L,collisionDetection:s.closestCenter,onDragEnd:P=>{const{active:v,over:A}=P;if(A&&v.id!==A.id){const S=j.conditions.findIndex(F=>F.id===v.id),R=j.conditions.findIndex(F=>F.id===A.id);S!==-1&&R!==-1&&y(j.id,S,R)}},children:e.jsx(s.SortableContext,{items:j.conditions.map(P=>P.id),strategy:s.verticalListSortingStrategy,children:j.conditions.map((P,v)=>e.jsx(ut,{condition:P,index:v,groupId:j.id,groupLogicalOperator:j.logicalOperator,onUpdateCondition:u,onUpdateField:E,onRemoveCondition:p,onUpdateGroupOperator:b,availableFields:l,updateConditionFields:N},P.id))})}),e.jsx(s.DndContext,{sensors:L,collisionDetection:s.closestCenter,onDragEnd:P=>{const{active:v,over:A}=P;if(A&&v.id!==A.id){const S=j.groups.findIndex(F=>F.id===v.id),R=j.groups.findIndex(F=>F.id===A.id);S!==-1&&R!==-1&&T(j.id,S,R)}},children:e.jsx(s.SortableContext,{items:j.groups.map(P=>P.id),strategy:s.verticalListSortingStrategy,children:j.groups.map(P=>f(P,k+1,j.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(j.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),g&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>x(j.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},j.id):e.jsx(Vr,{group:j,depth:k,parentGroupId:D,onUpdateGroupOperator:b,onUpdateGroupNegate:h,onRemoveGroup:m,onUpdateCondition:u,onUpdateField:E,onRemoveCondition:p,onReorderConditions:y,onReorderGroups:T,onAddCondition:o,onAddGroup:x,availableFields:l,renderFilterGroup:f,updateConditionFields:N},j.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:[d?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):f(c),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:g,onCheckedChange:j=>w(j)}),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:C(c)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:i,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?c:null),children:"Apply Filters"})]})]})}function $r({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:i,isOpen:c,onOpenChange:l}){const d=x=>{a(t,x),l(!1)},o=()=>{r(t),l(!1)};return e.jsxs(s.Dialog,{modal:!1,open:c,onOpenChange:l,children:[c&&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:x=>{x.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(zr,{filters:n,availableFields:i,onSave:d,onCancel:()=>l(!1),onClearAll:o})]})]})}function qr({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var T,C;const[i,c]=I.useState(null),l=s.useEditorStore(B=>B.card),d=s.useEditorStore(B=>B.actions.updateCardConfig),o=(T=l==null?void 0:l.config)==null?void 0:T.joinPlan,x=I.useCallback(B=>B.entityName===s.CALCULATED_FIELD_ENTITY_MARKER||B.entityName==="calculated_fields"||B.qualifiedEntityName==="calculated_fields",[]),p=(C=l==null?void 0:l.dataSource)==null?void 0:C.semanticDomainId,{data:m}=s.useJoinabilityMap(p),u=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],N=I.useCallback(B=>B.startsWith("card-source-")?"source":B.startsWith("card-")?null:B.startsWith("source-")||n.find(O=>O.id===B)?"source":a("groupBy").find(O=>O.id===B)?"groupBy":a("metrics").find(O=>O.id===B)?"metrics":a("pivotBy").find(O=>O.id===B)?"pivotBy":a("sortBy").find(O=>O.id===B)?"sortBy":a("detailColumns").find(O=>O.id===B)?"detailColumns":null,[n,a]),b=I.useCallback(B=>{c(B.active.id)},[]),h=I.useCallback(B=>{var M;const{active:O,over:L}=B;if(!L||!t){c(null);return}const g=O.id,w=L.id,E=N(g),f=N(w)||w;if(f==="sortBy"){if(E==="source"){const j=n.find(D=>D.id===g);if(!j){c(null);return}if(!(a("groupBy").some(D=>D.name===j.name&&D.qualifiedEntityName===j.qualifiedEntityName)||a("metrics").some(D=>D.name===j.name&&D.qualifiedEntityName===j.qualifiedEntityName)||a("detailColumns").some(D=>D.name===j.name&&D.qualifiedEntityName===j.qualifiedEntityName))){c(null);return}}else if(E==="pivotBy"){c(null);return}else if(E!=="groupBy"&&E!=="metrics"&&E!=="sortBy"&&E!=="detailColumns"){c(null);return}}if(E==="source"&&f==="sortBy"){const j=[...n].find(v=>v.id===g);if(!j){c(null);return}const k=a("sortBy");if(s.fieldAlreadyExists(j,k)){c(null);return}const D=s.validateFieldForChartType(j,"sortBy",l.type);if(!D.isValid){s.ue.error("Invalid Field Type",{description:D.reason,position:"top-center",duration:3e3}),c(null);return}const P=s.getNewField(j,"sortBy",k);c(null),r("sortBy",[...k,P]);return}if(E==="source"&&f!=="source"&&f!=="sortBy"){const j=[...n].find(R=>R.id===g);if(!j){c(null);return}const k=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],D=k.filter(R=>!x(R));if(D.length>0){const R=D[0].qualifiedEntityName;if(!R){c(null);return}if(R!==j.qualifiedEntityName&&!x(j)&&j.qualifiedEntityName)if(p&&(m!=null&&m.joinabilityMap)){if(s.calculateFieldState(j,{joinabilityMap:m.joinabilityMap,selectedFields:k,baseEntityName:(M=o==null?void 0:o.baseEntity)==null?void 0:M.name}).state==="unreachable"){s.showJoinRequiredNotification(),c(null);return}}else{if(!o){s.showJoinRequiredNotification(),c(null);return}if(!s.areEntitiesJoined(R,j.qualifiedEntityName,o)){s.showJoinRequiredNotification(),c(null);return}}}const P=a(f);if(s.fieldAlreadyExists(j,P)){c(null);return}const v=s.validateFieldForChartType(j,f,l.type);if(!v.isValid){s.ue.error("Invalid Field Type",{description:v.reason,position:"top-center",duration:3e3}),c(null);return}const A=s.getNewField(j,f,P),S=[...P,A];c(null),r(f,S),f==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(l.type,l.config,d,t,S);return}if(E&&f&&E!=="source"&&f!=="source"&&E!==f){const j=a(E),k=a(f),D=j.find(R=>R.id===g);if(!D){c(null);return}const P=s.validateFieldForChartType(D,f,l.type);if(!P.isValid){s.ue.error("Invalid Field Type",{description:P.reason,position:"top-center",duration:3e3}),c(null);return}const v=s.getNewField(D,f,k);if(c(null),f==="sortBy"){s.fieldAlreadyExists(D,k)||r(f,[...k,v]);return}const A=j.filter(R=>R.id!==g),S=[...k,v];r(E,A),r(f,S),f==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(l.type,l.config,d,t,S);return}if(E&&f&&E===f&&E!=="source"){const j=a(E),k=j.findIndex(P=>P.id===g),D=j.findIndex(P=>P.id===w);if(k!==D){const P=s.arrayMove(j,k,D);r(E,P)}}c(null)},[t,n,a,r,N,o,p,m,x,l.type,d,l.config]),y=i?u.find(B=>B.id===i):null;return{activeId:i,activeField:y,handleDragStart:b,handleDragEnd:h}}function Kr({activeView:t,onViewChange:n,splitViewEnabled:a}){const r=s.useEditorStore(d=>d.card),{config:i}=I.useContext(s.SemaphorContext).tokenProps,c=(i==null?void 0:i.showInfoTab)!==!1,l=()=>a?!1:!["table","pivotTable","aggregateTable","detailTable"].includes(r.type);return e.jsx(s.Tabs,{value:t,onValueChange:d=>n(d),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"}),l()&&e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),r.type!=="kpi"&&c&&e.jsx(s.TabsTrigger,{value:"info",className:"rounded-md transition data-[state=active]:bg-muted",children:"Info"})]})})}const Gr=[{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 Ur(){var o,x;const t=s.useEditorStore(p=>p.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=I.useState(!1),[i,c]=I.useState(""),l=p=>{if(p==="custom"){r(!0);return}r(!1),n(t.id,parseInt(p))},d=p=>{const m=p.target.value;c(m),m&&!isNaN(parseInt(m))&&n(t.id,parseInt(m))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(s.Input,{type:"number",value:i,onChange:d,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((x=(o=t.config)==null?void 0:o.rowLimit)==null?void 0:x.toString())||"100",onValueChange:l,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:Gr.map(p=>e.jsx(s.SelectItem,{value:p.value,children:p.label},p.value))})]})})}function _r({card:t,queryData:n,isLoading:a,isFetching:r,pagination:i,onPaginationChange:c,onSortChange:l,sortState:d,splitViewEnabled:o}){const x=I.useMemo(()=>(n==null?void 0:n.records)||[],[n==null?void 0:n.records]);return!o||["table","pivotTable","aggregateTable","detailTable"].includes(t.type)?e.jsx(ns,{}):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(ns,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:[(a||r)&&(n==null?void 0:n.records)&&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"})}),(n==null?void 0:n.records)&&e.jsx(s.TableVisual,{card:t,data:x,paginationMetadata:i,onPaginationChange:c,isLoading:a||r,onSortChange:l,sortState:d})]})})]})}const Hr="semaphor-split-view-enabled";function Jr(){return Zs(Hr,!0)}function Yr({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onFiltersClick:i,activeCard:c,columns:l,columnsLoading:d,columnsError:o}){var se,ne,_;const x=s.useEditorStore(W=>W.card),p=s.useDashboardStore(W=>W.filterValues),m=s.useDashboardStore(W=>W.selectedSheetId),u=s.useDashboardStore(W=>W.inlineFilterValuesMap[(c==null?void 0:c.id)||""]),{updateCardConfig:N,setCard:b,updateCardInFrame:h,setShowAIDialog:y}=s.useEditorActions(),T=s.useEditorStore(W=>W.showAIDialog),C=s.useDashboardStore(W=>W.isVisualEditing),[B,O]=I.useState(!1),[L,g]=I.useState(!1),[w,E]=I.useState(null),{config:f}=I.useContext(s.SemaphorContext).tokenProps,M=(f==null?void 0:f.showInfoTab)!==!1,[j,k]=Jr();s.useEditorStore(W=>{var le;return!!((le=W.card.customCardPreferences)!=null&&le.url)});const{data:D,errorMessage:P,isLoading:v,isFetching:A,errorSql:S,pagination:R,refetch:F,comparisonMetadata:z}=s.useDashboardCardQuery(c),G=I.useMemo(()=>(D==null?void 0:D.records)||[],[D==null?void 0:D.records]),[V,U]=I.useState(!1);I.useEffect(()=>{A||U(!1)},[A]);const Q=()=>{const W=!j;W&&t==="table"&&n("chart"),k(W)},J=(W,le)=>{const he={...c,paginationConfig:{page:W+1,pageSize:le}};b(he),h(he)};function Z(){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(x.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(p||{},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(c.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",l.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:d?"Loading...":o?"Error loading columns":JSON.stringify(l.slice(0,5),null,2)})]})]})]})}const q=W=>{if(!x.config)return;const le=s.sortStateToSortByColumns(W,x.config.metricColumns,x.config.groupByColumns,x.config.detailColumns);N(x.id,{...x.config,sortByColumns:le})},Y=I.useMemo(()=>{var W;return s.sortByColumnsToSortState((W=x.config)==null?void 0:W.sortByColumns)},[(se=x.config)==null?void 0:se.sortByColumns]);return e.jsxs("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":T&&C}),children:[a&&Z(),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"&&T&&e.jsx("div",{className:"w-[260px]",children:e.jsx(os,{variant:"outline"})}),e.jsx(Kr,{activeView:t,onViewChange:n,splitViewEnabled:j}),e.jsx(s.FilterInfo,{cardId:c.id,cardFilters:(ne=c.config)==null?void 0:ne.filters,cardFilterCount:s.getFilterCount(((_=c.config)==null?void 0:_.filters)||null),onFiltersClick:i,inlineFilters:c.inlineFilters,inlineFilterValues:u,sheetId:m||""}),z&&x.type!=="table"&&e.jsx(s.ComparisonMetadataBadge,{metadata:z,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Ur,{})}),T&&e.jsx(ye.EditorClearButton,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:v||A,onClick:()=>{U(!0),F()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":V})})}),t==="chart"&&e.jsx(s.IconButton,{tooltip:j?"Hide Results Table":"Show Results Table",onClick:Q,children:j?e.jsx(Vt,{className:"size-4"}):e.jsx(ea,{className:"size-4"})}),t==="chart"&&e.jsx(e.Fragment,{children:e.jsx(rt,{})}),!T&&e.jsx(s.IconButton,{onClick:()=>y(!T),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),r&&s.isDevEnv]})]}),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":j&&!["table","pivotTable","aggregateTable","detailTable"].includes(c.type)}),children:e.jsx(_r,{card:c,queryData:D,isLoading:v,isFetching:A,pagination:R,onPaginationChange:J,onSortChange:q,sortState:Y,splitViewEnabled:j})}),t==="table"&&(D==null?void 0:D.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:[(v||A)&&(D==null?void 0:D.records)&&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"})}),e.jsx(s.TableVisual,{card:c,data:G,comparisonMetadata:z,paginationMetadata:R,onPaginationChange:J,isLoading:v||A,onSortChange:q,sortState:Y})]}),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:P?e.jsx(ls,{error:P,errorSql:S,onSendFeedback:()=>{const W=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:x.config,dataSource:c.dataSource,dashboardFilters:p,errorMessage:P,errorSql:S,generatedSql:D==null?void 0:D.sql});E(W),g(!0)},onOpenInEditor:()=>{y(!0),setTimeout(()=>{const W=s.useEditorStore.getState().actions;W.setIsDevMode(!0),W.setCardSql(S||""),setTimeout(()=>{W.setRunSql(!0)},100)},100)}}):(D==null?void 0:D.sql)&&e.jsx(tt,{sql:D.sql,showCardDetails:!0})})})]}),w&&e.jsx(s.FeedbackDialog,{open:L,onOpenChange:g,feedbackData:w})]})]})}function Qr({activeField:t}){const[n,a]=I.useState(!0);return I.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(cs,{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 Wr=()=>{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 i;if((i=r.reason)!=null&&i.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 Xr({column:t,isSelected:n,onSelect:a,availableFields:r,width:i,onWidthChange:c}){var F,z,G;const l=s.useEditorStore(V=>V.card),{updateCardConfig:d,removeGroupByColumn:o,removeMetricColumn:x,updateFilters:p}=s.useEditorActions(),[m,u]=I.useState(!1),[N,b]=I.useState(!1),h=I.useRef(null),y=I.useCallback(V=>{V.preventDefault(),V.stopPropagation(),b(!0),h.current={startX:V.clientX,startWidth:i||150};const U=J=>{if(!h.current)return;const Z=J.clientX-h.current.startX,q=Math.max(80,h.current.startWidth+Z);c==null||c(t.id,q)},Q=()=>{b(!1),h.current=null,document.removeEventListener("mousemove",U),document.removeEventListener("mouseup",Q)};document.addEventListener("mousemove",U),document.addEventListener("mouseup",Q)},[i,t.id,c]),T=(F=l==null?void 0:l.config)==null?void 0:F.filters,C=(z=T==null?void 0:T.conditions)==null?void 0:z.some(V=>V.field.name===t.name&&V.field.qualifiedEntityName===t.qualifiedEntityName),B=V=>{V?p(l.id,V):d(l.id,{filters:void 0})},{attributes:O,listeners:L,setNodeRef:g,transform:w,transition:E,isDragging:f}=s.useSortable({id:t.id}),M={transform:s.CSS.Transform.toString(w),transition:E},j=s.getDataType(t.dataType),k=Zr(j),D=()=>{var Q;const V=((Q=l==null?void 0:l.config)==null?void 0:Q.sortByColumns)||[],U=V.findIndex(J=>J.name===t.name);if(U!==-1){const J=[...V];J[U]={...J[U],direction:"asc"},d(l.id,{sortByColumns:J})}else d(l.id,{sortByColumns:[...V,{...t,id:`sort-${t.id}`,role:"sortby",direction:"asc"}]})},P=()=>{var Q;const V=((Q=l==null?void 0:l.config)==null?void 0:Q.sortByColumns)||[],U=V.findIndex(J=>J.name===t.name);if(U!==-1){const J=[...V];J[U]={...J[U],direction:"desc"},d(l.id,{sortByColumns:J})}else d(l.id,{sortByColumns:[...V,{...t,id:`sort-${t.id}`,role:"sortby",direction:"desc"}]})},v=()=>{var Q;const V=((Q=l==null?void 0:l.config)==null?void 0:Q.groupByColumns)||[];if(!V.some(J=>J.name===t.name)){const J={...t,id:`groupby-${t.id}-${Date.now()}`,role:"groupby"};d(l.id,{groupByColumns:[...V,J]})}},A=V=>{var J;const U=((J=l==null?void 0:l.config)==null?void 0:J.metricColumns)||[];if(!U.some(Z=>Z.name===t.name&&Z.aggregate===V)){const Z={...t,id:`metric-${t.id}-${V}-${Date.now()}`,label:`${V} of ${t.label||t.name}`,role:"metric",aggregate:V};d(l.id,{metricColumns:[...U,Z]})}},S=()=>{t.role==="groupby"?o(l.id,t.id):t.role==="metric"&&x(l.id,t.id)},R={...M,width:i?`${i}px`:void 0,minWidth:i?`${i}px`:"120px"};return e.jsxs("th",{ref:g,style:R,className:s.cn("group relative border-r border-border bg-background px-1 py-0",f&&"opacity-50",n&&"bg-primary/10",N&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...O,...L,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(k,{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,")"]}),C&&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:()=>u(!0),children:[e.jsx(s.Filter,{className:s.cn("mr-2 h-4 w-4",C&&"text-primary")}),C?"Edit Filter":"Filter"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:D,children:[e.jsx(Ft,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(s.DropdownMenuItem,{onClick:P,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:()=>A("SUM"),children:"Sum"}),e.jsx(s.DropdownMenuItem,{onClick:()=>A("AVG"),children:"Average"}),e.jsx(s.DropdownMenuItem,{onClick:()=>A("COUNT"),children:"Count"}),e.jsx(s.DropdownMenuItem,{onClick:()=>A("DISTINCT"),children:"Count Distinct"}),e.jsx(s.DropdownMenuItem,{onClick:()=>A("MIN"),children:"Min"}),e.jsx(s.DropdownMenuItem,{onClick:()=>A("MAX"),children:"Max"})]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:v,children:[e.jsx(rs,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(s.DropdownMenuItem,{disabled:!0,children:[e.jsx(Hs,{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:S,className:"text-destructive focus:text-destructive",children:[e.jsx(s.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:y,className:s.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",N&&"bg-primary")}),e.jsx(dt,{open:m,onOpenChange:u,availableFields:r.length>0?r:[t],existingFilters:T,editingCondition:C?(G=T==null?void 0:T.conditions)==null?void 0:G.find(V=>V.field.name===t.name&&V.field.qualifiedEntityName===t.qualifiedEntityName):void 0,onSave:B})]})}function Zr(t){switch(t){case"number":return s.Hash;case"date":return s.Calendar;case"string":default:return s.Type}}function el({selectedColumn:t,onColumnSelect:n,isLoading:a=!1,sourceFields:r=[]}){var E,f,M,j;const i=s.useEditorStore(k=>k.card),{updateCardConfig:c}=s.useEditorActions(),[l,d]=I.useState(null),[o,x]=I.useState({}),[p,m]=I.useState(!1),u=I.useMemo(()=>{var P,v;const k=((P=i==null?void 0:i.config)==null?void 0:P.groupByColumns)||[],D=((v=i==null?void 0:i.config)==null?void 0:v.metricColumns)||[];return[...k,...D]},[(E=i==null?void 0:i.config)==null?void 0:E.groupByColumns,(f=i==null?void 0:i.config)==null?void 0:f.metricColumns]),N=I.useMemo(()=>{const k=new Set(u.map(D=>`${D.qualifiedEntityName}.${D.name}`));return r.filter(D=>!k.has(`${D.qualifiedEntityName}.${D.name}`))},[r,u]),{data:b,isLoading:h}=s.useDashboardCardQuery(i),y=(b==null?void 0:b.records)||[],T=I.useCallback((k,D)=>{x(P=>({...P,[k]:D}))},[]),C=I.useCallback(k=>{var A,S;const D=s.getDataType(k.dataType),P=((A=i==null?void 0:i.config)==null?void 0:A.groupByColumns)||[],v=((S=i==null?void 0:i.config)==null?void 0:S.metricColumns)||[];if(D==="number"){const R={...k,id:`metric-${k.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};c(i.id,{metricColumns:[...v,R]})}else{const R={...k,id:`groupby-${k.id}-${Date.now()}`,role:"groupby"};c(i.id,{groupByColumns:[...P,R]})}m(!1)},[(M=i==null?void 0:i.config)==null?void 0:M.groupByColumns,(j=i==null?void 0:i.config)==null?void 0:j.metricColumns,i.id,c]),B=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),O=k=>{d(k.active.id)},L=k=>{const{active:D,over:P}=k;if(d(null),!P||D.id===P.id)return;const v=u.findIndex(S=>S.id===D.id),A=u.findIndex(S=>S.id===P.id);if(v!==-1&&A!==-1){const S=s.arrayMove(u,v,A),R=S.filter(z=>z.role==="groupby"),F=S.filter(z=>z.role==="metric");c(i.id,{groupByColumns:R,metricColumns:F})}},g=l?u.find(k=>k.id===l):null,w=k=>{let D="";for(;k>=0;)D=String.fromCharCode(k%26+65)+D,k=Math.floor(k/26)-1;return D};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"})}):u.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:L,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:u.map(k=>k.id),strategy:s.horizontalListSortingStrategy,children:u.map((k,D)=>e.jsx("th",{style:{width:o[k.id]?`${o[k.id]}px`:void 0,minWidth:o[k.id]?`${o[k.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:w(D)},`letter-${k.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:u.map(k=>k.id),strategy:s.horizontalListSortingStrategy,children:u.map(k=>e.jsx(Xr,{column:k,isSelected:(t==null?void 0:t.id)===k.id,onSelect:()=>n(k),availableFields:r,width:o[k.id],onWidthChange:T},k.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(s.Popover,{open:p,onOpenChange:m,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:N.map(k=>{const D=s.getDataType(k.dataType),P=D==="number"?s.Hash:D==="date"?s.Calendar:s.Type;return e.jsxs(s.CommandItem,{value:k.label||k.name,onSelect:()=>C(k),children:[e.jsx(P,{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:k.label||k.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:k.entityName})]})]},k.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:h?e.jsx("tr",{children:e.jsx("td",{colSpan:u.length+2,className:"h-32 text-center",children:e.jsx(s.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):y.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:u.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):y.slice(0,100).map((k,D)=>e.jsxs("tr",{className:s.cn("border-b border-border transition-colors hover:bg-muted/50",D%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:D+1}),u.map(P=>{const v=k[P.name]??k[P.label??""];return e.jsx("td",{style:{width:o[P.id]?`${o[P.id]}px`:void 0,minWidth:o[P.id]?`${o[P.id]}px`:"120px"},className:s.cn("border-r border-border px-3 py-2 text-sm",(t==null?void 0:t.id)===P.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:sl(v,P)})},`${D}-${P.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},D))})]}),e.jsx(s.DragOverlay,{children:g&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:g.label||g.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(y.length,100)," of ",y.length," rows"]}),e.jsxs("span",{children:[u.length," columns"]})]})]})}function sl(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 tl({entityGroups:t,isLoading:n=!1}){var B,O;const a=s.useEditorStore(L=>L.card),{updateCardConfig:r,removeGroupByColumn:i,removeMetricColumn:c}=s.useEditorActions(),[l,d]=I.useState(!0),[o,x]=I.useState(""),[p,m]=I.useState(new Set),u=((B=a==null?void 0:a.config)==null?void 0:B.groupByColumns)||[],N=((O=a==null?void 0:a.config)==null?void 0:O.metricColumns)||[],b=L=>{const g=new Set(p);g.has(L)?g.delete(L):g.add(L),m(g)},h=L=>u.some(g=>g.name===L.name&&g.qualifiedEntityName===L.qualifiedEntityName)||N.some(g=>g.name===L.name&&g.qualifiedEntityName===L.qualifiedEntityName),y=(L,g)=>{if(g)if(s.getDataType(L.dataType)==="number"){const E={...L,id:`metric-${L.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(a.id,{metricColumns:[...N,E]})}else{const E={...L,id:`groupby-${L.id}-${Date.now()}`,role:"groupby"};r(a.id,{groupByColumns:[...u,E]})}else{const w=u.findIndex(f=>f.name===L.name&&f.qualifiedEntityName===L.qualifiedEntityName),E=N.findIndex(f=>f.name===L.name&&f.qualifiedEntityName===L.qualifiedEntityName);w!==-1&&i(a.id,u[w].id),E!==-1&&c(a.id,N[E].id)}},T=L=>{if(!o)return L;const g=o.toLowerCase();return L.filter(w=>w.name.toLowerCase().includes(g)||w.label&&w.label.toLowerCase().includes(g))},C=L=>{switch(s.getDataType(L)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.Type}};return l?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:()=>d(!1),title:"Close panel",children:e.jsx(Yt,{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,{placeholder:"Search columns...",value:o,onChange:L=>x(L.target.value),className:"h-8 pl-8 text-sm"})]})}),(u.length>0||N.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[u.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(rs,{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:u.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:u.map(L=>{const g=C(L.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(g,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:L.label||L.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:()=>i(a.id,L.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},L.id)})})})]}),N.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:N.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:N.map(L=>{const g=C(L.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(g,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:L.label||L.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:L.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:()=>c(a.id,L.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},L.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(L=>{const g=T(L.columns);if(g.length===0)return null;const w=p.has(L.entityId)||o.length>0;return e.jsxs(s.Collapsible,{open:w,onOpenChange:()=>b(L.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",w&&"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:L.label||L.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:g.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:g.map(E=>{const f=C(E.dataType),M=h(E);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:j=>y(E,j),className:"h-3.5 w-3.5"}),e.jsx(f,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:E.label||E.name})]},E.id)})})})]},L.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:()=>d(!0),title:"Open panel",children:e.jsx(Qt,{className:"h-4 w-4"})})})}const al=[{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 nl({value:t,onChange:n,onSubmit:a,onCancel:r,selectedColumn:i,availableColumns:c}){const[l,d]=I.useState(!1),[o,x]=I.useState("column"),p=I.useRef(null);I.useEffect(()=>{const b=h=>{h.key==="Escape"&&t?r():h.key==="Enter"&&t&&!l&&a(t)};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[t,r,a,l]);const m=b=>{const h=`[${b.label||b.name}]`,y=p.current;if(y){const T=y.selectionStart||0,C=y.selectionEnd||0,B=t.slice(0,T)+h+t.slice(C);n(B),setTimeout(()=>{y.setSelectionRange(T+h.length,T+h.length),y.focus()},0)}else n(t+h);d(!1)},u=b=>{const h=p.current;if(h){const y=h.selectionStart||0,T=h.selectionEnd||0,C=t.slice(0,y)+b.syntax+t.slice(T);n(C),setTimeout(()=>{h.setSelectionRange(y+b.name.length+1,y+b.syntax.length-1),h.focus()},0)}else n(t+b.syntax);d(!1)},N=b=>{switch(s.getDataType(b)){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:i?e.jsx("span",{className:"truncate",children:i.label||i.name}):e.jsx("span",{children:"—"})}),e.jsxs(s.Popover,{open:l&&o==="function",onOpenChange:b=>{d(b),b&&x("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(Zt,{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:al.map(b=>e.jsx(s.CommandItem,{value:b.name,onSelect:()=>u(b),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:b.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:b.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:b.syntax})]})},b.name))})]})]})})]}),e.jsxs(s.Popover,{open:l&&o==="column",onOpenChange:b=>{d(b),b&&x("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:c.map(b=>{const h=N(b.dataType);return e.jsxs(s.CommandItem,{value:b.label||b.name,onSelect:()=>m(b),children:[e.jsx(h,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:b.label||b.name})]},b.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(s.Input,{ref:p,value:t,onChange:b=>n(b.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 rl({className:t}){var u,N,b,h;const n=s.useEditorStore(y=>y.card),[a,r]=I.useState(null),[i,c]=I.useState(""),{columns:l=[],columnGroups:d=[],isLoading:o}=s.useColumns();(u=n==null?void 0:n.config)!=null&&u.groupByColumns,(N=n==null?void 0:n.config)!=null&&N.metricColumns,(b=n==null?void 0:n.config)!=null&&b.groupByColumns,(h=n==null?void 0:n.config)!=null&&h.pivotByColumns;const x=y=>{r(y),c(y?`[${y.label||y.name}]`:"")},p=y=>{console.log("Formula submitted:",y),c(""),r(null)},m=()=>{c(""),r(null)};return e.jsxs("div",{className:s.cn("flex h-full w-full flex-col",t),children:[e.jsx(nl,{value:i,onChange:c,onSubmit:p,onCancel:m,selectedColumn:a,availableColumns:l}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(el,{selectedColumn:a,onColumnSelect:x,isLoading:o,sourceFields:l})}),e.jsx(tl,{entityGroups:d,isLoading:o})]})]})}function ll(){var z,G;const[t,n]=I.useState("chart"),[a,r]=I.useState(!1),[i,c]=I.useState(!1),[l,d]=I.useState(!0),o=s.useEditorStore(V=>V.showAIDialog),x=s.useDashboardStore(V=>V.isVisualEditing),{setCardType:p}=s.useEditorActions(),m=s.useEditorStore(V=>V.card.type);I.useEffect(()=>Wr(),[]);const u=V=>{p(V)},N=s.useEditorStore(V=>V.frame),b=s.useEditorStore(V=>V.card);s.useEditorStore(V=>V.activeTabCardId),s.useEditorStore(V=>V.actions.getAvailableFields);const{addCard:h,removeCard:y,updateCard:T,setActiveCard:C,updateFilters:B}=s.useEditorActions(),{columnFields:O=[],scopedFields:L=[],isLoading:g,error:w}=s.useScopedFields(),E=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),f=b,{getFieldsForContainer:M,setFieldsForContainer:j}=s.useFieldManagement(f),{activeField:k,handleDragStart:D,handleDragEnd:P}=qr({activeCardId:N.activeCardId,sourceFields:L,getFieldsForContainer:M,setFieldsForContainer:j}),v=(V,U)=>{U&&B(V,U)},A=V=>{var U;T(V,{config:{...(U=N.cards.find(Q=>Q.id===V))==null?void 0:U.config,filters:void 0}})},S=O,R=V=>{if(!V)return 0;let U=V.conditions.length;return V.groups.forEach(Q=>{U+=R(Q)}),U},F=R(((z=f==null?void 0:f.config)==null?void 0:z.filters)||null);return e.jsxs(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragStart:D,onDragEnd:P,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(et,{isVisible:l,onToggleVisibility:()=>d(!l)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:m==="tableBuilder"?e.jsx(rl,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!o&&e.jsx(Sr,{selectedChart:m,onChartChange:u,groupByFields:M("groupBy"),pivotByFields:M("pivotBy"),metricsFields:M("metrics"),sortByFields:M("sortBy"),detailFields:M("detailColumns"),activeField:k}),e.jsx(Yr,{selectedChart:m,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onFiltersClick:()=>c(!0),filterCount:F,activeCard:f,dataSourceState:b.dataSource||s.EMPTY_DATA_SOURCE,columns:O,columnsLoading:g,columnsError:w,getFieldsForContainer:M,cards:N.cards,activeCardId:N.activeCardId,addCard:h,setActiveCard:C})]})}),!l&&x&&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:()=>d(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),f&&e.jsx($r,{cardId:f.id,filters:((G=f.config)==null?void 0:G.filters)||null,onFiltersChange:v,onClearFilters:A,availableFields:S,isOpen:i,onOpenChange:c}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Qr,{activeField:k||null})})]})}function ol({authToken:t,onSave:n,onClose:a}){const r=I.useRef(null),i=s.useEditorStore(g=>g.showAIDialog),c=s.useEditorStore(g=>g.isDevMode),l=s.useAssistantLayoutStore(g=>g.setFullscreen),d=s.useAssistantLayoutStore(g=>g.setPanelOpen),o=s.useAssistantLayoutStore(g=>g.setContainer),x=s.useAssistantPanel("editor"),p=s.useFullscreenAssistant(),m=s.useAssistantContainer("editor"),u=p==="editor",N=I.useCallback(g=>{o("editor",g)},[o]),{setAuthToken:b}=s.useDashboardActions(),{setShowAIDialog:h,setOnSave:y,setOnClose:T}=s.useEditorActions(),{setActiveAssistantType:C}=s.useAIActions();I.useEffect(()=>{n&&y(n),a&&T(a)},[n,y,a,T]),I.useEffect(()=>{t&&t.accessToken&&b(t)},[t,b]),I.useEffect(()=>{var g,w;i?((g=r.current)==null||g.resize(40),d("editor",!0),C("editor")):((w=r.current)==null||w.resize(0),d("editor",!1),p==="editor"&&l(null),C(null))},[i,d,C,l,p]);function B(g){var w;g<1?(h(!1),d("editor",!1),p==="editor"&&l(null),C(null),(w=r.current)==null||w.resize(0)):(i||(h(!0),C("editor")),x.isOpen||d("editor",!0))}function O(){return e.jsxs(e.Fragment,{children:[e.jsx(et,{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",u&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(or,{})}),e.jsx(s.ResizableHandle,{disabled:!i}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:B,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Ks,{isFullscreen:u,onFullscreenChange:g=>l(g?"editor":null),fullscreenContainer:m})})})]}),e.jsx("div",{ref:N,className:s.cn("absolute inset-0",!u&&"pointer-events-none")})]})]})}function L(){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",u&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(ll,{})}),e.jsx(s.ResizableHandle,{disabled:!i}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:B,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Ks,{isFullscreen:u,onFullscreenChange:g=>l(g?"editor":null),fullscreenContainer:m})})})]}),e.jsx("div",{ref:N,className:s.cn("absolute inset-0",!u&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:c?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:O()}):L()})}function il(){s.useDashboardStore(l=>l.selectedCardId);const t=s.useDashboardStore(l=>l.selectedSheetId),{setIsVisualEditing:n}=s.useDashboardStore(l=>l.actions),a=s.useDashboardStore(l=>l.isVisualEditing),r=s.useDashboardStore(l=>l.actions.updateFrame);function i(l){t&&(r(t,l),n(!1))}function c(){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(ol,{onSave:i,onClose:c})})}exports.default=il;