react-semaphor 0.1.144 → 0.1.145

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 (23) hide show
  1. package/dist/chunks/{dashboard-controls-BG6qR7N2.js → dashboard-controls-CK-TP9Qx.js} +3 -3
  2. package/dist/chunks/{dashboard-controls-_rTkbfKU.js → dashboard-controls-DhQZskp-.js} +1 -1
  3. package/dist/chunks/{dashboard-export-dialog-BXuJmTUR.js → dashboard-export-dialog-D2JI5ycD.js} +1 -1
  4. package/dist/chunks/{dashboard-export-dialog-iH6sg1-y.js → dashboard-export-dialog-DWHbgRQ2.js} +3 -3
  5. package/dist/chunks/{dashboard-json-CV6LkrYw.js → dashboard-json-C_agr9Il.js} +1 -1
  6. package/dist/chunks/{dashboard-json-DZkwc1co.js → dashboard-json-xIJDJDEK.js} +1 -1
  7. package/dist/chunks/{edit-dashboard-visual-tCgjsYbu.js → edit-dashboard-visual-CyWgFWeR.js} +2121 -2125
  8. package/dist/chunks/{edit-dashboard-visual-TG6Ezk2J.js → edit-dashboard-visual-DjlER5zs.js} +13 -13
  9. package/dist/chunks/{editor-action-buttons-Cvg5mWPC.js → editor-action-buttons-CRGFmZT-.js} +2 -2
  10. package/dist/chunks/{editor-action-buttons-Czzj0JBw.js → editor-action-buttons-DPryoh3-.js} +1 -1
  11. package/dist/chunks/{index-Do9K-YLk.js → index-DB87nSG-.js} +4 -4
  12. package/dist/chunks/{index-CPBGb2zs.js → index-DI6ZxR4E.js} +1 -1
  13. package/dist/chunks/{resource-management-panel-Chc6oyIG.js → resource-management-panel-BOJcXuoC.js} +2 -2
  14. package/dist/chunks/{resource-management-panel-DyeJEtOT.js → resource-management-panel-BugB44JB.js} +1 -1
  15. package/dist/chunks/{use-visual-utils-Bf6l2e8y.js → use-visual-utils-CpYOpmej.js} +1 -1
  16. package/dist/chunks/{use-visual-utils-Dtg1I8ku.js → use-visual-utils-jua7RF1E.js} +1 -1
  17. package/dist/dashboard/index.cjs +1 -1
  18. package/dist/dashboard/index.js +1 -1
  19. package/dist/index.cjs +1 -1
  20. package/dist/index.js +4 -4
  21. package/dist/surfboard/index.cjs +1 -1
  22. package/dist/surfboard/index.js +1 -1
  23. 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-CPBGb2zs.js"),D=require("react"),qe=require("./editor-action-buttons-Czzj0JBw.js"),nt=require("react-dom");function at(t){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return a.default=t,Object.freeze(a)}const Ke=at(D);/**
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),s=require("./index-DI6ZxR4E.js"),D=require("react"),qe=require("./editor-action-buttons-DPryoh3-.js"),nt=require("react-dom");function at(t){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return a.default=t,Object.freeze(a)}const Ke=at(D);/**
2
2
  * @license lucide-react v0.453.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -168,21 +168,21 @@
168
168
  *
169
169
  * This source code is licensed under the ISC license.
170
170
  * See the LICENSE file in the root directory of this source tree.
171
- */const At=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 It({initialJoinPlan:t,availableDataSources:a}){const[n,r]=D.useState(t),[l,d]=D.useState(new Set),i=()=>{const w=n.joins.length>0?Math.max(...n.joins.map(y=>y.sequence))+1:1,g={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:w,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,g]}),d(new Set([...l,g.id]))},c=w=>{r({...n,joins:n.joins.filter(g=>g.id!==w)}),d(new Set([...l].filter(g=>g!==w)))},o=(w,g)=>{var b,A,F,E,L;const y=n.joins.find(S=>S.id===w);if(!y)return;const T={...y,...g};if((b=T.source)!=null&&b.name&&((A=T.target)!=null&&A.name)&&T.source.name===T.target.name){s.ue.error("Self-joins are not yet supported",{description:`Joining ${T.source.name} to itself is not currently supported. Please select a different target table.`});return}const M=n.joins.filter(S=>{var V;return S.id!==w&&S.target.name===((V=T.target)==null?void 0:V.name)});if((F=T.target)!=null&&F.name&&M.length>0){s.ue.error("Duplicate join targets are not supported",{description:`The table ${T.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const N=n.joins.map(S=>S.id===w?T:S);if((E=T.source)!=null&&E.name&&((L=T.target)!=null&&L.name)&&T.joinKeyGroups[0].keys.length===0){const S=a.find(G=>{var q;return G.name===((q=T.source)==null?void 0:q.name)}),V=a.find(G=>{var q;return G.name===((q=T.target)==null?void 0:q.name)}),K={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:(V==null?void 0:V.name)||"",entityName:(V==null?void 0:V.name)||"",entityType:(V==null?void 0:V.type)||"table"},operator:"="},H=[...T.joinKeyGroups];H[0]={...H[0],keys:[K]},T.joinKeyGroups=H,N[N.findIndex(G=>G.id===w)]=T}r({...n,joins:N})};return{joinPlan:n,expandedJoins:l,setJoinPlan:r,addJoin:i,removeJoin:c,updateJoin:o,moveJoinUp:w=>{const g=n.joins.findIndex(y=>y.id===w);if(g>0){const y=[...n.joins],T={...y[g]},M={...y[g-1]};y[g]=M,y[g-1]=T,y.forEach((b,A)=>{b.sequence=A+1});const N={...n,joins:y};r(N)}},moveJoinDown:w=>{const g=n.joins.findIndex(y=>y.id===w);if(g<n.joins.length-1){const y=[...n.joins],T={...y[g]},M={...y[g+1]};y[g]=M,y[g+1]=T,y.forEach((b,A)=>{b.sequence=A+1});const N={...n,joins:y};r(N)}},toggleJoinExpansion:w=>{const g=new Set(l);g.has(w)?g.delete(w):g.add(w),d(g)},getAvailableSourceEntities:w=>{if(n.joins.length===0)return a;const g=n.joins.findIndex(T=>T.id===w);if(g===0)return a.filter(T=>T.name===n.baseEntity.name);const y=new Set;return n.baseEntity.name&&y.add(n.baseEntity.name),n.joins.slice(0,g).forEach(T=>{y.add(T.source.name),y.add(T.target.name)}),a.filter(T=>y.has(T.name))},getAvailableTargetEntities:w=>a.filter(g=>g.name!==w),addJoinKeyGroup:w=>{const g=n.joins.find(T=>T.id===w);if(!g)return;const y=[...g.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];o(w,{joinKeyGroups:y})},updateGroupOperator:(w,g,y)=>{const T=n.joins.find(N=>N.id===w);if(!T)return;const M=[...T.joinKeyGroups];M[g]={...M[g],operator:y},o(w,{joinKeyGroups:M})},removeJoinKeyGroup:(w,g)=>{const y=n.joins.find(M=>M.id===w);if(!y)return;const T=[...y.joinKeyGroups];T.splice(g,1),o(w,{joinKeyGroups:T})},addJoinKey:(w,g)=>{const y=n.joins.find(A=>A.id===w);if(!y)return;const T=a.find(A=>A.name===y.source.name),M=a.find(A=>A.name===y.target.name),N=[...y.joinKeyGroups],b={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(T==null?void 0:T.name)||"",entityName:(T==null?void 0:T.name)||"",entityType:(T==null?void 0:T.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:"="};N[g]={...N[g],keys:[...N[g].keys,b]},o(w,{joinKeyGroups:N})},updateJoinKey:(w,g,y,T,M)=>{const N=n.joins.find(L=>L.id===w);if(!N)return;const b=a.find(L=>L.name===N.source.name),A=a.find(L=>L.name===N.target.name),F=[...N.joinKeyGroups],E=F[g].keys[y];T==="sourceColumnName"&&b?F[g].keys[y]={...E,source:{...E.source,name:M}}:T==="targetColumnName"&&A?F[g].keys[y]={...E,target:{...E.target,name:M}}:T==="operator"&&(F[g].keys[y]={...E,operator:M}),o(w,{joinKeyGroups:F})},removeJoinKey:(w,g,y)=>{const T=n.joins.find(N=>N.id===w);if(!T)return;const M=[...T.joinKeyGroups];M[g].keys.splice(y,1),o(w,{joinKeyGroups:M})},generateSQLPreview:()=>{const w=[...n.joins].sort((T,M)=>T.sequence-M.sequence),g=n.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let y=`SELECT *
172
- FROM ${g.name}`;return w.forEach(T=>{const M=a.find(A=>A.name===T.target.name);if(!M)return;const N=T.joinKeyGroups.filter(A=>A.keys&&A.keys.length>0).map(A=>{const F=A.keys.filter(E=>{var L,S,V,K;return((L=E.source)==null?void 0:L.name)&&((S=E.target)==null?void 0:S.name)&&((V=E.source)==null?void 0:V.entityName)&&((K=E.target)==null?void 0:K.entityName)}).map(E=>`${E.source.entityName}.${E.source.name} ${E.operator} ${E.target.entityName}.${E.target.name}`);return F.length>1?`(${F.join(` ${A.operator} `)})`:F[0]}).filter(Boolean),b=N.length>1?N.join(" OR "):N[0]||"condition_here";y+=`
173
- ${T.joinType} JOIN ${M.name}
174
- ON ${b}`}),y},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(T=>!T.source.name||!T.target.name)||n.joins.some(T=>T.joinKeyGroups.some(M=>M.keys.length===0))||n.joins.some(T=>T.joinKeyGroups.some(M=>M.keys.some(N=>!N.source.name||!N.target.name||!N.operator))))}}function Dt({joinPlan:t,availableDataSources:a,onSave:n,onRemove:r,onCancel:l}){const{setCardConfig:d}=s.useEditorActions();s.useEditorStore(N=>N.card.config);const{columnGroups:i}=s.useColumns(),{joinPlan:c,expandedJoins:o,setJoinPlan:u,addJoin:x,removeJoin:h,updateJoin:p,moveJoinUp:k,moveJoinDown:m,toggleJoinExpansion:f,getAvailableSourceEntities:j,getAvailableTargetEntities:C,addJoinKeyGroup:I,updateGroupOperator:O,removeJoinKeyGroup:R,addJoinKey:v,updateJoinKey:w,removeJoinKey:g,generateSQLPreview:y,isValidConfiguration:T}=It({initialJoinPlan:t,availableDataSources:a}),M=N=>{const b=i.find(A=>A.entityName===N);return(b==null?void 0:b.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:c.baseEntity.name,onValueChange:N=>{const b=a.find(A=>A.name===N);u({...c,baseEntity:{connectionId:(b==null?void 0:b.connectionId)||"",connectionType:(b==null?void 0:b.connectionType)||"none",type:(b==null?void 0:b.type)||"table",name:N,database:b==null?void 0:b.database,schema:b==null?void 0:b.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:a.map(N=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:N.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:N.type}),N.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},N.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:y()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",c.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:x,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),c.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:c.joins.map(N=>{const b=a.find(E=>E.name===N.source.name),A=a.find(E=>E.name===N.target.name),F=o.has(N.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:N.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",N.sequence,b&&A&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",b.name," → ",A.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>k(N.id),disabled:N.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>m(N.id),disabled:N.sequence===c.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>f(N.id),children:F?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(N.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),F&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:N.source.name,onValueChange:E=>{const L=a.find(S=>S.name===E);p(N.id,{source:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:E,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:j(N.id).map(E=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:E.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:E.type}),E.name]})},E.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:N.joinType,onValueChange:E=>p(N.id,{joinType:E}),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:N.target.name,onValueChange:E=>{const L=a.find(S=>S.name===E);p(N.id,{target:{connectionId:(L==null?void 0:L.connectionId)||"",connectionType:(L==null?void 0:L.connectionType)||"none",type:(L==null?void 0:L.type)||"table",name:E,database:L==null?void 0:L.database,schema:L==null?void 0:L.schema}})},disabled:!N.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:N.source.name?C(N.source.name).map(E=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:E.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:E.type}),E.name,E.name===N.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},E.name)):[]})]})]})]}),N.source.name&&N.target.name&&b&&A&&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:()=>I(N.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),N.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:N.joinKeyGroups.map((E,L)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{children:["Group ",L+1]}),L>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:E.operator,onValueChange:S=>O(N.id,L,S),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:()=>R(N.id,L),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[E.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:E.keys.map((S,V)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[V>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:E.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:S.source.name,onValueChange:K=>w(N.id,L,V,"sourceColumnName",K),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:M(N.source.name).map(K=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:K.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:K.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:K.dataType})]})},K.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:S.operator,onValueChange:K=>w(N.id,L,V,"operator",K),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:S.target.name,onValueChange:K=>w(N.id,L,V,"targetColumnName",K),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:M(N.target.name).map(K=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:K.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:K.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:K.dataType})]})},K.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>g(N.id,L,V),children:e.jsx(s.X,{className:"size-3.5"})})]},S.id||V))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>v(N.id,L),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},E.id))})]})]})]},N.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>n(c),disabled:!T(),children:"Save"})]})]})}function ws({children:t,open:a,onOpenChange:n,joinPlan:r,availableDataSources:l,onRemove:d,onSave:i,onCancel:c}){return e.jsxs(s.Dialog,{open:a,onOpenChange:n,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(Dt,{joinPlan:r,availableDataSources:l,onSave:i,onCancel:c,onRemove:d})]}),t]})}function Mt({joins:t,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"max-h-[400px] divide-y divide-border overflow-y-auto",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const l=[...t].sort((i,c)=>i.sequence-c.sequence),d=n.find(i=>i.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:d==null?void 0:d.type}),e.jsx("span",{className:"text-xs font-medium",children:d==null?void 0:d.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(i=>{const c=n.find(o=>o.name===i.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:i.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:c==null?void 0:c.type}),e.jsx("span",{className:"text-xs font-medium",children:c==null?void 0:c.name})]})]},i.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((l,d)=>l.sequence-d.sequence).map((l,d)=>{const i=n.find(u=>u.name===l.source.name),c=n.find(u=>u.name===l.target.name),o=l.joinKeyGroups.reduce((u,x)=>u+x.keys.length,0);return e.jsxs("div",{className:"rounded-md bg-muted p-2 text-left",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:d+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto shrink-0 text-xs",children:[o," condition",o>1?"s":""]})]}),e.jsxs("div",{className:"mt-1 truncate pl-1 text-xs text-muted-foreground",children:[i==null?void 0:i.name," → ",c==null?void 0:c.name]})]},l.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function ns({open:t,onOpenChange:a,variant:n="button"}={}){var I,O;const r=s.useEditorStore(R=>R.card),{autoJoinMetadata:l}=s.useDashboardCardQuery(r),d=s.useEditorStore(R=>R.actions.updateCardConfig),i=((I=r==null?void 0:r.config)==null?void 0:I.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[c,o]=D.useState(!1),u=t!==void 0,x=u?t:c,h=u?a:o,p=((O=r==null?void 0:r.dataSource)==null?void 0:O.selectedEntities)||[],k=R=>{d(r.id,{...r==null?void 0:r.config,joinPlan:R}),h(!1)},m=()=>{d(r.id,{...r==null?void 0:r.config,joinPlan:void 0})},f=()=>{h(!1)},j=()=>{const R=[...i.joins].sort((g,y)=>g.sequence-y.sequence),v=i.baseEntity;if(!v.name)return"SELECT * FROM table -- Please select a base entity";let w=`SELECT *
175
- FROM ${v.name}`;return R.forEach(g=>{const y=p.find(N=>N.name===g.target.name);if(!y)return;const T=g.joinKeyGroups.filter(N=>N.keys&&N.keys.length>0).map(N=>{const b=N.keys.filter(A=>{var F,E,L,S;return((F=A.source)==null?void 0:F.name)&&((E=A.target)==null?void 0:E.name)&&((L=A.source)==null?void 0:L.entityName)&&((S=A.target)==null?void 0:S.entityName)}).map(A=>`${A.source.entityName}.${A.source.name} ${A.operator} ${A.target.entityName}.${A.target.name}`);return b.length>1?`(${b.join(` ${N.operator} `)})`:b[0]}).filter(Boolean),M=T.length>1?T.join(" OR "):T[0]||"condition_here";w+=`
176
- ${g.joinType} JOIN ${y.name}
177
- ON ${M}`}),w};if(p.length<2)return null;const C=i.joins.length>0&&e.jsx(s.TooltipContent,{side:"bottom",className:"ml-4 max-w-md overflow-hidden p-0",children:e.jsx(Mt,{joins:i.joins,baseEntityId:i.baseEntity.name,availableDataSources:p,generateSQLPreview:j})});return e.jsxs(e.Fragment,{children:[e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:n==="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:R=>{R.stopPropagation(),h(!0)},children:[e.jsx(s.Link,{className:"h-3 w-3"}),i.joins.length]}):e.jsxs(s.Button,{onClick:()=>h(!0),variant:"outline",className:"w-full bg-muted/50",children:[e.jsx(s.Link,{className:"mr-2 h-3.5 w-3.5"}),i.joins.length===0?"Configure Joins":i.joins.length===1?"Join":"Joins",i.joins.length>0&&e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1.5 text-xs font-medium text-primary-foreground",children:i.joins.length}),(l==null?void 0:l.autoResolved)&&e.jsxs(s.Badge,{variant:"secondary",className:"ml-2 h-5 gap-1 bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:[e.jsx(s.Sparkles,{className:"h-3 w-3"}),"Auto"]})]})}),C]})}),e.jsx(ws,{open:x,onOpenChange:h,joinPlan:i,availableDataSources:p,onSave:k,onCancel:f,onRemove:m,children:e.jsx("div",{})})]})}function Lt({open:t,onOpenChange:a}){const[n,r]=D.useState([]),{updateDataSource:l}=s.useEditorActions(),d=s.useDashboardStore(m=>m.dashboard.aiContext),i=(d==null?void 0:d.selectedEntities)||[];D.useEffect(()=>{t&&r([])},[t]);const c=m=>{r(f=>f.some(C=>C.name===m.name&&C.type===m.type)?f.filter(C=>!(C.name===m.name&&C.type===m.type)):[...f,m])},o=()=>{r([...i])},u=()=>{r([])},x=()=>{if(n.length===0)return;const m=n[0],f=m.connectionId||"",j=m.connectionType||"",I=n.some(R=>R.type==="dataset")?"semanticDomain":"database";l({connectionId:f,connectionType:j,mode:I,selectedEntities:n}),a(!1)},h=m=>"label"in m&&m.label?m.label:m.name,p=m=>{if("description"in m&&m.description)return m.description;const f=[];return m.database&&f.push(m.database),m.schema&&f.push(m.schema),m.name&&f.push(m.name),f.join(".")},k=m=>n.some(f=>f.name===m.name&&f.type===m.type);return i.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:a,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:()=>a(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:a,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:n.length===i.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:n.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[n.length," of ",i.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:i.map((m,f)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",k(m)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:k(m),onCheckedChange:()=>c(m)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:s.getEntityIcon(m.type)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:h(m)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:p(m)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:m.type})]},`${m.type}-${m.name}-${f}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:x,disabled:n.length===0,children:["Select"," ",n.length>0?`(${n.length})`:""]})]})})})]})})}function as({entities:t,title:a}){const{isConsoleMode:n}=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:a??`${t.length} more entities`}),e.jsx("div",{className:"space-y-1",children:t.map((r,l)=>{const d=s.getEntityDetails(r),i=d.find(o=>o.label==="Description"&&o.value),c=d.filter(o=>o.label==="Description"?!1:n?!0:!["Connection","Database","Schema"].includes(o.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(r)}),i&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:i.value})]}),c.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:c.map((o,u)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[o.label,":"]}),e.jsx("span",{className:"font-mono",children:o.value})]},u))})]},`remaining-${r.type}-${r.name}-${l}`)})})]})})}function ks(t,a){const[n,r]=D.useState(()=>{const l=localStorage.getItem(t);return l?JSON.parse(l):a});return D.useEffect(()=>{localStorage.setItem(t,JSON.stringify(n))},[n,t]),[n,r]}function Ts({isVisible:t}){var f,j;const a=s.useEditorStore(C=>C.isDevMode);s.useSyncLegacyEditorState();const[n,r]=D.useState(!1),[l,d]=D.useState(!1),[i,c]=ks("semaphor:data-source-collapsed",!1),o=s.useEditorStore(C=>C.card.dataSource),u=s.useEditorStore(C=>{var I,O;return(O=(I=C.card)==null?void 0:I.config)==null?void 0:O.joinPlan}),{updateDataSource:x}=s.useEditorActions(),h=((f=o==null?void 0:o.selectedEntities)==null?void 0:f.length)||0,p=((j=u==null?void 0:u.joins)==null?void 0:j.length)||0,m={...{connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},...o,selectedEntities:(o==null?void 0:o.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[h===0&&p===0?e.jsx("div",{className:"p-4 px-6",children:e.jsxs(s.Button,{className:"w-full bg-muted/50",variant:"outline",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),"Choose Dataset"]})}):e.jsxs("div",{children:[e.jsxs("div",{className:s.cn("flex cursor-pointer items-center justify-between px-6 pt-3",!i&&"pb-3"),onClick:()=>c(!i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Data Source"}),i&&e.jsxs("div",{className:"flex items-center gap-1.5",onClick:C=>C.stopPropagation(),children:[h>0&&e.jsx(s.TooltipProvider,{delayDuration:100,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"h-5 cursor-pointer gap-1 px-1.5 text-xs transition-colors hover:bg-secondary/80",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"h-3 w-3"}),h]})}),e.jsx(as,{entities:m.selectedEntities,title:`${h} selected ${h===1?"entity":"entities"}`})]})}),p>0&&!a&&e.jsx(ns,{variant:"badge"})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:C=>{C.stopPropagation(),c(!i)},children:i?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:s.cn("overflow-hidden transition-all duration-200 ease-in-out",i?"max-h-0 opacity-0":"max-h-96 opacity-100"),children:[e.jsx("div",{className:"px-6 pb-2",children:e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"w-full bg-muted/50",variant:"outline",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),h===1?"Dataset":"Datasets",e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1.5 text-xs font-medium text-primary-foreground",children:h})]})}),e.jsx(as,{entities:m.selectedEntities,title:`${h} selected ${h===1?"entity":"entities"}`})]})})}),!a&&e.jsx("div",{className:"px-6 pb-2",children:e.jsx(ns,{})})]})]}),e.jsx(s.FieldsSection,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(o==null?void 0:o.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:m}),e.jsx(Lt,{open:l,onOpenChange:d})]})}function He({error:t,errorSql:a,onSendFeedback:n,onOpenInEditor:r,className:l,showFeedbackButton:d=!0,errorTitle:i="Query Error"}){const[c,o]=D.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-destructive/30 bg-destructive/5 p-4",l),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(s.CircleAlert,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-destructive"}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:i}),e.jsxs("div",{className:"relative rounded-md bg-background/60 p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 h-6 w-6 z-10"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"font-mono text-xs text-foreground/80 break-all",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a&&e.jsx(s.Collapsible,{open:c,onOpenChange:o,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:c?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),r&&a&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:r,children:[e.jsx(Cs,{className:"mr-1.5 h-3.5 w-3.5"}),"Open in Editor"]}),d&&n&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:n,children:[e.jsx(s.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),a&&e.jsx(s.Collapsible,{open:c,onOpenChange:o,children:e.jsx(s.CollapsibleContent,{className:"space-y-2",children:e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Error SQL Query"}),e.jsx(s.CopyButton,{text:a,className:"h-6 w-6"})]}),e.jsx("div",{className:"rounded-md bg-background/60 p-2 max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:a,language:"sql"})})]})})})]})]})})}function Es({sql:t,error:a,errorSql:n,onDebugWithAssistant:r}){const l=s.useEditorStore(f=>f.isDevMode),{setIsDevMode:d,setCardSql:i,setRunSql:c}=s.useEditorActions(),[o,u]=D.useState(!1),x=s.useEditorStore(f=>f.card),h=s.useEditorStore(f=>f.frame),p=s.useDashboardStore(f=>f.selectedSheetId),k=s.useDashboardStore(f=>{var j;return(j=f.dashboard)==null?void 0:j.id});function m(f){d(!0),i(f||t),setTimeout(()=>{c(!0)},100)}return e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col pt-4",children:[!l&&t&&!a&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsxs(s.Button,{onClick:()=>m(),variant:"secondary",size:"sm",children:[e.jsx(Cs,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),e.jsxs(s.Button,{onClick:()=>u(!o),variant:"outline",size:"sm",children:[e.jsx(s.Info,{className:"mr-2 h-4 w-4"}),"Card Details"]})]}),o&&e.jsx("div",{className:"mb-3 rounded-lg border border-border bg-muted/30 p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Card Information"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>u(!1),children:e.jsx(ys,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID"}),e.jsx("code",{className:"text-xs font-mono",children:x.id||"N/A"})]}),e.jsx(s.CopyButton,{text:x.id||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Frame ID"}),e.jsx("code",{className:"text-xs font-mono",children:h.id||"N/A"})]}),e.jsx(s.CopyButton,{text:h.id||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Sheet ID"}),e.jsx("code",{className:"text-xs font-mono",children:p||"N/A"})]}),e.jsx(s.CopyButton,{text:p||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Dashboard ID"}),e.jsx("code",{className:"text-xs font-mono",children:k||"N/A"})]}),e.jsx(s.CopyButton,{text:k||"",className:"h-6 w-6"})]})]})]})}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-auto text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(He,{error:a,errorSql:n,showFeedbackButton:!1,onOpenInEditor:()=>m(n)}),!a&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute right-2 top-2 z-10",children:e.jsx(s.CopyButton,{text:t,className:"h-6 w-6"})}),e.jsx(s.CodeHighlighter,{code:t,language:"sql"})]})})]}),a&&r&&e.jsx("div",{className:"mt-3",children:e.jsxs(s.Button,{onClick:r,size:"sm",variant:"outline",children:[e.jsx(ht,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})})]})}function Ft({sql:t,error:a,errorSql:n,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:a?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(ys,{className:"h-4 w-4 text-red-500"}):e.jsx(s.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(s.HoverCardContent,{align:"start",className:"flex w-[700px]",children:e.jsx(Es,{errorSql:n,sql:t,error:a,onDebugWithAssistant:r})})]})}function Ot(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 As(t){const{theme:a}=s.useTheme(),n=s.useDashboardStore(f=>f.theme),r=s.useEditorStore(f=>f.frame),l=s.useEditorStore(f=>f.card),d=s.useEditorStore(f=>f.activeTabCardId),i=s.Le(),{refetch:c}=s.useDashboardCardQuery(l),{updateCardTab:o,setRunSql:u}=s.useEditorActions(),x=D.useRef(),h=D.useRef({}),p=r.cards.find(f=>f.id===d),k=D.useCallback(()=>{let f="";return t==="python"&&(f=(p==null?void 0:p.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(f=(p==null?void 0:p.sql)||""),f},[t,p]);D.useEffect(()=>{if(d&&l.id&&l.id!==d){if(x.current&&i){const f=x.current.getModel();f&&(h.current[l.id]=f);let j=h.current[d];if(!j){const C=k();j=i.editor.createModel(C,t),h.current[d]=j}x.current.setModel(j)}o(d,l),u(!0)}},[d,l,o,i,u,t,k]),D.useEffect(()=>{if(!i)return;const f=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",j=n==="system"?f:n;i.editor.defineTheme("default",{base:j==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":j==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),i.editor.setTheme("default")},[a,n,i]),D.useEffect(()=>{const f=x.current;f&&i&&l&&f.addCommand(i.KeyMod.Shift|i.KeyCode.Enter,function(){return c(),!1})},[i,c,l]);function m(f,j){if(x.current=f,!h.current[l.id]){const C=f.getModel(),I=k();h.current[l.id]=C||(j==null?void 0:j.editor.createModel(I,t))||f.getModel()}f.setModel(h.current[l.id])}return{handleEditorDidMount:m}}function Rt(){const t=s.useEditorStore(i=>i.card.sql),a=s.useEditorStore(i=>i.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=As("sql");function d(i){n(i),s.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:d,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function Bt(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=As("python");function r(l){a(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function Vt(){const t=s.useQueryClient(),{isConsoleMode:a}=s.useDashboardPreferences(),[n,r]=D.useState(!1);s.useEditorStore(P=>P.frame);const l=s.useEditorStore(P=>P.card);s.useEditorStore(P=>P.isShowingVisual),s.useEditorStore(P=>P.selectedConnectionId),s.useEditorStore(P=>P.tempQueryData),s.useEditorStore(P=>P.selectedDatabaseName),s.useEditorStore(P=>P.selectedDatamodelId),s.useEditorStore(P=>P.selectedSchemaName);const d=s.useEditorStore(P=>P.showAIDialog);s.useEditorStore(P=>P.selectedTableName);const i=s.useEditorStore(P=>{var z;return(z=P==null?void 0:P.card)==null?void 0:z.sql}),c=s.useEditorStore(P=>{var z;return(z=P==null?void 0:P.card)==null?void 0:z.python}),{cardFilterValues:o}=s.useCardFilterValues((l==null?void 0:l.id)??""),u=s.useDashboardStore(P=>P.inlineFilterValuesMap[(l==null?void 0:l.id)??""]),x=D.useRef(!0),{setCardCustomCfg:h,setQueryResultColumns:p,setCardSql:k,setTempQueryData:m,setPythonStdOut:f,setCardPreferences:j,setCardType:C,setCardPython:I,runAssistant:O,setShowAIDialog:R,setCard:v,updateCardInFrame:w}=s.useEditorActions();s.useEditorStore(P=>P.onSave),s.useEditorStore(P=>P.onClose),s.useEditorStore(P=>P.actions.setSqlGen);const g=s.useEditorStore(P=>P.runSql),y=s.useEditorStore(P=>P.actions.setRunSql),T=s.useEditorStore(P=>P.actions.setIsSqlRunning),{data:M,isLoading:N,isFetching:b,isSuccess:A,isError:F,error:E,errorSql:L,queryKey:S,refetch:V,errorMessage:K}=s.useDashboardCardQuery(l);D.useEffect(()=>{if(M&&(M.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),f((M==null?void 0:M.output)||""),M.records.length>0)){const{dimensionKeys:P}=s.getKeys(M.records);p(P)}},[M,p,f]),D.useEffect(()=>{(N||b)&&T(!0),(F||A)&&T(!1),F&&(p([]),f(""))},[N,b,M,f,F,A,T,p,E]),D.useEffect(()=>{g&&(t.getQueryData(S)||V(),y(!1))},[g,V,y,S,t]),D.useEffect(()=>{if(x.current){x.current=!1;return}V()},[u,V]);async function H(){const P=`Can you help me debug this query?
171
+ */const At=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 It({initialJoinPlan:t,availableDataSources:a}){const[n,r]=D.useState(t),[l,d]=D.useState(new Set),i=()=>{const k=n.joins.length>0?Math.max(...n.joins.map(j=>j.sequence))+1:1,g={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:k,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,g]}),d(new Set([...l,g.id]))},c=k=>{r({...n,joins:n.joins.filter(g=>g.id!==k)}),d(new Set([...l].filter(g=>g!==k)))},o=(k,g)=>{var v,A,F,E,M;const j=n.joins.find(S=>S.id===k);if(!j)return;const T={...j,...g};if((v=T.source)!=null&&v.name&&((A=T.target)!=null&&A.name)&&T.source.name===T.target.name){s.ue.error("Self-joins are not yet supported",{description:`Joining ${T.source.name} to itself is not currently supported. Please select a different target table.`});return}const L=n.joins.filter(S=>{var P;return S.id!==k&&S.target.name===((P=T.target)==null?void 0:P.name)});if((F=T.target)!=null&&F.name&&L.length>0){s.ue.error("Duplicate join targets are not supported",{description:`The table ${T.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const N=n.joins.map(S=>S.id===k?T:S);if((E=T.source)!=null&&E.name&&((M=T.target)!=null&&M.name)&&T.joinKeyGroups[0].keys.length===0){const S=a.find(V=>{var G;return V.name===((G=T.source)==null?void 0:G.name)}),P=a.find(V=>{var G;return V.name===((G=T.target)==null?void 0:G.name)}),K={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:(P==null?void 0:P.name)||"",entityName:(P==null?void 0:P.name)||"",entityType:(P==null?void 0:P.type)||"table"},operator:"="},H=[...T.joinKeyGroups];H[0]={...H[0],keys:[K]},T.joinKeyGroups=H,N[N.findIndex(V=>V.id===k)]=T}r({...n,joins:N})};return{joinPlan:n,expandedJoins:l,setJoinPlan:r,addJoin:i,removeJoin:c,updateJoin:o,moveJoinUp:k=>{const g=n.joins.findIndex(j=>j.id===k);if(g>0){const j=[...n.joins],T={...j[g]},L={...j[g-1]};j[g]=L,j[g-1]=T,j.forEach((v,A)=>{v.sequence=A+1});const N={...n,joins:j};r(N)}},moveJoinDown:k=>{const g=n.joins.findIndex(j=>j.id===k);if(g<n.joins.length-1){const j=[...n.joins],T={...j[g]},L={...j[g+1]};j[g]=L,j[g+1]=T,j.forEach((v,A)=>{v.sequence=A+1});const N={...n,joins:j};r(N)}},toggleJoinExpansion:k=>{const g=new Set(l);g.has(k)?g.delete(k):g.add(k),d(g)},getAvailableSourceEntities:k=>{if(n.joins.length===0)return a;const g=n.joins.findIndex(T=>T.id===k);if(g===0)return a.filter(T=>T.name===n.baseEntity.name);const j=new Set;return n.baseEntity.name&&j.add(n.baseEntity.name),n.joins.slice(0,g).forEach(T=>{j.add(T.source.name),j.add(T.target.name)}),a.filter(T=>j.has(T.name))},getAvailableTargetEntities:k=>a.filter(g=>g.name!==k),addJoinKeyGroup:k=>{const g=n.joins.find(T=>T.id===k);if(!g)return;const j=[...g.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];o(k,{joinKeyGroups:j})},updateGroupOperator:(k,g,j)=>{const T=n.joins.find(N=>N.id===k);if(!T)return;const L=[...T.joinKeyGroups];L[g]={...L[g],operator:j},o(k,{joinKeyGroups:L})},removeJoinKeyGroup:(k,g)=>{const j=n.joins.find(L=>L.id===k);if(!j)return;const T=[...j.joinKeyGroups];T.splice(g,1),o(k,{joinKeyGroups:T})},addJoinKey:(k,g)=>{const j=n.joins.find(A=>A.id===k);if(!j)return;const T=a.find(A=>A.name===j.source.name),L=a.find(A=>A.name===j.target.name),N=[...j.joinKeyGroups],v={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(T==null?void 0:T.name)||"",entityName:(T==null?void 0:T.name)||"",entityType:(T==null?void 0:T.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(L==null?void 0:L.name)||"",entityName:(L==null?void 0:L.name)||"",entityType:(L==null?void 0:L.type)||"table"},operator:"="};N[g]={...N[g],keys:[...N[g].keys,v]},o(k,{joinKeyGroups:N})},updateJoinKey:(k,g,j,T,L)=>{const N=n.joins.find(M=>M.id===k);if(!N)return;const v=a.find(M=>M.name===N.source.name),A=a.find(M=>M.name===N.target.name),F=[...N.joinKeyGroups],E=F[g].keys[j];T==="sourceColumnName"&&v?F[g].keys[j]={...E,source:{...E.source,name:L}}:T==="targetColumnName"&&A?F[g].keys[j]={...E,target:{...E.target,name:L}}:T==="operator"&&(F[g].keys[j]={...E,operator:L}),o(k,{joinKeyGroups:F})},removeJoinKey:(k,g,j)=>{const T=n.joins.find(N=>N.id===k);if(!T)return;const L=[...T.joinKeyGroups];L[g].keys.splice(j,1),o(k,{joinKeyGroups:L})},generateSQLPreview:()=>{const k=[...n.joins].sort((T,L)=>T.sequence-L.sequence),g=n.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let j=`SELECT *
172
+ FROM ${g.name}`;return k.forEach(T=>{const L=a.find(A=>A.name===T.target.name);if(!L)return;const N=T.joinKeyGroups.filter(A=>A.keys&&A.keys.length>0).map(A=>{const F=A.keys.filter(E=>{var M,S,P,K;return((M=E.source)==null?void 0:M.name)&&((S=E.target)==null?void 0:S.name)&&((P=E.source)==null?void 0:P.entityName)&&((K=E.target)==null?void 0:K.entityName)}).map(E=>`${E.source.entityName}.${E.source.name} ${E.operator} ${E.target.entityName}.${E.target.name}`);return F.length>1?`(${F.join(` ${A.operator} `)})`:F[0]}).filter(Boolean),v=N.length>1?N.join(" OR "):N[0]||"condition_here";j+=`
173
+ ${T.joinType} JOIN ${L.name}
174
+ ON ${v}`}),j},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(T=>!T.source.name||!T.target.name)||n.joins.some(T=>T.joinKeyGroups.some(L=>L.keys.length===0))||n.joins.some(T=>T.joinKeyGroups.some(L=>L.keys.some(N=>!N.source.name||!N.target.name||!N.operator))))}}function Dt({joinPlan:t,availableDataSources:a,onSave:n,onRemove:r,onCancel:l}){const{setCardConfig:d}=s.useEditorActions();s.useEditorStore(N=>N.card.config);const{columnGroups:i}=s.useColumns(),{joinPlan:c,expandedJoins:o,setJoinPlan:u,addJoin:x,removeJoin:h,updateJoin:p,moveJoinUp:w,moveJoinDown:m,toggleJoinExpansion:f,getAvailableSourceEntities:b,getAvailableTargetEntities:C,addJoinKeyGroup:I,updateGroupOperator:O,removeJoinKeyGroup:R,addJoinKey:y,updateJoinKey:k,removeJoinKey:g,generateSQLPreview:j,isValidConfiguration:T}=It({initialJoinPlan:t,availableDataSources:a}),L=N=>{const v=i.find(A=>A.entityName===N);return(v==null?void 0:v.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:c.baseEntity.name,onValueChange:N=>{const v=a.find(A=>A.name===N);u({...c,baseEntity:{connectionId:(v==null?void 0:v.connectionId)||"",connectionType:(v==null?void 0:v.connectionType)||"none",type:(v==null?void 0:v.type)||"table",name:N,database:v==null?void 0:v.database,schema:v==null?void 0:v.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:a.map(N=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:N.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:N.type}),N.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},N.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:j()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",c.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:x,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),c.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:c.joins.map(N=>{const v=a.find(E=>E.name===N.source.name),A=a.find(E=>E.name===N.target.name),F=o.has(N.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:N.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",N.sequence,v&&A&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",v.name," → ",A.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>w(N.id),disabled:N.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>m(N.id),disabled:N.sequence===c.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>f(N.id),children:F?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(N.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),F&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:N.source.name,onValueChange:E=>{const M=a.find(S=>S.name===E);p(N.id,{source:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:E,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:b(N.id).map(E=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:E.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:E.type}),E.name]})},E.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:N.joinType,onValueChange:E=>p(N.id,{joinType:E}),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:N.target.name,onValueChange:E=>{const M=a.find(S=>S.name===E);p(N.id,{target:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:E,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},disabled:!N.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:N.source.name?C(N.source.name).map(E=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:E.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:E.type}),E.name,E.name===N.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},E.name)):[]})]})]})]}),N.source.name&&N.target.name&&v&&A&&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:()=>I(N.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),N.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:N.joinKeyGroups.map((E,M)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{children:["Group ",M+1]}),M>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(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:E.operator,onValueChange:S=>O(N.id,M,S),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:()=>R(N.id,M),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[E.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:E.keys.map((S,P)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[P>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:E.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:S.source.name,onValueChange:K=>k(N.id,M,P,"sourceColumnName",K),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:L(N.source.name).map(K=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:K.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:K.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:K.dataType})]})},K.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:S.operator,onValueChange:K=>k(N.id,M,P,"operator",K),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:S.target.name,onValueChange:K=>k(N.id,M,P,"targetColumnName",K),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:L(N.target.name).map(K=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:K.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:K.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:K.dataType})]})},K.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>g(N.id,M,P),children:e.jsx(s.X,{className:"size-3.5"})})]},S.id||P))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>y(N.id,M),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},E.id))})]})]})]},N.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),l()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:l,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>n(c),disabled:!T(),children:"Save"})]})]})}function ws({children:t,open:a,onOpenChange:n,joinPlan:r,availableDataSources:l,onRemove:d,onSave:i,onCancel:c}){return e.jsxs(s.Dialog,{open:a,onOpenChange:n,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(Dt,{joinPlan:r,availableDataSources:l,onSave:i,onCancel:c,onRemove:d})]}),t]})}function Mt({joins:t,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"max-h-[400px] divide-y divide-border overflow-y-auto",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const l=[...t].sort((i,c)=>i.sequence-c.sequence),d=n.find(i=>i.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:d==null?void 0:d.type}),e.jsx("span",{className:"text-xs font-medium",children:d==null?void 0:d.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),l.map(i=>{const c=n.find(o=>o.name===i.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:i.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:c==null?void 0:c.type}),e.jsx("span",{className:"text-xs font-medium",children:c==null?void 0:c.name})]})]},i.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((l,d)=>l.sequence-d.sequence).map((l,d)=>{const i=n.find(u=>u.name===l.source.name),c=n.find(u=>u.name===l.target.name),o=l.joinKeyGroups.reduce((u,x)=>u+x.keys.length,0);return e.jsxs("div",{className:"rounded-md bg-muted p-2 text-left",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:d+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:l.joinType}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto shrink-0 text-xs",children:[o," condition",o>1?"s":""]})]}),e.jsxs("div",{className:"mt-1 truncate pl-1 text-xs text-muted-foreground",children:[i==null?void 0:i.name," → ",c==null?void 0:c.name]})]},l.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function ns({open:t,onOpenChange:a,variant:n="button"}={}){var I,O;const r=s.useEditorStore(R=>R.card),{autoJoinMetadata:l}=s.useDashboardCardQuery(r),d=s.useEditorStore(R=>R.actions.updateCardConfig),i=((I=r==null?void 0:r.config)==null?void 0:I.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[c,o]=D.useState(!1),u=t!==void 0,x=u?t:c,h=u?a:o,p=((O=r==null?void 0:r.dataSource)==null?void 0:O.selectedEntities)||[],w=R=>{d(r.id,{...r==null?void 0:r.config,joinPlan:R}),h(!1)},m=()=>{d(r.id,{...r==null?void 0:r.config,joinPlan:void 0})},f=()=>{h(!1)},b=()=>{const R=[...i.joins].sort((g,j)=>g.sequence-j.sequence),y=i.baseEntity;if(!y.name)return"SELECT * FROM table -- Please select a base entity";let k=`SELECT *
175
+ FROM ${y.name}`;return R.forEach(g=>{const j=p.find(N=>N.name===g.target.name);if(!j)return;const T=g.joinKeyGroups.filter(N=>N.keys&&N.keys.length>0).map(N=>{const v=N.keys.filter(A=>{var F,E,M,S;return((F=A.source)==null?void 0:F.name)&&((E=A.target)==null?void 0:E.name)&&((M=A.source)==null?void 0:M.entityName)&&((S=A.target)==null?void 0:S.entityName)}).map(A=>`${A.source.entityName}.${A.source.name} ${A.operator} ${A.target.entityName}.${A.target.name}`);return v.length>1?`(${v.join(` ${N.operator} `)})`:v[0]}).filter(Boolean),L=T.length>1?T.join(" OR "):T[0]||"condition_here";k+=`
176
+ ${g.joinType} JOIN ${j.name}
177
+ ON ${L}`}),k};if(p.length<2)return null;const C=i.joins.length>0&&e.jsx(s.TooltipContent,{side:"bottom",className:"ml-4 max-w-md overflow-hidden p-0",children:e.jsx(Mt,{joins:i.joins,baseEntityId:i.baseEntity.name,availableDataSources:p,generateSQLPreview:b})});return e.jsxs(e.Fragment,{children:[e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:n==="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:R=>{R.stopPropagation(),h(!0)},children:[e.jsx(s.Link,{className:"h-3 w-3"}),i.joins.length]}):e.jsxs(s.Button,{onClick:()=>h(!0),variant:"outline",className:"w-full bg-muted/50",children:[e.jsx(s.Link,{className:"mr-2 h-3.5 w-3.5"}),i.joins.length===0?"Configure Joins":i.joins.length===1?"Join":"Joins",i.joins.length>0&&e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1.5 text-xs font-medium text-primary-foreground",children:i.joins.length}),(l==null?void 0:l.autoResolved)&&e.jsxs(s.Badge,{variant:"secondary",className:"ml-2 h-5 gap-1 bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:[e.jsx(s.Sparkles,{className:"h-3 w-3"}),"Auto"]})]})}),C]})}),e.jsx(ws,{open:x,onOpenChange:h,joinPlan:i,availableDataSources:p,onSave:w,onCancel:f,onRemove:m,children:e.jsx("div",{})})]})}function Lt({open:t,onOpenChange:a}){const[n,r]=D.useState([]),{updateDataSource:l}=s.useEditorActions(),d=s.useDashboardStore(m=>m.dashboard.aiContext),i=(d==null?void 0:d.selectedEntities)||[];D.useEffect(()=>{t&&r([])},[t]);const c=m=>{r(f=>f.some(C=>C.name===m.name&&C.type===m.type)?f.filter(C=>!(C.name===m.name&&C.type===m.type)):[...f,m])},o=()=>{r([...i])},u=()=>{r([])},x=()=>{if(n.length===0)return;const m=n[0],f=m.connectionId||"",b=m.connectionType||"",I=n.some(R=>R.type==="dataset")?"semanticDomain":"database";l({connectionId:f,connectionType:b,mode:I,selectedEntities:n}),a(!1)},h=m=>"label"in m&&m.label?m.label:m.name,p=m=>{if("description"in m&&m.description)return m.description;const f=[];return m.database&&f.push(m.database),m.schema&&f.push(m.schema),m.name&&f.push(m.name),f.join(".")},w=m=>n.some(f=>f.name===m.name&&f.type===m.type);return i.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:a,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:()=>a(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:a,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:n.length===i.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:n.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[n.length," of ",i.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:i.map((m,f)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",w(m)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:w(m),onCheckedChange:()=>c(m)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:s.getEntityIcon(m.type)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:h(m)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:p(m)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:m.type})]},`${m.type}-${m.name}-${f}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:x,disabled:n.length===0,children:["Select"," ",n.length>0?`(${n.length})`:""]})]})})})]})})}function as({entities:t,title:a}){const{isConsoleMode:n}=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:a??`${t.length} more entities`}),e.jsx("div",{className:"space-y-1",children:t.map((r,l)=>{const d=s.getEntityDetails(r),i=d.find(o=>o.label==="Description"&&o.value),c=d.filter(o=>o.label==="Description"?!1:n?!0:!["Connection","Database","Schema"].includes(o.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(r)}),i&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:i.value})]}),c.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:c.map((o,u)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[o.label,":"]}),e.jsx("span",{className:"font-mono",children:o.value})]},u))})]},`remaining-${r.type}-${r.name}-${l}`)})})]})})}function ks(t,a){const[n,r]=D.useState(()=>{const l=localStorage.getItem(t);return l?JSON.parse(l):a});return D.useEffect(()=>{localStorage.setItem(t,JSON.stringify(n))},[n,t]),[n,r]}function Ts({isVisible:t}){var f,b;const a=s.useEditorStore(C=>C.isDevMode);s.useSyncLegacyEditorState();const[n,r]=D.useState(!1),[l,d]=D.useState(!1),[i,c]=ks("semaphor:data-source-collapsed",!1),o=s.useEditorStore(C=>C.card.dataSource),u=s.useEditorStore(C=>{var I,O;return(O=(I=C.card)==null?void 0:I.config)==null?void 0:O.joinPlan}),{updateDataSource:x}=s.useEditorActions(),h=((f=o==null?void 0:o.selectedEntities)==null?void 0:f.length)||0,p=((b=u==null?void 0:u.joins)==null?void 0:b.length)||0,m={...{connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},...o,selectedEntities:(o==null?void 0:o.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[h===0&&p===0?e.jsx("div",{className:"p-4 px-6",children:e.jsxs(s.Button,{className:"w-full bg-muted/50",variant:"outline",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),"Choose Dataset"]})}):e.jsxs("div",{children:[e.jsxs("div",{className:s.cn("flex cursor-pointer items-center justify-between px-6 pt-3",!i&&"pb-3"),onClick:()=>c(!i),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Data Source"}),i&&e.jsxs("div",{className:"flex items-center gap-1.5",onClick:C=>C.stopPropagation(),children:[h>0&&e.jsx(s.TooltipProvider,{delayDuration:100,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"h-5 cursor-pointer gap-1 px-1.5 text-xs transition-colors hover:bg-secondary/80",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"h-3 w-3"}),h]})}),e.jsx(as,{entities:m.selectedEntities,title:`${h} selected ${h===1?"entity":"entities"}`})]})}),p>0&&!a&&e.jsx(ns,{variant:"badge"})]})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:C=>{C.stopPropagation(),c(!i)},children:i?e.jsx(s.ChevronDown,{className:"h-4 w-4"}):e.jsx(s.ChevronUp,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:s.cn("overflow-hidden transition-all duration-200 ease-in-out",i?"max-h-0 opacity-0":"max-h-96 opacity-100"),children:[e.jsx("div",{className:"px-6 pb-2",children:e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{className:"w-full bg-muted/50",variant:"outline",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),h===1?"Dataset":"Datasets",e.jsx("span",{className:"ml-2 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1.5 text-xs font-medium text-primary-foreground",children:h})]})}),e.jsx(as,{entities:m.selectedEntities,title:`${h} selected ${h===1?"entity":"entities"}`})]})})}),!a&&e.jsx("div",{className:"px-6 pb-2",children:e.jsx(ns,{})})]})]}),e.jsx(s.FieldsSection,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(o==null?void 0:o.selectedEntities)||[],dialogMode:"dataSource",open:n,onOpenChange:r,dataSource:m}),e.jsx(Lt,{open:l,onOpenChange:d})]})}function He({error:t,errorSql:a,onSendFeedback:n,onOpenInEditor:r,className:l,showFeedbackButton:d=!0,errorTitle:i="Query Error"}){const[c,o]=D.useState(!1);return e.jsx("div",{className:s.cn("rounded-lg border border-destructive/30 bg-destructive/5 p-4",l),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(s.CircleAlert,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-destructive"}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:i}),e.jsxs("div",{className:"relative rounded-md bg-background/60 p-3",children:[e.jsx(s.CopyButton,{text:t,className:"absolute right-2 top-2 h-6 w-6 z-10"}),e.jsx("div",{className:"max-h-40 overflow-auto pr-10",children:e.jsx("p",{className:"font-mono text-xs text-foreground/80 break-all",children:t})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a&&e.jsx(s.Collapsible,{open:c,onOpenChange:o,children:e.jsx(s.CollapsibleTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-8",children:c?e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronUp,{className:"mr-1.5 h-3.5 w-3.5"}),"Hide Details"]}):e.jsxs(e.Fragment,{children:[e.jsx(s.ChevronDown,{className:"mr-1.5 h-3.5 w-3.5"}),"Show Details"]})})})}),r&&a&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:r,children:[e.jsx(Cs,{className:"mr-1.5 h-3.5 w-3.5"}),"Open in Editor"]}),d&&n&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8",onClick:n,children:[e.jsx(s.MessageSquareWarning,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Feedback"]})]}),a&&e.jsx(s.Collapsible,{open:c,onOpenChange:o,children:e.jsx(s.CollapsibleContent,{className:"space-y-2",children:e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Error SQL Query"}),e.jsx(s.CopyButton,{text:a,className:"h-6 w-6"})]}),e.jsx("div",{className:"rounded-md bg-background/60 p-2 max-h-80 overflow-auto",children:e.jsx(s.CodeHighlighter,{code:a,language:"sql"})})]})})})]})]})})}function Es({sql:t,error:a,errorSql:n,onDebugWithAssistant:r}){const l=s.useEditorStore(f=>f.isDevMode),{setIsDevMode:d,setCardSql:i,setRunSql:c}=s.useEditorActions(),[o,u]=D.useState(!1),x=s.useEditorStore(f=>f.card),h=s.useEditorStore(f=>f.frame),p=s.useDashboardStore(f=>f.selectedSheetId),w=s.useDashboardStore(f=>{var b;return(b=f.dashboard)==null?void 0:b.id});function m(f){d(!0),i(f||t),setTimeout(()=>{c(!0)},100)}return e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col pt-4",children:[!l&&t&&!a&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsxs(s.Button,{onClick:()=>m(),variant:"secondary",size:"sm",children:[e.jsx(Cs,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),e.jsxs(s.Button,{onClick:()=>u(!o),variant:"outline",size:"sm",children:[e.jsx(s.Info,{className:"mr-2 h-4 w-4"}),"Card Details"]})]}),o&&e.jsx("div",{className:"mb-3 rounded-lg border border-border bg-muted/30 p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Card Information"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>u(!1),children:e.jsx(ys,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID"}),e.jsx("code",{className:"text-xs font-mono",children:x.id||"N/A"})]}),e.jsx(s.CopyButton,{text:x.id||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Frame ID"}),e.jsx("code",{className:"text-xs font-mono",children:h.id||"N/A"})]}),e.jsx(s.CopyButton,{text:h.id||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Sheet ID"}),e.jsx("code",{className:"text-xs font-mono",children:p||"N/A"})]}),e.jsx(s.CopyButton,{text:p||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Dashboard ID"}),e.jsx("code",{className:"text-xs font-mono",children:w||"N/A"})]}),e.jsx(s.CopyButton,{text:w||"",className:"h-6 w-6"})]})]})]})}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-auto text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(He,{error:a,errorSql:n,showFeedbackButton:!1,onOpenInEditor:()=>m(n)}),!a&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute right-2 top-2 z-10",children:e.jsx(s.CopyButton,{text:t,className:"h-6 w-6"})}),e.jsx(s.CodeHighlighter,{code:t,language:"sql"})]})})]}),a&&r&&e.jsx("div",{className:"mt-3",children:e.jsxs(s.Button,{onClick:r,size:"sm",variant:"outline",children:[e.jsx(ht,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})})]})}function Ft({sql:t,error:a,errorSql:n,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:a?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(ys,{className:"h-4 w-4 text-red-500"}):e.jsx(s.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(s.HoverCardContent,{align:"start",className:"flex w-[700px]",children:e.jsx(Es,{errorSql:n,sql:t,error:a,onDebugWithAssistant:r})})]})}function Ot(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 As(t){const{theme:a}=s.useTheme(),n=s.useDashboardStore(f=>f.theme),r=s.useEditorStore(f=>f.frame),l=s.useEditorStore(f=>f.card),d=s.useEditorStore(f=>f.activeTabCardId),i=s.Le(),{refetch:c}=s.useDashboardCardQuery(l),{updateCardTab:o,setRunSql:u}=s.useEditorActions(),x=D.useRef(),h=D.useRef({}),p=r.cards.find(f=>f.id===d),w=D.useCallback(()=>{let f="";return t==="python"&&(f=(p==null?void 0:p.python)||s.PYTHON_DEFAULT_CODE),t==="sql"&&(f=(p==null?void 0:p.sql)||""),f},[t,p]);D.useEffect(()=>{if(d&&l.id&&l.id!==d){if(x.current&&i){const f=x.current.getModel();f&&(h.current[l.id]=f);let b=h.current[d];if(!b){const C=w();b=i.editor.createModel(C,t),h.current[d]=b}x.current.setModel(b)}o(d,l),u(!0)}},[d,l,o,i,u,t,w]),D.useEffect(()=>{if(!i)return;const f=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",b=n==="system"?f:n;i.editor.defineTheme("default",{base:b==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":b==="light"?"#ffffff":s.hslStringToHex("240 10% 10%")}}),i.editor.setTheme("default")},[a,n,i]),D.useEffect(()=>{const f=x.current;f&&i&&l&&f.addCommand(i.KeyMod.Shift|i.KeyCode.Enter,function(){return c(),!1})},[i,c,l]);function m(f,b){if(x.current=f,!h.current[l.id]){const C=f.getModel(),I=w();h.current[l.id]=C||(b==null?void 0:b.editor.createModel(I,t))||f.getModel()}f.setModel(h.current[l.id])}return{handleEditorDidMount:m}}function Rt(){const t=s.useEditorStore(i=>i.card.sql),a=s.useEditorStore(i=>i.sqlGen),{setCardSql:n,setSqlGen:r}=s.useEditorActions(),{handleEditorDidMount:l}=As("sql");function d(i){n(i),s.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!t&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(s.Ft,{theme:"default",className:"pt-3",onChange:d,value:t||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:l})]})}function Bt(){const t=s.useEditorStore(l=>l.card.python),{setCardPython:a}=s.useEditorActions(),{handleEditorDidMount:n}=As("python");function r(l){a(l)}return e.jsx(s.Ft,{className:"pt-3",theme:"default",onChange:r,value:t||s.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function Vt(){const t=s.useQueryClient(),{isConsoleMode:a}=s.useDashboardPreferences(),[n,r]=D.useState(!1);s.useEditorStore(V=>V.frame);const l=s.useEditorStore(V=>V.card);s.useEditorStore(V=>V.isShowingVisual),s.useEditorStore(V=>V.selectedConnectionId),s.useEditorStore(V=>V.tempQueryData),s.useEditorStore(V=>V.selectedDatabaseName),s.useEditorStore(V=>V.selectedDatamodelId),s.useEditorStore(V=>V.selectedSchemaName);const d=s.useEditorStore(V=>V.showAIDialog);s.useEditorStore(V=>V.selectedTableName);const i=s.useEditorStore(V=>{var G;return(G=V==null?void 0:V.card)==null?void 0:G.sql}),c=s.useEditorStore(V=>{var G;return(G=V==null?void 0:V.card)==null?void 0:G.python}),{cardFilterValues:o}=s.useCardFilterValues((l==null?void 0:l.id)??"");s.useDashboardStore(V=>V.inlineFilterValuesMap[(l==null?void 0:l.id)??""]),D.useRef(!0);const{setCardCustomCfg:u,setQueryResultColumns:x,setCardSql:h,setTempQueryData:p,setPythonStdOut:w,setCardPreferences:m,setCardType:f,setCardPython:b,runAssistant:C,setShowAIDialog:I,setCard:O,updateCardInFrame:R}=s.useEditorActions();s.useEditorStore(V=>V.onSave),s.useEditorStore(V=>V.onClose),s.useEditorStore(V=>V.actions.setSqlGen);const y=s.useEditorStore(V=>V.runSql),k=s.useEditorStore(V=>V.actions.setRunSql),g=s.useEditorStore(V=>V.actions.setIsSqlRunning),{data:j,isLoading:T,isFetching:L,isSuccess:N,isError:v,error:A,errorSql:F,queryKey:E,refetch:M,errorMessage:S}=s.useDashboardCardQuery(l);D.useEffect(()=>{if(j&&(j.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),w((j==null?void 0:j.output)||""),j.records.length>0)){const{dimensionKeys:V}=s.getKeys(j.records);x(V)}},[j,x,w]),D.useEffect(()=>{(T||L)&&g(!0),(v||N)&&g(!1),v&&(x([]),w(""))},[T,L,j,w,v,N,g,x,A]),D.useEffect(()=>{y&&(t.getQueryData(E)||M(),k(!1))},[y,M,k,E,t]);async function P(){const V=`Can you help me debug this query?
178
178
 
179
179
  Error:
180
180
 
181
- ${K}
181
+ ${S}
182
182
 
183
183
  Error SQL:
184
184
 
185
- ${L}
185
+ ${F}
186
186
 
187
187
  Query:
188
188
 
@@ -190,6 +190,6 @@ ${g.joinType} JOIN ${y.name}
190
190
 
191
191
  ${c?`Python:
192
192
  ${c}`:""}
193
- `;O(P)}function G(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.ResizablePanel,{id:"1",order:1,defaultSize:n?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(Rt,{})}),n&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),n&&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(Bt,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function q(){var P,z,J,B,W,X;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:N||b,onClick:()=>{V()},className:"h-8 shrink-0",size:"sm",children:[N||b?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(s.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(Ft,{errorSql:L,sql:M==null?void 0:M.sql,error:K,onDebugWithAssistant:H}),e.jsx(qe.EditorClearButton,{}),e.jsxs(s.Toggle,{pressed:n,onPressedChange:ee=>r(ee),className:"h-8",size:"sm",variant:"outline",children:[e.jsx(Ot,{className:"mr-2 size-4 text-foreground/70"}),"Python"]}),!d&&e.jsxs("button",{disabled:d,onClick:()=>{R(!0)},className:"flex h-8 w-full cursor-text items-center justify-start rounded-md bg-muted/50 px-3 text-left text-sm text-muted-foreground",children:[e.jsx(s.Sparkles,{className:"mr-3 size-4 text-foreground/70"}),"Type your question..."]}),e.jsxs("div",{className:"flex flex-1 items-center justify-end gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((z=(P=l.preferences)==null?void 0:P.tablePrefs)==null?void 0:z.enableDevModePagination)??!1,onCheckedChange:ee=>{var _;j({...l.preferences,tablePrefs:{...(_=l.preferences)==null?void 0:_.tablePrefs,enableDevModePagination:ee}})}}),e.jsx(s.Label,{htmlFor:"pagination",className:"cursor-pointer text-sm",children:"Paginate"}),((B=(J=l.preferences)==null?void 0:J.tablePrefs)==null?void 0:B.enableDevModePagination)&&e.jsxs(s.Select,{value:String(((X=(W=l.preferences)==null?void 0:W.tablePrefs)==null?void 0:X.pageSize)||50),onValueChange:ee=>{var Y,le,ce;const _=Number(ee),ne={...l,preferences:{...l.preferences,tablePrefs:{...(Y=l.preferences)==null?void 0:Y.tablePrefs,pageSize:_}},paginationConfig:{page:1,pageSize:_}};v(ne),w(ne),l.sql&&((ce=(le=l.preferences)==null?void 0:le.tablePrefs)!=null&&ce.enableDevModePagination)&&y(!0)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"10",children:"10"}),e.jsx(s.SelectItem,{value:"25",children:"25"}),e.jsx(s.SelectItem,{value:"50",children:"50"}),e.jsx(s.SelectItem,{value:"100",children:"100"}),e.jsx(s.SelectItem,{value:"500",children:"500"}),e.jsx(s.SelectItem,{value:"1000",children:"1000"})]})]})]}),o&&o.length>0&&e.jsxs(s.HoverCard,{openDelay:200,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",className:"h-8 gap-2 px-2",children:[e.jsx(s.Filter,{className:"size-4"}),e.jsx(s.Badge,{className:"h-5 min-w-5 bg-purple-100 px-1.5 text-purple-700 hover:bg-purple-100 dark:bg-purple-950 dark:text-purple-300",children:o.length})]})}),e.jsx(s.HoverCardContent,{className:"mr-4 max-h-[400px] w-[500px] overflow-auto p-0",children:e.jsxs("div",{className:"p-3",children:[e.jsx("div",{className:"mb-2 text-sm font-semibold",children:"Active Dashboard Filters"}),e.jsx(s.CodeHighlighter,{code:JSON.stringify(o,null,2),language:"json"})]})})]})]})]})})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsx("div",{className:"relative flex grow overflow-y-scroll",children:G()}),q()]})}const Pt=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:s.Grid3x3}];function zt({className:t}){const a=s.useEditorStore(o=>o.card),{setCardType:n,setCard:r,updateCardInFrame:l}=s.useEditorActions(),d=["table","aggregateTable","pivotTable"].includes(a.type),i=s.hasValidCardConfig(a.config);if(!d||!i)return null;const c=o=>{var x;const u=o;if(u==="aggregateTable"&&((x=a.config)!=null&&x.pivotByColumns)&&a.config.pivotByColumns.length>0){const h={...a,type:u,config:{...a.config,pivotByColumns:[]}};r(h),l(h)}else{n(u);const h={...a,type:u};l(h)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:a.type,onValueChange:c,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:Pt.map(o=>{const u=o.icon,x=a.type===o.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:o.value,id:`table-type-${o.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${o.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all",x?"bg-muted text-foreground shadow-sm":"text-muted-foreground hover:bg-muted/50"),children:[e.jsx(u,{className:"h-3.5 w-3.5"}),o.label]})]},o.value)})})})}function $t({type:t,isLinked:a,className:n}){const r=s.useDashboardStore(p=>p.selectedFrameId),l=s.useManagementStore(p=>p.selectedVisual),d=s.useEditorStore(p=>p.frame);let i;if(t)i=t;else if(a!==void 0)i=a?"linked":"library";else if(!!!(d!=null&&d.visualId||l!=null&&l.id)&&r)i="local";else if(l&&!r)i="library";else if(d!=null&&d.visualId&&r)i="linked";else if(l!=null&&l.id&&r)i="library";else return null;if(i==="local")return null;const c={linked:"border-purple-200/70 bg-gradient-to-r from-purple-50/50 to-purple-100/30 text-purple-900 shadow-sm hover:from-purple-100/60 hover:to-purple-100/50 hover:shadow-md dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100 dark:hover:from-purple-950/60 dark:hover:to-purple-900/50",library:"border-blue-200/70 bg-gradient-to-r from-blue-50/50 to-blue-100/30 text-blue-900 shadow-sm hover:from-blue-100/60 hover:to-blue-100/50 hover:shadow-md dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30 dark:text-blue-100 dark:hover:from-blue-950/60 dark:hover:to-blue-900/50"},o={linked:"Linked to library: Changes made here update the library visual and all linked instances.",library:"Library visual: Share and reuse this visual across multiple dashboards."},u={linked:"border-purple-200 bg-purple-50 text-purple-900 dark:border-purple-800 dark:bg-purple-950 dark:text-purple-100",library:"border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-800 dark:bg-blue-950 dark:text-blue-100"},x={linked:"fill-purple-50 dark:fill-purple-950",library:"fill-blue-50 dark:fill-blue-950"},h={linked:e.jsx(gt,{className:"h-3.5 w-3.5"}),library:e.jsx(ft,{className:"h-3.5 w-3.5"})};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:s.cn("cursor-help select-none transition-all",c[i],n),children:h[i]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:s.cn("max-w-xs",u[i]),children:[e.jsx(s.TooltipArrow,{className:x[i]}),e.jsx("p",{children:o[i]})]})]})})}function Is({className:t,...a}){var G,q,P;const n=s.useEditorStore(z=>z.card),r=((G=n.customCardPreferences)==null?void 0:G.showCardHeader)??!0,l=((P=(q=n.preferences)==null?void 0:q.displayOptions)==null?void 0:P.showInlineFilterBar)??!0,d=s.useEditorStore(z=>z.frame),i=s.useDashboardStore(z=>z.dashboard.filters),c=s.useDashboardStore(z=>z.selectedSheetId),[o,u]=D.useState(!1),{currentUser:x}=s.useCurrentUserInfo(),{tokenProps:h}=D.useContext(s.SemaphorContext),p=s.useEditorStore(z=>z.actions.setRunSql),{updateFilter:k}=s.useDashboardActions(),m=i==null?void 0:i.find(z=>z.id===d.filterId),{data:f,isLoading:j,isFetching:C,errorMessage:I,errorSql:O,pagination:R}=s.useDashboardCardQuery(n),v=D.useMemo(()=>(f==null?void 0:f.records)||[],[f==null?void 0:f.records]),{setCard:w,updateCardInFrame:g,setIsDevMode:y,setCardSql:T}=s.useEditorActions(),{data:M}=s.useTopoJson(n),N=D.useMemo(()=>{var z;return n.type!=="pivotTable"||!((z=f==null?void 0:f.records)!=null&&z.length)?null:{records:f.records,columnSubtotalMeta:f.columnSubtotalMeta,subtotalColumns:f.subtotalColumns||[],pivotSchema:f.pivotSchema||[],groupByColumns:f.groupByColumns}},[n.type,f==null?void 0:f.records,f==null?void 0:f.columnSubtotalMeta,f==null?void 0:f.subtotalColumns,f==null?void 0:f.pivotSchema,f==null?void 0:f.groupByColumns]),b=s.usePivotTableConfig(n,N),A=z=>{y(!0),T(z||O||n.sql||n.python||""),setTimeout(()=>{p(!0)},100)},F=()=>{u(!0)},E=D.useMemo(()=>{const z=typeof window<"u"?window.location.href:"",J=typeof navigator<"u"?navigator.userAgent:"",B=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:s.FeedbackCategory.QUERY_GENERATION,user:x,tokenContext:h,systemState:{cardConfig:n.config,dataSource:n.dataSource,dashboardFilters:i,errorMessage:I||void 0,errorSql:O||n.sql||n.python,generatedSql:O||n.sql},metadata:{url:z,userAgent:J,timestamp:new Date().toISOString(),viewport:B}}},[x,h,n,i,I,O]),L=(z,J)=>{var W,X;const B={...n,paginationConfig:{page:z+1,pageSize:J}};w(B),g(B),n.sql&&((X=(W=n.preferences)==null?void 0:W.tablePrefs)!=null&&X.enableDevModePagination)&&p(!0)},S=z=>{var W,X,ee,_;const J=s.sortStateToSortByColumns(z,(W=n.config)==null?void 0:W.metricColumns,(X=n.config)==null?void 0:X.groupByColumns),B={...n,config:{...n.config||{},sortByColumns:J}};w(B),g(B),n.sql&&((_=(ee=n.preferences)==null?void 0:ee.tablePrefs)!=null&&_.enableDevModePagination)&&p(!0)},V=D.useMemo(()=>!n.id||!(f!=null&&f.records)?null:s.createChartConfig({card:n,data:f==null?void 0:f.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:M}),[n.id,f==null?void 0:f.records,n.type,n.customCfg,n.preferences,M]);function K(z){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(s.EditorCustomVisual,{card:z})})}function H(){if(f!=null&&f.records&&(f==null?void 0:f.records.length)===0&&!j&&!C)return I?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(He,{error:I,errorSql:O||n.sql||n.python,onOpenInEditor:A,onSendFeedback:F,showFeedbackButton:!0,errorTitle:"Unable to Create Visual"})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((j||C)&&(!(f!=null&&f.records)||f.records.length===0))return n.type==="table"?e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableSkeleton,{})}):e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!n.id)return null;if(n.type==="custom")return K(n);if(!["table","pivotTable","aggregateTable","custom"].includes(n.type)&&V)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:j||C?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:V})});if(n.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:n,data:v,paginationMetadata:R,onPaginationChange:L,onSortChange:S,isLoading:j||C})});if(n.type==="pivotTable"&&b)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.PivotTableTanstack,{card:n,data:b.data,options:b.options,onAggregationChange:z=>{const J=s.handleAggregationChange(z,n.config),B={...n,config:J};w(B),g(B)},onAggregationLabelChange:z=>{const J=s.handleAggregationLabelChange(z,n.config),B={...n,config:J};w(B),g(B)}})});if(n.type==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:n,data:(f==null?void 0:f.records)||[],groupByColumns:f==null?void 0:f.groupByColumns,pivotSchema:f==null?void 0:f.pivotSchema,paginationMetadata:R,onPaginationChange:L,onAggregationChange:z=>{const J=s.handleAggregationChange(z,n.config),B={...n,config:J};w(B),g(B)},isLoading:j||C})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...a,children:[(j||C)&&(f==null?void 0:f.records)&&f.records.length>0&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),r&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:n.title,onSave:z=>w({...n,title:z}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx($t,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(zt,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:n.description||"",onSave:z=>w({...n,description:z}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),m&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:m.title||m.column,onSave:z=>k({...m,title:z}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:m})]})]}),l&&n.inlineFilters&&n.inlineFilters.length>0&&e.jsx("div",{className:"px-6 pb-3",children:e.jsx(s.InlineFilterBar,{card:n,sheetId:c||""})}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:H()}),e.jsx(s.FeedbackDialog,{open:o,onOpenChange:u,feedbackData:E,showDebugInfo:!0})]})}const ze=({language:t,value:a,onChange:n,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:a,onChange:n}),Kt=()=>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."})]})]}),Gt=({customCode:t,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:l})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ze,{language:"json",value:n,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ze,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ze,{language:"javascript",value:t,onChange:l})})]}),qt=({error:t,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:l})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:l,variant:"outline",children:"Close"})]});function Ut(){const[t,a]=D.useState(!1),[n,r]=D.useState(""),[l,d]=D.useState(""),[i,c]=D.useState(""),[o,u]=D.useState(""),x=s.useEditorStore(v=>v.card),h=s.useEditorStore(v=>v.card.customCfg),p=h?JSON.stringify(h,null,2):"",{data:k}=s.useDashboardCardQuery(x),{data:m}=s.useTopoJson(x),{setCardCustomCfg:f,setCustomVisualCode:j}=s.useEditorActions(),C=v=>{var w,g;return JSON.stringify({...v,data:{...v.data,datasets:(g=(w=v.data)==null?void 0:w.datasets)==null?void 0:g.map(y=>({...y,data:[]}))}},null,2)},I=()=>{var w,g;if(!((w=k==null?void 0:k.records)!=null&&w.length))return;const v=s.createChartConfig({card:x,data:k.records,cardType:x.type,queryConfig:x.queryConfig,preferences:x.preferences,topoJson:m});if(v){r(C(v)),c(((g=x.preferences)==null?void 0:g.customVisualCode)||"");const y=s.merge(v,h);d(C(y))}},O=()=>{try{if(i&&j(i),l){const v=JSON.parse(l),w=s.getObjectDiff(JSON.parse(n),v);f(w),u("")}}catch{u("Invalid JSON configuration")}},R=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:a,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:I,className:R?"":"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(Kt,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Is,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Gt,{customCode:i,cardCustomCfgString:p,mergedConfig:l,onConfigChange:v=>d(v??""),onCodeChange:v=>c(v??"")})]}),e.jsx(qt,{error:o,hasCardCustomConfig:!!h,onReset:()=>{d(n),f(null)},onApply:O,onClose:()=>a(!1)})]})]})}function Ht({isStarred:t,onClick:a,className:n}){const r=l=>{l.stopPropagation(),l.preventDefault(),a(l)};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",n),"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 rs({chartType:t,chartName:a,isCustom:n=!1,pluginName:r,isStarred:l,showStar:d=!0,onSelect:i,onToggleStar:c}){return e.jsxs("button",{onClick:i,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:[d&&e.jsx("div",{className:s.cn("absolute left-1 top-1 transition-opacity",l?"opacity-100":"opacity-0 group-hover:opacity-100"),children:e.jsx(Ht,{isStarred:l,onClick:()=>c()})}),n&&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:a,isCustom:n,className:"h-6 w-6"}),e.jsx("span",{title:a,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:a})]})}const ls=[{id:"table",name:"Table"},{id:"bar",name:"Bar Chart"},{id:"line",name:"Line Chart"},{id:"stackedBar",name:"Stacked Bar"},{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 Ds({onChartSelect:t,onClose:a}){const[n,r]=D.useState(""),{starredCharts:l,isStarred:d,toggleStar:i}=s.useStarredChartsStore(),{data:c=[],isLoading:o}=s.useCustomVisualsQuery(),{setCardType:u,setCardPreferences:x,setIsDevMode:h}=s.useEditorStore(v=>v.actions),{setCardCustomCfg:p,setCustomCardPreferences:k,setQueryConfig:m}=s.useEditorActions(),f=D.useMemo(()=>{if(!n)return ls;const v=n.toLowerCase();return ls.filter(w=>w.name.toLowerCase().includes(v))},[n]),j=D.useMemo(()=>{const v=c.filter(g=>g.componentType==="chart");if(!n)return v;const w=n.toLowerCase();return v.filter(g=>g.name.toLowerCase().includes(w))},[c,n]),C=v=>{p(null),x({}),u(v),["custom","text","map"].includes(v)&&(h(!0),m(void 0)),t==null||t(v),a==null||a()},I=v=>{p(null),x({}),u("custom"),k({type:"component",visualType:"single",url:v.url,componentName:v.name,icon:v.icon,pluginChartType:v.chartType}),m(void 0),t==null||t("custom",v),a==null||a()},O=v=>{const w={type:"default",id:v.id,name:v.name};i(w)},R=v=>{const w={type:"custom",id:v.name,url:v.url,icon:v.icon,name:v.name};i(w)};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,{placeholder:"Search charts...",value:n,onChange:v=>r(v.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:[f.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:f.map(v=>e.jsx(rs,{chartType:v.id,chartName:v.name,isCustom:!1,isStarred:d("default",v.id),onSelect:()=>C(v.id),onToggleStar:()=>O(v)},v.id))})]}),j.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:j.map((v,w)=>e.jsx(rs,{chartName:v.name,isCustom:!0,pluginName:v.pluginName,isStarred:d("custom",v.name),onSelect:()=>I(v),onToggleStar:()=>R(v)},`${v.url}-${v.name}-${w}`))})]})]}),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..."})]}),f.length===0&&j.length===0&&!o&&e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No charts found"})]})]})}function Ms({variant:t="ghost"}){var d,i;const[a,n]=D.useState(!1),r=s.useEditorStore(c=>c.card),l=r.type;return e.jsxs(s.Popover,{open:a,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(s.SelectedChartIcon,{className:"size-4",chartType:l,customIcon:(d=r.customCardPreferences)==null?void 0:d.icon,componentName:(i=r.customCardPreferences)==null?void 0:i.componentName})})}),e.jsx(s.PopoverContent,{onOpenAutoFocus:c=>c.preventDefault(),className:"z-[70] w-[360px] p-3",children:e.jsx(Ds,{onClose:()=>n(!1)})})]})}function Jt({error:t,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[l,d]=D.useState(!1),i=D.useRef(null),c=D.useRef(!1);function o(){t&&!c.current&&navigator.clipboard.writeText(t)}function u(p){(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),o())}function x(){const p=window.getSelection();if(p&&p.toString().trim()!==""){const k=p.toString();navigator.clipboard.writeText(k),d(!0),c.current=!0,setTimeout(()=>{d(!1),c.current=!1},1e3)}else c.current=!1}function h(){d(!1),c.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${a}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:i,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${n}`,onClick:o,onKeyDown:u,onMouseUp:x,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function _t(){const t=s.useEditorStore(o=>{var u,x;return(x=(u=o.card.preferences)==null?void 0:u.chartOptions)==null?void 0:x.indexAxis}),a=s.useEditorStore(o=>o.card.type),{setChartOrientation:n,setCardPreferences:r}=s.useEditorStore(o=>o.actions),l=o=>{if(n(o),a!=="bullet")return;const u=o==="y"?"horizontal":"vertical",x=s.useEditorStore.getState().card.preferences,h={...x||{},bulletConfig:{...(x==null?void 0:x.bulletConfig)||{},orientation:u}};r(h)};function d(){const o=t??"x",u=()=>{l(o==="x"?"y":"x")};return e.jsx(s.IconButton,{onClick:u,tooltip:"Chart Orientation",children:o==="x"?e.jsx(Pe,{className:"size-4"}):e.jsx(Ve,{className:"size-4"})})}function i(){const o=()=>{l(t==="y"||t===void 0?"x":"y")};return e.jsx(s.IconButton,{onClick:o,tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(Pe,{className:"size-4"}):e.jsx(Ve,{className:"size-4"})})}function c(){const o=t??"y",u=()=>{l(o==="y"?"x":"y")};return e.jsx(s.IconButton,{onClick:u,tooltip:"Chart Orientation",children:o==="y"?e.jsx(Ve,{className:"size-4"}):e.jsx(Pe,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?i():a==="bullet"?c():d()})}function Qt({className:t}){var k,m,f,j,C,I,O,R,v,w;const a=s.useEditorStore(g=>g.card),{setCardPreferences:n,updateCardInFrame:r,setCard:l}=s.useEditorActions(),[d,i]=D.useState(!1),c=((m=(k=a.preferences)==null?void 0:k.displayOptions)==null?void 0:m.showFilterInfo)??!0,o=((j=(f=a.preferences)==null?void 0:f.displayOptions)==null?void 0:j.showCardToolbar)??!0,u=((I=(C=a.preferences)==null?void 0:C.displayOptions)==null?void 0:I.showChrome)??!0,x=((R=(O=a.preferences)==null?void 0:O.displayOptions)==null?void 0:R.allowScroll)??!0,h=((w=(v=a.preferences)==null?void 0:v.displayOptions)==null?void 0:w.showInlineFilterBar)??!0,p=(g,y)=>{var N;const T={...a.preferences,displayOptions:{...(N=a.preferences)==null?void 0:N.displayOptions,[g]:y}};n(T);const M={...a,preferences:T};l(M),r(M)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:d,onOpenChange:i,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(Ss,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"Display Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Changes apply to dashboard view only"})}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:g=>{p("showFilterInfo",g)},onSelect:g=>g.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:g=>{p("showCardToolbar",g)},onSelect:g=>g.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Toolbar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Hover actions"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:g=>{p("showChrome",g)},onSelect:g=>g.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Chrome"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Frame & padding"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:g=>{p("allowScroll",g)},onSelect:g=>g.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Allow Scroll"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card content scroll"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:h,onCheckedChange:g=>{p("showInlineFilterBar",g)},onSelect:g=>g.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 Yt(){const[t,a]=D.useState(!1),n=s.useEditorStore(h=>h.card),r=s.useEditorStore(h=>h.selectedConnectionId),{setCard:l}=s.useEditorActions(),d=s.useDashboardStore(h=>h.actions.removeCardInlineFilterValue),i=(n==null?void 0:n.inlineFilters)||[];function c(h){const p=h.qualifiedFieldName||h.name;if(i.find(I=>I.column===p))return;const m=h.qualifiedFieldName?h.qualifiedFieldName.split(".").slice(0,-1).join("."):h.qualifiedEntityName||h.entityName,f=s.fmt(h.name),j=h.qualifiedFieldName||f,C={id:s.v4(),column:p,title:h.label||h.name,dataType:h.dataType,table:h.entityName||"",database:"",connectionId:r||"",operation:"in",sql:s.getDefaultFilterSql(h.dataType,m,j),width:250};l({...n,inlineFilters:[...i,C]})}function o(h){const p=i.filter(k=>k.id!==h);l({...n,inlineFilters:p}),d(n.id,h)}function u(h,p){const k=i.map(m=>m.id===h?{...m,...p}:m);l({...n,inlineFilters:k})}return["bar","line","pie","doughnut","table","stackedBar","stackedLine","horizontalBar","radar","polarArea","scatter","bubble","funnel","aggregateTable","custom"].includes(n==null?void 0:n.type)?e.jsx("div",{className:"flex items-center gap-1",children:e.jsxs(s.Popover,{open:t,onOpenChange:a,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.IconButton,{tooltip:"Add Inline Filter",className:s.cn("relative",{"text-primary":i.length>0}),children:[e.jsx(bt,{className:"h-4 w-4"}),i.length>0&&e.jsx("span",{className:"absolute -right-1 -top-1 flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] font-medium text-primary-foreground",children:i.length})]})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80 p-0",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"border-b px-4 py-3",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Inline Filters"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"On-card filters for fast, focused exploration."})]}),e.jsx("div",{className:"flex max-h-[300px] flex-col overflow-hidden",children:e.jsx(s.DndContext,{collisionDetection:s.closestCenter,children:e.jsx(s.SortableContext,{items:[],strategy:s.verticalListSortingStrategy,children:e.jsx(s.FieldsList,{context:"inline-filter",onFieldSelect:c,inlineFilters:i})})})}),i.length>0&&e.jsxs("div",{className:"border-t px-4 py-3",children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Active Filters"}),e.jsx("div",{className:"space-y-1",children:i.map(h=>e.jsx(Wt,{filter:h,onUpdate:p=>u(h.id,p),onRemove:()=>o(h.id)},h.id))})]})]})})]})}):null}function Wt({filter:t,onUpdate:a,onRemove:n}){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=>a(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:n,children:e.jsx(s.X,{className:"h-3 w-3"})})]})]})}function Ls(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var i,c;return(c=(i=d.card)==null?void 0:i.preferences)==null?void 0:c.chartOptions}),n=s.getChartGridStyle(a),{setChartGrid:r}=s.useEditorActions();function l(){const d=["xy","none","x","y"],c=(d.indexOf(n)+1)%d.length;r(d[c])}return e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(_t,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsx(e.Fragment,{}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:l,children:[(n==="xy"||!n)&&e.jsx(s.Grid3x3,{className:"size-4"}),n==="x"&&e.jsx(Ns,{className:"size-4"}),n==="y"&&e.jsx(Ue,{className:"size-4"}),n==="none"&&e.jsx(Tt,{className:"size-4"})]}),e.jsx(Yt,{}),e.jsx(Qt,{})]})}function Xt(){const t=s.useEditorStore(m=>m.frame),a=s.useEditorStore(m=>m.card),{setFrame:n,setActiveTabCardId:r,setCard:l,updateCardInFrame:d}=s.useEditorActions(),i=(m,f)=>{m.dataTransfer.setData("tabIndex",f.toString())},c=m=>{m.preventDefault()},o=(m,f)=>{const j=m.dataTransfer.getData("tabIndex");if(j===f.toString())return;const C=Array.from(t.cards),[I]=C.splice(parseInt(j),1);C.splice(f,0,I),n({...t,cards:C})};function u(m){const f=t.cards.filter(I=>I.id!==m),j=f[0],C={...t,cards:f,activeCardId:j.id};n(C),r(j.id),l(j)}function x(m,f){const j={...t,cards:[...t.cards,f],activeCardId:m.id};n(j),r(f.id)}function h(){const m={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};x(a,m)}function p(m){const f={dataSource:m.dataSource,connectionId:m.connectionId,lastSelectedDatabase:m.lastSelectedDatabase,lastSelectedSchema:m.lastSelectedSchema,lastSelectedTable:m.lastSelectedTable,lastSelectedDatamodelId:m.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};x(m,f)}function k(m,f){return m.cards.length===1&&(f.displayTab===!0||f.displayTab===void 0)||m.activeCardId!==f.id&&(f.displayTab===!0||f.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const j=f.displayTab===void 0?!1:!f.displayTab;l({...f,displayTab:j}),d({...f,displayTab:j})},children:f.displayTab===!0||f.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(dt,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((m,f)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:j=>i(j,f),onDragOver:c,onDrop:j=>o(j,f),className:"",value:m.id,children:[k(t,m),e.jsx(s.Editable,{enabled:t.activeCardId===m.id,text:m.tabTitle||m.title,onSave:j=>{l({...a,tabTitle:j}),d({...a,tabTitle:j})},children:m.tabTitle||m.title},m.id),t.activeCardId===m.id&&e.jsx(s.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:j=>{j.stopPropagation(),h()}}),t.activeCardId===m.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(m.id)})]},m.id)),e.jsx(s.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>p(a),children:e.jsx(s.Plus,{className:"h-4 w-4"})})]})})}function Ge(){const t=s.useEditorStore(j=>j.frame),a=s.useEditorStore(j=>j.card),n=s.useEditorStore(j=>j.isSqlRunning),r=s.useEditorStore(j=>j.isDevMode),{setFrame:l,setActiveTabCardId:d,setCard:i,setIsDevMode:c,setRunSql:o}=s.useEditorActions(),{data:u,isLoading:x,isFetching:h,isError:p}=s.useDashboardCardQuery(a);function k(j){const C=t.cards.find(I=>I.id===j);if(C!=null&&C.sql){r||c(!0),d(j);return}if(C!=null&&C.queryConfig){r&&c(!1),m(j),d(j);return}r||m(j),d(j)}function m(j){const C={...t,cards:t.cards.map(O=>O.id===a.id?a:O),activeCardId:j};l(C);const I=C.cards.find(O=>O.id===j);I.sql&&o(!0),i(I)}function f(){return a.type==="kpi"?x||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:a,data:u==null?void 0:u.records,isPending:x||h,isError:p})})}):a.type==="text"?x||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:n,card:a,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Is,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:k,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(j=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:j.id,children:f()},j.id)),e.jsx(Xt,{})]})}function os({children:t}){const a=s.useEditorStore(b=>b.frame),n=s.useEditorStore(b=>b.card),r=s.useEditorStore(b=>b.isDevMode),l=s.useEditorStore(b=>b.isShowingVisual),d=s.useDashboardStore(b=>b.isVisualEditing),i=s.useEditorStore(b=>b.pythonStdOut),c=s.useEditorStore(b=>b.actions.setRunSql),{setFrame:o,setCard:u,setActiveTabCardId:x,runAssistant:h,setIsDevMode:p,setCardPreferences:k}=s.useEditorActions(),{data:m,isLoading:f,isFetching:j,errorMessage:C,refetch:I,pagination:O}=s.useDashboardCardQuery(n),R=D.useMemo(()=>(m==null?void 0:m.records)||[],[m==null?void 0:m.records]),[v,w]=D.useState(!1);D.useEffect(()=>{j||w(!1)},[j]);function g(b,A){var L,S;const F={...n,paginationConfig:{page:b+1,pageSize:A}};u(F);const E={...a,cards:a.cards.map(V=>V.id===n.id?F:V)};o(E),n.sql&&((S=(L=n.preferences)==null?void 0:L.tablePrefs)!=null&&S.enableDevModePagination)&&c(!0)}function y(b){var L,S,V,K;const A=s.sortStateToSortByColumns(b,(L=n.config)==null?void 0:L.metricColumns,(S=n.config)==null?void 0:S.groupByColumns),F={...n,config:{...n.config||{},sortByColumns:A}};u(F);const E={...a,cards:a.cards.map(H=>H.id===n.id?F:H)};o(E),n.sql&&((K=(V=n.preferences)==null?void 0:V.tablePrefs)!=null&&K.enableDevModePagination)&&c(!0)}function T(){const b=JSON.stringify(m==null?void 0:m.records,null,2),A=new Blob([b],{type:"application/json"}),F=URL.createObjectURL(A),E=document.createElement("a");E.href=F,E.download=`${n.title}.json`,E.click()}function M(){const A=[Object.keys(m==null?void 0:m.records.reduce((S,V)=>({...S,...V}),{})).join(","),...((m==null?void 0:m.records)||[]).map(S=>Object.values(S).join(","))].join(`
194
- `),F=new Blob([A],{type:"text/csv"}),E=URL.createObjectURL(F),L=document.createElement("a");L.href=E,L.download=`${n.title}.csv`,L.click()}function N(){const b=`Can you get the documentation for ${n.type} chart?`;h(b)}return n?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[l&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(Ms,{}),d&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:N,children:e.jsx(ot,{className:"size-4"})}),!["table","custom"].includes(n.type)&&d&&e.jsx(Ut,{})]}),!l&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:M,children:e.jsx(s.PiFileCsv,{className:"size-4"})}),e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:T,children:e.jsx(ut,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(m==null?void 0:m.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(s.IconButton,{tooltip:"Refresh",disabled:f||j,onClick:()=>{w(!0),I()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":v})})}),e.jsx(Ls,{})]}),r&&e.jsx(en,{})]}),l?e.jsx(Ge,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[i&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:i&&e.jsx(Zt,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":i}),children:[(m==null?void 0:m.records)&&(m==null?void 0:m.records.length)>0&&e.jsx(s.TableVisual,{card:n,data:R,paginationMetadata:O,onPaginationChange:g,onSortChange:y,isLoading:f||j}),C&&e.jsx(Jt,{error:C})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function Zt(){const t=s.useEditorStore(n=>n.pythonStdOut);if(!t)return null;const a=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:a}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function en(){const t=s.useEditorStore(n=>n.isShowingVisual),a=s.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs(s.Toggle,{pressed:!t,onPressedChange:()=>a(!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 ie({value:t,onCommit:a,type:n="text",placeholder:r,className:l}){const[d,i]=D.useState(t),c=D.useRef(!1);D.useEffect(()=>{i(t)},[t]);const o=()=>{if(c.current){c.current=!1;return}d!==t&&a(d)},u=x=>{if(x.key==="Enter"){x.currentTarget.blur();return}x.key==="Escape"&&(c.current=!0,i(t),x.currentTarget.blur())};return e.jsx(s.Input$1,{type:n,placeholder:r,value:d,onChange:x=>i(x.target.value),onBlur:o,onKeyDown:u,className:l})}function he({defaultValue:t,label:a,options:n,value:r,onValueChange:l,className:d,icon:i,showPlaceholderLabel:c=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",d),children:e.jsxs("div",{className:"flex items-center gap-2",children:[i&&e.jsx("span",{children:i}),c&&e.jsx(s.SelectValue,{placeholder:a})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:a}),n.map(o=>e.jsx(s.SelectItem,{value:o.value,children:o.label},o.value))]})})]})}const sn={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:a})=>(a==null?void 0:a.includes("language-"))?e.jsx("pre",{className:"my-3 overflow-x-auto rounded-md bg-muted p-3 text-xs",children:e.jsx("code",{children:t})}):e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:t}),pre:({children:t})=>e.jsx(e.Fragment,{children:t})};function Fs(){var f,j;const t=s.useEditorStore(C=>C.card.customCardPreferences),{data:a}=s.usePluginQuery(),n=(a==null?void 0:a.plugins)||[],r=s.useEditorStore(C=>C.card),l=s.useEditorStore(C=>C.frame),d=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:i}=s.useEditorActions(),{components:c,manifest:o}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(f=o==null?void 0:o.visuals)==null?void 0:f.find(C=>C.name===(t==null?void 0:t.componentName));function x(C,I){if(!t)return;const R={...(t==null?void 0:t.dataInputCardIds)||{},[C]:{cardId:I,hookRef:null}};i({...t,dataInputCardIds:R})}function h(C){var O,R;const I=(O=l==null?void 0:l.cards)==null?void 0:O.filter(v=>{var w;return((w=v==null?void 0:v.customCardPreferences)==null?void 0:w.visualType)!=="multiple"}).map(v=>({value:v.id,label:v.tabTitle||v.title}));return e.jsx("div",{className:"space-y-2",children:(R=C==null?void 0:C.dataInputs)==null?void 0:R.map((v,w)=>{var g,y;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:v}),e.jsx(he,{className:"col-span-6 h-8 w-full justify-between",label:"",options:I||[],value:((y=(g=t==null?void 0:t.dataInputCardIds)==null?void 0:g[w])==null?void 0:y.cardId)||"",onValueChange:T=>x(w,T)})]},w+Math.random())})})}function p(C,I,O=[],R=""){var v,w;return t?C==="input"?e.jsx(ie,{className:`h-8 w-full ${s.removeRing}`,value:String(((v=t==null?void 0:t.settings)==null?void 0:v[I])??R??""),onCommit:g=>{i({...t,settings:{...t==null?void 0:t.settings,[I]:g}})}},I):C==="select"?e.jsx(he,{className:"h-8 w-full",label:"",options:O,value:((w=t==null?void 0:t.settings)==null?void 0:w[I])||R,onValueChange:g=>{i({...t,settings:{...t==null?void 0:t.settings,[I]:g}})}}):null:null}function k(C){const I=Object.entries((C==null?void 0:C.settings)||{});return e.jsx("div",{className:"space-y-3",children:I.map(([O,R])=>{var v;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:R.title}),((v=R.docs)==null?void 0:v.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:R.docs.description})})]})})]}),p(R.ui,O,R.options,R.defaultValue)]},O)})})}function m(C){t&&i({...t,visualType:C,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"",children:[e.jsxs(s.AccordionItem,{value:"plugin-settings",children:[e.jsx(s.AccordionTrigger,{children:"Plugin"}),e.jsx(s.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(he,{icon:e.jsx(vs,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(t==null?void 0:t.url)||"",onValueChange:C=>i({...t||{url:"",componentName:""},url:C})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:d,onValueChange:m,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:c&&e.jsx(he,{icon:e.jsx(ct,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(c==null?void 0:c.filter(C=>C.type===d).map(C=>({value:C.name,label:C.name})))||[],value:t.componentName,onValueChange:C=>{console.log("changing value",C),i({...t,componentName:C})}})})]})})]}),((j=r==null?void 0:r.customCardPreferences)==null?void 0:j.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:(u==null?void 0:u.name)||"Settings"}),(u==null?void 0:u.docs)&&e.jsxs(s.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,onClick:C=>C.stopPropagation(),children:e.jsx(s.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground transition-colors hover:text-foreground"})}),e.jsx(s.HoverCardContent,{side:"right",align:"start",className:"max-h-[40vh] w-[500px] overflow-y-auto text-left",children:e.jsxs("div",{className:"space-y-4 text-left",children:[u.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:u.docs.description}),u.docs.dataSchema&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Data Schema"}),e.jsx("div",{className:"prose prose-sm dark:prose-invert prose-pre:bg-muted prose-pre:text-xs max-w-none",children:e.jsx(s.Markdown,{remarkPlugins:[s.remarkGfm],components:sn,children:u.docs.dataSchema})})]}),u.docs.useCases&&u.docs.useCases.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Use Cases"}),e.jsx("ul",{className:"space-y-1 text-sm",children:u.docs.useCases.map((C,I)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:C})]},I))})]})]})})]})]})}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:k(u)})})]})]})]})}function Se(){const[t,a]=D.useState([]),n=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(u=>u.actions),d=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var x;return(x=u.card.preferences)==null?void 0:x.filterOnClickColumnIndex}),D.useEffect(()=>{d&&a(new Array(d.length).fill(!1))},[d]);function i(u,x){var h,p;x?n!=null&&n.onClickFilter&&((h=n==null?void 0:n.onClickFilter)==null?void 0:h.length)>0?l({...n,onClickFilter:[...n.onClickFilter,{columnIndex:u,expression:""}]}):l({...n,onClickFilter:[{columnIndex:u,expression:""}]}):(l({...n,onClickFilter:(p=n==null?void 0:n.onClickFilter)==null?void 0:p.filter(k=>k.columnIndex!==u)}),a(k=>{const m=[...k];return m[u]=!1,m}))}function c(u,x){var p;const h=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.map(k=>k.columnIndex===u?{...k,expression:x.target.value}:k);l({...n,onClickFilter:h})}function o(u){var x,h,p,k;if(t!=null&&t[u]||(h=(x=n==null?void 0:n.onClickFilter)==null?void 0:x.find(m=>m.columnIndex===u))!=null&&h.expression)return e.jsx(s.Input$1,{value:(k=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(m=>m.columnIndex===u))==null?void 0:k.expression,onChange:m=>c(u,m),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:d==null?void 0:d.map((u,x)=>{var h,p;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=n==null?void 0:n.onClickFilter)!=null&&h.find(k=>k.columnIndex===x)),onCheckedChange:k=>i(x,k)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(k=>k.columnIndex===x))&&e.jsx(s.Pencil,{onClick:()=>{a(k=>{const m=[...k];return m[x]=!k[x],m})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),o(x)]})},u)})})}function tn({idx:t}){var c;const a=s.useEditorStore(o=>{var u;return(u=o.card)==null?void 0:u.preferences}),n=s.useEditorStore(o=>{var u;return(u=o.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(o=>o.actions.setCardPreferences),l=(c=a==null?void 0:a.chartOptions)==null?void 0:c.indexAxis,d=n==null?void 0:n.find(o=>o.idx===t);function i(o,u){(o==="end"||o==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const x={display:o!=="none",align:o,anchor:o,clamp:!0};if(!d)r({...a,datasetOptions:[...n||[],{idx:u,datalabels:x}]});else{const h={...d};h.datalabels=x;const p=n==null?void 0:n.map(k=>k.idx===u?h:k);r({...a,datasetOptions:p})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(s.Tag,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>i("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>i("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(jt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>i("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(yt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>i("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(vt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function nn(){const t=s.useEditorStore(d=>d.card),{data:a}=s.useDashboardCardQuery(t),{keys:n}=s.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(d=>!s.METADATA_KEYS.includes(d));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const d=s.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:i}=s.getKeys(d);l=i.slice(1)}return{transformedMetricKeys:l,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function Je({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Os(){const t=s.useEditorStore(o=>o.card),a=s.useEditorStore(o=>{var u,x,h;return(h=(x=(u=o==null?void 0:o.card)==null?void 0:u.preferences)==null?void 0:x.chartOptions)==null?void 0:h.indexAxis}),{data:n}=s.useDashboardCardQuery(t),r=a==="y"?"Metric":"Dimension",l=a==="y"?"Dimension":"Metric",{dimensionKeys:d,transformedMetricKeys:i,keys:c}=nn();return c.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:d.map(o=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:o,children:Rs(o)},o))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:l}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:i.map((o,u)=>e.jsx(Bs,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:o,idx:u},o))})]})]})}function Rs(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function Bs({col:t,idx:a,className:n,iconClassName:r,children:l}){const d=s.useEditorStore(x=>{var h;return(h=x.card)==null?void 0:h.preferences}),i=s.useEditorStore(x=>{var h,p;return(p=(h=x.card)==null?void 0:h.preferences)==null?void 0:p.datasetOptions}),c=i==null?void 0:i.find(x=>x.idx===a),{setCardPreferences:o}=s.useEditorStore(x=>x.actions);function u(x){if(!c)o({...d,datasetOptions:[...i||[],{idx:a,type:x==="area"?"line":x,fill:x==="area"?"origin":""}]});else{const h={...c};h.type=x==="area"?"line":x,h.fill=x==="area"?"origin":"";const p=i==null?void 0:i.map(k=>k.idx===a?h:k);o({...d,datasetOptions:p})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[l||e.jsx(Je,{className:"max-w-[100px]",title:t,children:Rs(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>u("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>u("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>u("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(tn,{idx:a})]})]})}function De(){const t=s.useDashboardStore(c=>c.dashboard.filters),a=s.useEditorStore(c=>c.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=s.useAssignFilter();function d(c){const o=l(c,"frame");n({...a,filterId:o})}const i=t==null?void 0:t.find(c=>c.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(an,{onSelect:d,columns:r}),i&&e.jsx(s.FilterHeader,{filter:i})]})}function an({columns:t,onSelect:a}){var i;const[n,r]=Ke.useState(!1),[l,d]=Ke.useState("");return e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[l?(i=t.find(c=>c.column_name===l))==null?void 0:i.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(c=>e.jsxs(s.CommandItem,{value:c.column_name,onSelect:o=>{const u=o===l?"":o;d(u),r(!1),u&&a(c)},children:[c.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===c.column_name?"opacity-100":"opacity-0")})]},c.column_name))})]})]})})]})}function rn({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:a=>a.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(Os,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(De,{})]})]})]})})}function ln({cardType:t}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:d=>d.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:a(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(De,{})]})]})]})})}function Vs(){const t=s.useEditorStore(c=>c.card.type),a=s.useEditorStore(c=>c.isDevMode),n=s.useEditorStore(c=>c.card.preferences),{setCardPreferences:r}=s.useEditorStore(c=>c.actions);function l(c){var x;const o={datalabels:{display:c!=="none",align:c,anchor:c,clamp:!0}},u={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(x=n==null?void 0:n.chartOptions)==null?void 0:x.plugins,...o}}};r(u)}function d(){var c,o,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(o=(c=n==null?void 0:n.chartOptions)==null?void 0:c.plugins)==null?void 0:o.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function i(){var c,o,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(o=(c=n==null?void 0:n.chartOptions)==null?void 0:c.plugins)==null?void 0:o.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?d():i()})}const on={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},cn={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function dn(){const t=s.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:un(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Vs,{}),e.jsx(Se,{}),e.jsx(De,{})]})]})}function un(t){if(["line","bar"].includes(t))return e.jsxs(e.Fragment,{children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT x-axis, y-axis-1, y-axis-2, y-axis-3,... FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"X-axis - Category (ex. city)"}),e.jsx("li",{children:"Y-axis - Number (ex. population)"})]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and change the `type` property in the dataset."]}),e.jsx("pre",{children:JSON.stringify(on,null,2)})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and add `fill` property to the dataset. See",e.jsx("a",{className:"mx-1 text-blue-500 hover:underline",href:"https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html",target:"_blank",children:"docs"}),"for more options."]}),e.jsx("pre",{children:JSON.stringify(cn,null,2)})]})]})]});if(t==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis, radius FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Bubble Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"}),e.jsx("li",{children:"Radius - Number (ex. population)"})]})]})]})});if(t==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"})]})]})]})});if(["pie","doughnut","polarArea","funnel"].includes(t))return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:t==="polarArea"?"Polar":t.charAt(0).toUpperCase()+t.slice(1)})," ","chart query"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Measure - Number (ex. population)"})]})]})]})})}function mn({colorRanges:t,setColorRanges:a}){const n={start:-1/0,end:100,color:""};function r(i,c,o){const u=[...t];u[i]={...u[i],[c]:o},a(u)}function l(i){const c=[...t];c.splice(i,1),a(c)}function d(){a([...t,n])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:"Color Range"}),e.jsx(s.Button,{onClick:d,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((i,c)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input$1,{onChange:o=>r(c,"start",o.target.value),value:i.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input$1,{value:i.end,onChange:o=>r(c,"end",o.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input$1,{onChange:o=>r(c,"color",o.target.value),value:i.color,className:s.cn(`h-7 min-w-14 p-0 ${s.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:s.colors.green[600]}),e.jsx("option",{children:s.colors.red[500]}),e.jsx("option",{children:s.colors.yellow[400]}),e.jsx("option",{children:s.colors.orange[500]})]}),e.jsx(s.Button,{onClick:()=>l(c),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},c))]})}function xn(){var x,h,p,k,m;const t=s.useEditorStore(f=>f.card.preferences),a=s.useEditorStore(f=>f.actions.setCardPreferences),n=s.useEditorStore(f=>f.card),r=s.hasValidCardConfig(n.config),l=s.useEditorStore(f=>f.actions.setNumberFormat);s.useEditorStore(f=>{var j,C;return(C=(j=f.card.preferences)==null?void 0:j.formatNumber)==null?void 0:C.decimalPlaces});const d=s.useEditorStore(f=>{var j,C;return(C=(j=f.card.preferences)==null?void 0:j.formatNumber)==null?void 0:C.locale}),i=s.useEditorStore(f=>{var j,C;return(C=(j=f.card.preferences)==null?void 0:j.formatNumber)==null?void 0:C.currency});s.useEditorStore(f=>f.actions.setFilterOnClickField);const c=s.useEditorStore(f=>{var j,C;return(C=(j=f.card.preferences)==null?void 0:j.formatNumber)==null?void 0:C.colorRanges})||[],o=s.useEditorStore(f=>f.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(f=>f.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((x=t==null?void 0:t.formatNumber)!=null&&x.enabled),onCheckedChange:f=>{a({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:f}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:d||"none",onValueChange:f=>{var j,C,I;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((C=t==null?void 0:t.formatNumber)==null?void 0:C.currency)||"",f,((I=t==null?void 0:t.formatNumber)==null?void 0:I.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Format"}),e.jsx(s.SelectItem,{value:"none",children:"Auto"},"none"),s.LOCALE_CURRENCY_PAIRS.map(f=>e.jsx(s.SelectItem,{value:f.locale,children:f.locale},f.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:i||"none",onValueChange:f=>{var j,C,I;console.log("currency",f),l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,f==="none"?"":f,((C=t==null?void 0:t.formatNumber)==null?void 0:C.locale)||"",((I=t==null?void 0:t.formatNumber)==null?void 0:I.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),u.map(f=>e.jsx(s.SelectItem,{value:f,children:f},f))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Decimals"}),e.jsxs(s.Select,{value:((k=(p=t==null?void 0:t.formatNumber)==null?void 0:p.decimalPlaces)==null?void 0:k.toString())||"0",onValueChange:f=>{var j,C,I;return l(Number(f),((j=t==null?void 0:t.formatNumber)==null?void 0:j.currency)||"",((C=t==null?void 0:t.formatNumber)==null?void 0:C.locale)||"",((I=t==null?void 0:t.formatNumber)==null?void 0:I.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["0","1","2","3","4"].map(f=>e.jsx(s.SelectItem,{value:f,children:f},f))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input$1,{value:((m=t==null?void 0:t.formatNumber)==null?void 0:m.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:f=>{var j,C,I;return l(((j=t==null?void 0:t.formatNumber)==null?void 0:j.decimalPlaces)||0,((C=t==null?void 0:t.formatNumber)==null?void 0:C.currency)||"",((I=t==null?void 0:t.formatNumber)==null?void 0:I.locale)||"",f.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(mn,{colorRanges:c,setColorRanges:o})]})]})}function hn(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{type:"single",collapsible:!0,children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(s.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(xn,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function $e({children:t,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,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:a}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const pn=[{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"}],fn=["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"],gn=fn.map(t=>({label:t,value:t}));function jn(){var o,u,x,h,p,k,m,f,j,C,I,O,R,v,w,g,y,T;const t=s.useEditorStore(M=>M.card),a=(u=(o=t==null?void 0:t.preferences)==null?void 0:o.mapVisualOptions)==null?void 0:u.topoJsonUrl,[n,r]=D.useState(((h=(x=t==null?void 0:t.preferences)==null?void 0:x.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:d}=s.useTopoJson(t),i=Object.keys((d==null?void 0:d.objects)||{}).map(M=>({label:M,value:M}))||[],c=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx($e,{summary:"Map Chart",children:e.jsx("p",{className:"rounded-md bg-muted p-2 font-mono text-xs",children:"SELECT country, value FROM table"})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx($e,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(he,{className:"h-9",options:c,onValueChange:M=>{console.log("value",M),l({...t.preferences,mapVisualOptions:{topoJsonUrl:M}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(s.Input$1,{onChange:M=>{r(M.target.value)},onBlur:()=>{var M;console.log("onBlur",n),l({...t.preferences,mapVisualOptions:{...(M=t.preferences)==null?void 0:M.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),d&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(he,{className:"h-9",options:i,value:((k=(p=t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:k.objectKey)||"",label:"Map Object",onValueChange:M=>{var N;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,objectKey:M}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(he,{className:"h-9",options:pn,value:((f=(m=t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:f.projection)||"",label:"Projection",onValueChange:M=>{var N;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,projection:M}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(he,{className:"h-9",options:gn,value:((C=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:C.colorScale)||"",label:"Select Color Scale",onValueChange:M=>{var N;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,colorScale:M}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx($e,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input$1,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((O=(I=t.preferences)==null?void 0:I.mapVisualOptions)==null?void 0:O.projectionScale)||1,onChange:M=>{var N;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,projectionScale:Number(M.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input$1,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((w=(v=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:v.projectionOffset)==null?void 0:w[0])||0,onChange:M=>{var N,b,A,F;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,projectionOffset:[Number(M.target.value),((F=(A=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:F[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input$1,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((T=(y=(g=t.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:y.projectionOffset)==null?void 0:T[1])||0,onChange:M=>{var N,b,A,F;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,projectionOffset:[((F=(A=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:F[0])||0,Number(M.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Se,{})]})}function bn(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:a}=s.useEditorStore(l=>l.actions);function n(l){a({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Oe({cardType:t,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${n}`}),e.jsx(s.AccordionContent,{children:a||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(bn,{})})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(De,{})]})]})]})})}function vn(){const t=s.useEditorStore(r=>{var l,d;return(d=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:d.sortChart}),{setSortChart:a}=s.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(he,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(Os,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(De,{})]})]})]})})}function yn({cardType:t="table"}){console.log("cardType",t);const a=s.useEditorStore(l=>{var d;return(d=l.card)==null?void 0:d.preferences}),n=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{n({...a,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(De,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}function Ps({color:t,onColorChange:a,onClose:n}){const[r,l]=D.useState(0),[d,i]=D.useState(100),[c,o]=D.useState(50),[u,x]=D.useState(t);D.useEffect(()=>{const j=is(t);if(j){const C=cs(j.r,j.g,j.b);l(C.h),i(C.s),o(C.l),x(t)}},[t]);const h=j=>{l(j),k(j,d,c)},p=j=>{const C=j.currentTarget.getBoundingClientRect(),I=Math.max(0,Math.min(1,(j.clientX-C.left)/C.width)),O=Math.max(0,Math.min(1,(j.clientY-C.top)/C.height)),R=I*100,v=(1-O)*100;i(R),o(v),k(r,R,v)},k=(j,C,I)=>{const O=Cn(j,C,I),R=Nn(O.r,O.g,O.b);x(R)},m=j=>{if(x(j),/^#[0-9A-Fa-f]{6}$/.test(j)){const C=is(j);if(C){const I=cs(C.r,C.g,C.b);l(I.h),i(I.s),o(I.l)}}},f=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(a(u),n())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:p,onMouseMove:j=>{j.buttons===1&&p(j)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${d}%`,top:`${100-c}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:j=>h(Number(j.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"HEX"}),e.jsx(s.Input$1,{value:u,onChange:j=>m(j.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:u}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(s.Button,{onClick:f,children:"OK"})]})]})}function is(t){const a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return a?{r:parseInt(a[1],16),g:parseInt(a[2],16),b:parseInt(a[3],16)}:null}function Nn(t,a,n){return"#"+((1<<24)+(t<<16)+(a<<8)+n).toString(16).slice(1)}function cs(t,a,n){t/=255,a/=255,n/=255;const r=Math.max(t,a,n),l=Math.min(t,a,n);let d=0,i=0;const c=(r+l)/2;if(r!==l){const o=r-l;switch(i=c>.5?o/(2-r-l):o/(r+l),r){case t:d=((a-n)/o+(a<n?6:0))/6;break;case a:d=((n-t)/o+2)/6;break;case n:d=((t-a)/o+4)/6;break}}return{h:Math.round(d*360),s:Math.round(i*100),l:Math.round(c*100)}}function Cn(t,a,n){t/=360,a/=100,n/=100;let r,l,d;if(a===0)r=l=d=n;else{const i=(u,x,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?u+(x-u)*6*h:h<.5?x:h<.6666666666666666?u+(x-u)*(.6666666666666666-h)*6:u),c=n<.5?n*(1+a):n+a-n*a,o=2*n-c;r=i(o,c,t+1/3),l=i(o,c,t),d=i(o,c,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(d*255)}}const Sn=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function zs(){var O,R,v,w,g,y,T,M,N,b;const t=s.useEditorStore(A=>A.card),a=s.useEditorStore(A=>{var F;return(F=A.card)==null?void 0:F.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[d,i]=D.useState({}),[c,o]=D.useState(null),[u,x]=D.useState(null),h=D.useMemo(()=>{var L,S,V,K,H,G,q;if(!(l!=null&&l.records)||l.records.length===0)return[];const A=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",F=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line"||(t==null?void 0:t.type)==="horizontalBar"||(t==null?void 0:t.type)==="bullet",E=((L=t==null?void 0:t.config)==null?void 0:L.pivotByColumns)&&t.config.pivotByColumns.length>0;if((A||F)&&E){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const P=new Set;return l.pivotSchema.forEach(z=>{z.alias&&P.add(z.alias)}),Array.from(P)}if(l.records.length>0){const P=l.records[0],z=Object.keys(P),J=new Set;(S=t==null?void 0:t.config)!=null&&S.groupByColumns&&t.config.groupByColumns.forEach(X=>{J.add(X.label||X.name),J.add(X.alias||X.name)});const B=new Set;return(V=t==null?void 0:t.config)!=null&&V.metricColumns&&t.config.metricColumns.forEach(X=>{const ee=X.alias||X.name;B.add(ee),B.add(`${ee}_count`),B.add(`${ee}_sum`),B.add(`${ee}_avg`),B.add(`${ee}_min`),B.add(`${ee}_max`);const _=X.entityName||X.qualifiedEntityName;_&&(B.add(`${_}_${ee}`),B.add(`${_}_${ee}_count`))}),z.filter(X=>!J.has(X)&&!B.has(X))}}if((F||A)&&!E&&((H=(K=t==null?void 0:t.config)==null?void 0:K.metricColumns)!=null&&H.length))return t.config.metricColumns.map(P=>P.alias||P.label||P.name);if((q=(G=t==null?void 0:t.config)==null?void 0:G.groupByColumns)!=null&&q.length){const P=t.config.groupByColumns[0],z=P.label||P.name,J=new Set;return l.records.forEach(B=>{const W=B[z];W!=null&&J.add(String(W))}),Array.from(J)}return[]},[l,(O=t==null?void 0:t.config)==null?void 0:O.groupByColumns,(R=t==null?void 0:t.config)==null?void 0:R.pivotByColumns,(v=t==null?void 0:t.config)==null?void 0:v.metricColumns,t==null?void 0:t.type]),p=D.useMemo(()=>s.getDefaultChartColors(),[]);D.useEffect(()=>{const A={};h.forEach((F,E)=>{A[F]=s.getColorForValue(F,E,a==null?void 0:a.colorConfig)}),i(A)},[h,a==null?void 0:a.colorConfig,p]);const k=(A,F)=>{const E={...d,[A]:F};i(E);const L={...a||{},colorConfig:{segments:E}};n(L);const S={...t,preferences:L};r(S)},m=(A,F)=>{var H;const E=p[F%p.length],{[A]:L,...S}=((H=a==null?void 0:a.colorConfig)==null?void 0:H.segments)||{},V={...a||{},colorConfig:{segments:S}};n(V);const K={...t,preferences:V};r(K),i(G=>({...G,[A]:E}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((g=(w=t==null?void 0:t.config)==null?void 0:w.groupByColumns)==null?void 0:g.length)||((T=(y=t==null?void 0:t.config)==null?void 0:y.pivotByColumns)==null?void 0:T.length):(N=(M=t==null?void 0:t.config)==null?void 0:M.groupByColumns)==null?void 0:N.length)||["table","kpi","text","custom","heatmap"].includes(t.type))return null;const C=()=>{const A={...a||{},colorConfig:{segments:{}}};n(A);const F={...t,preferences:A};r(F);const E={};h.forEach((L,S)=>{E[L]=s.getColorForValue(L,S,void 0)}),i(E)},I=Object.keys(((b=a==null?void 0:a.colorConfig)==null?void 0:b.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nt,{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:I&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:C,children:[e.jsx(ts,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((A,F)=>{const E=s.isDefaultColor(d[A],F),L=!E;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:c===A,onOpenChange:S=>o(S?A: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[A]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:p.slice(0,10).map((S,V)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",d[A]===S?"border-gray-900":"border-transparent"),style:{backgroundColor:S},onClick:()=>{k(A,S),o(null)},children:[V===F%p.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:S})]},`default-${V}`))})]}),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:Sn.map((S,V)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",d[A]===S?"border-2 border-gray-900":S==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:S},onClick:()=>{k(A,S),o(null)},children:e.jsx("span",{className:"sr-only",children:S})},`preset-${V}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{x({value:A,color:d[A]}),o(null)},children:"Custom color"}),!E&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{m(A,F),o(null)},children:[e.jsx(ts,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:A}),L&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},A)})}),u&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>x(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Ps,{color:u.color,onColorChange:A=>{k(u.value,A),x(null)},onClose:()=>x(null)})})]})]})})]})}function pe({value:t,onSave:a,placeholder:n="",type:r="text",className:l=""}){const[d,i]=D.useState(t??""),[c,o]=D.useState(!1);D.useEffect(()=>{i(t??"")},[t]);const u=()=>{a(d),o(!1)},x=()=>{i(t??""),o(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input,{placeholder:n,type:r,value:c?d:t??"",onChange:h=>{i(h.target.value),o(!0)},onFocus:()=>o(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&c&&d!==t?u():h.key==="Escape"&&x()},"aria-label":n||"Edit field"}),c&&d!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:x,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const wn=["auto","number","currency","percent","scientific","date"],kn=[{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"}],Tn=[{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"}],En=t=>t.charAt(0).toUpperCase()+t.slice(1);function _e({formatOptions:t={},onFormatOptionsChange:a,showTitle:n=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",d=(c,o)=>{a({...t,[c]:o})},i=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[n&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:c=>d("type",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:wn.map(c=>e.jsx(s.SelectItem,{value:c,className:"text-xs",children:c==="auto"?"Auto (Default)":En(c)},c))})]})]}),l!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(l)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??i(),onChange:c=>d("decimalPlaces",parseInt(c.target.value)||0),className:"h-8 text-xs"})})]}),l==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:c=>d("currency",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:kn.map(c=>e.jsx(s.SelectItem,{value:c.value,className:"text-xs",children:c.label},c.value))})]})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:c=>d("useSuffix",c)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:c=>d("locale",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Tn.map(c=>e.jsx(s.SelectItem,{value:c.value,className:"text-xs",children:c.label},c.value))})]})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{placeholder:"e.g., $",value:t.prefix||"",onChange:c=>d("prefix",c.target.value),className:"h-8 text-xs"})})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{placeholder:"e.g., units",value:t.suffix||"",onChange:c=>d("suffix",c.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:c=>d("negativeInParentheses",c)})]}),l==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:c=>d("multiplyBy",c.target.value?parseFloat(c.target.value):void 0),className:"h-8 text-xs"})})]}),l==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:c=>d("dateFormat",c.target.value),className:"h-8 text-xs"})})]})]})]})}function ds({axis:t,label:a,type:n,config:r,onChange:l}){var h,p,k,m,f,j,C,I,O,R,v,w;const d=(g,y)=>{l({...r,[g]:y})},i=(g,y)=>{var T,M;l({...r,name:{enabled:g==="enabled"?y:((T=r==null?void 0:r.name)==null?void 0:T.enabled)??!1,text:g==="text"?y:(M=r==null?void 0:r.name)==null?void 0:M.text}})},c=(g,y)=>{var T,M;l({...r,labels:{enabled:g==="enabled"?y:((T=r==null?void 0:r.labels)==null?void 0:T.enabled)??!0,rotation:g==="rotation"?y:(M=r==null?void 0:r.labels)==null?void 0:M.rotation}})},o=(g,y)=>{l({...r,scale:{...r==null?void 0:r.scale,[g]:y===""?"auto":Number(y)}})},u=t==="x"?["auto","top","bottom"]:["auto","left","right"],x=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:a})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:g=>d("enabled",g),onClick:g=>g.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:g=>i("enabled",g)})]}),((p=r==null?void 0:r.name)==null?void 0:p.enabled)&&e.jsx(pe,{placeholder:`${a} title`,value:((k=r==null?void 0:r.name)==null?void 0:k.text)||"",onSave:g=>i("text",g),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:g=>d("position",g),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(g=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:g==="auto"?"Auto (Default)":s.titleCase(g)},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",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((m=r==null?void 0:r.labels)==null?void 0:m.enabled)!==!1,onCheckedChange:g=>c("enabled",g)})]}),((f=r==null?void 0:r.labels)==null?void 0:f.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((j=r==null?void 0:r.labels)==null?void 0:j.rotation)||"auto"),onValueChange:g=>c("rotation",g==="auto"?"auto":Number(g)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:x.map(g=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:g==="auto"?"Auto (Default)":`${g}°`},g))})]})]})]}),n==="value"&&e.jsx(_e,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:g=>l({...r,formatOptions:g}),showTitle:!0,title:"FORMAT"}),n==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"auto",value:((C=r==null?void 0:r.scale)==null?void 0:C.min)==="auto"||((I=r==null?void 0:r.scale)==null?void 0:I.min)===void 0?"":String(r.scale.min),onSave:g=>o("min",g),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"auto",value:((O=r==null?void 0:r.scale)==null?void 0:O.max)==="auto"||((R=r==null?void 0:r.scale)==null?void 0:R.max)===void 0?"":String(r.scale.max),onSave:g=>o("max",g),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"auto",value:((v=r==null?void 0:r.scale)==null?void 0:v.stepSize)==="auto"||((w=r==null?void 0:r.scale)==null?void 0:w.stepSize)===void 0?"":String(r.scale.stepSize),onSave:g=>o("stepSize",g),className:""})})]})]})]})]})]})}function $s(){const t=s.useEditorStore(i=>i.card),a=s.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi","treemap"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,a);if(!l.hasXAxis&&!l.hasYAxis)return null;const d=(i,c)=>{const u={...a||{},[i==="x"?"xAxisConfig":"yAxisConfig"]:c};n(u);const x={...t,preferences:u};r(x)};return e.jsxs(s.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ss,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[l.hasXAxis&&e.jsx(ds,{axis:"x",label:"X-Axis",type:l.xAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(t.type,"x"),a==null?void 0:a.xAxisConfig),onChange:i=>d("x",i)}),l.hasYAxis&&e.jsx(ds,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(t.type,"y"),a==null?void 0:a.yAxisConfig),onChange:i=>d("y",i)})]})})]})}function Ks(){const t=s.useEditorStore(x=>x.card),a=s.useEditorStore(x=>{var h,p,k,m;return(m=(k=(p=(h=x.card)==null?void 0:h.preferences)==null?void 0:p.chartOptions)==null?void 0:k.plugins)==null?void 0:m.legend}),{setLegendOptions:n}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r=s.getDefaultLegendConfig(t.type),l=(r==null?void 0:r.display)??!0,d=(r==null?void 0:r.position)??"top",i=(r==null?void 0:r.align)??"center",c=(x,h)=>{const p={...a,[x]:h};n(p)},o=["top","bottom","left","right"],u=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pt,{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)??l,onCheckedChange:x=>c("display",x)})]}),((a==null?void 0:a.display)??l)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(a==null?void 0:a.position)||d,onValueChange:x=>c("position",x),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:o.map(x=>e.jsx(s.SelectItem,{value:x,className:"text-xs",children:s.titleCase(x)},x))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(a==null?void 0:a.align)||i,onValueChange:x=>c("align",x),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(x=>e.jsx(s.SelectItem,{value:x,className:"text-xs",children:s.titleCase(x)},x))})]})]})]})]})})]})}function Gs(){var E,L,S,V,K,H,G,q,P,z,J;const t=s.useEditorStore(B=>B.card),a=s.useEditorStore(B=>{var W,X;return(X=(W=B.card)==null?void 0:W.preferences)==null?void 0:X.dataLabelsConfig}),n=s.useEditorStore(B=>{var W;return(W=B.card)==null?void 0:W.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const d=t.type==="bullet"?((E=n==null?void 0:n.bulletConfig)==null?void 0:E.orientation)??(((L=n==null?void 0:n.chartOptions)==null?void 0:L.indexAxis)==="x"?"vertical":"horizontal"):void 0,i=d!=null?d==="horizontal":((S=n==null?void 0:n.chartOptions)==null?void 0:S.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",o=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",u=!o,x=t.type==="bubble"||t.type==="scatter",h=(K=(V=n==null?void 0:n.chartOptions)==null?void 0:V.plugins)==null?void 0:K.datalabels,p=(h==null?void 0:h.display)!==!1&&((h==null?void 0:h.anchor)||(h==null?void 0:h.align)),k=s.getDefaultDataLabelsConfig(t.type,t.preferences),m=a??k,f=(k==null?void 0:k.enabled)??p??!1,j=(a==null?void 0:a.enabled)!==void 0?a.enabled:f,C=(B,W)=>{const _={...k??{},...a??{},[B]:W};B==="enabled"&&(_.display=W,W&&x&&!_.position&&(_.position="bottom")),B==="position"&&x&&(_.position="bottom");const ne={...t.preferences||{},dataLabelsConfig:_};r(ne);const Y={...t,preferences:ne};l(Y)},I=(B,W)=>{const X=a??{},_={...k??{},...X,font:{...X.font||{},[B]:W}},ne={...t.preferences||{},dataLabelsConfig:_};r(ne);const Y={...t,preferences:ne};l(Y)},O=(B,W)=>{const X=a??{},_={...k??{},...X,formatOptions:{...X.formatOptions||{},[B]:W}},ne={...t.preferences||{},dataLabelsConfig:_};r(ne);const Y={...t,preferences:ne};l(Y)},R=()=>{const B=t.type;return B==="stackedBar"||B==="stackedLine"||B==="pie"||B==="doughnut"?"center":i?"right":"top"},v=t.type!=="treemap"&&t.type!=="heatmap",w=t.type!=="treemap",g=R();let y=[];if(v)if(x)y=["bottom"];else if(c||o)y=["center"];else{const B=i?["center","left","right"]:["center","top","bottom"];y=["auto",...t.type==="bullet"?B:B.filter(X=>X!==g),"custom"]}const T=()=>s.titleCase(g),M=["center","start","end"],N=["center","start","end","top","bottom"],b=u?["auto","number","currency","percent","none"]:["number","currency","percent","none"],A=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"}],F=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Et,{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:j,onCheckedChange:B=>C("enabled",B)})]}),j&&e.jsxs(e.Fragment,{children:[v&&!c&&!o&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:x?(m==null?void 0:m.position)||"bottom":(m==null?void 0:m.position)||"auto",onValueChange:B=>C("position",B),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:y.map(B=>e.jsx(s.SelectItem,{value:B,className:"text-xs",children:B==="auto"?T():B==="custom"?"Custom (Advanced)":s.titleCase(B)},B))})]})]}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(a==null?void 0:a.showTotal)??!1,onCheckedChange:B=>C("showTotal",B)})]}),(m==null?void 0:m.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(s.Select,{value:(m==null?void 0:m.anchor)||"center",onValueChange:B=>C("anchor",B),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:M.map(B=>e.jsx(s.SelectItem,{value:B,className:"text-xs",children:s.titleCase(B)},B))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(s.Select,{value:String((m==null?void 0:m.align)||"center"),onValueChange:B=>C("align",B),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:N.map(B=>e.jsx(s.SelectItem,{value:B,className:"text-xs",children:s.titleCase(B)},B))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(m==null?void 0:m.format)||(u?"auto":"none"),onValueChange:B=>C("format",B),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:b.map(B=>e.jsx(s.SelectItem,{value:B,className:"text-xs",children:B==="auto"&&u?"Auto (Use Axis)":B==="none"?"None (Raw Value)":s.titleCase(B)},B))})]})]}),(m==null?void 0:m.format)&&!["auto","none"].includes(m.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(m.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"0",value:String(((H=m==null?void 0:m.formatOptions)==null?void 0:H.decimalPlaces)??(m.format==="currency"?2:m.format==="percent"?1:0)),onSave:B=>O("decimalPlaces",Number(B)),className:""})})]}),m.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((G=m==null?void 0:m.formatOptions)==null?void 0:G.currency)||"USD",onValueChange:B=>O("currency",B),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:A.map(B=>e.jsx(s.SelectItem,{value:B.value,className:"text-xs",children:B.label},B.value))})]})]}),["number","currency"].includes(m.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((q=m==null?void 0:m.formatOptions)==null?void 0:q.useSuffix)??!1,onCheckedChange:B=>O("useSuffix",B)})]}),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:((P=m==null?void 0:m.formatOptions)==null?void 0:P.locale)||"en-US",onValueChange:B=>O("locale",B),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:F.map(B=>e.jsx(s.SelectItem,{value:B.value,className:"text-xs",children:B.label},B.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(pe,{type:"number",placeholder:"12",value:String(((z=m==null?void 0:m.font)==null?void 0:z.size)||12),onSave:B=>I("size",Number(B)),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:((J=m==null?void 0:m.font)==null?void 0:J.weight)||"normal",onValueChange:B=>I("weight",B),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(s.Select,{value:(m==null?void 0:m.color)==="auto"||!(m!=null&&m.color)?"auto":"custom",onValueChange:B=>{B==="auto"&&C("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"0",value:String((m==null?void 0:m.rotation)||0),onSave:B=>C("rotation",Number(B)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const us=["poor","satisfactory","good"];function ms(t){if(!t)return;const a={...t};return a.targetMetricKey||delete a.targetMetricKey,a.comparativeMetricKey||delete a.comparativeMetricKey,!a.targetValue&&a.targetValue!==0&&delete a.targetValue,(!a.rangeKeys||Object.keys(a.rangeKeys).length===0)&&delete a.rangeKeys,(!a.ranges||Object.keys(a.ranges).length===0)&&delete a.ranges,(!a.rangeLabels||Object.keys(a.rangeLabels).length===0)&&delete a.rangeLabels,a}function qs(){var A,F;const t=s.useEditorStore(E=>E.card.preferences),a=s.useEditorStore(E=>E.card),n=s.useEditorStore(E=>E.isDevMode),{setCardPreferences:r,setChartOrientation:l}=s.useEditorActions(),d=D.useMemo(()=>(t==null?void 0:t.bulletConfig)||{},[t==null?void 0:t.bulletConfig]),c=s.hasValidCardConfig(a==null?void 0:a.config)&&!n,[o,u]=D.useState(d.showRanges??!1),[x,h]=D.useState(d.rangesArePercentages??!1),p=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!c,[k,m]=D.useState(p);D.useEffect(()=>{u(d.showRanges??!1)},[d.showRanges]),D.useEffect(()=>{h(d.rangesArePercentages??!1)},[d.rangesArePercentages]);const f=d.targetValue===void 0?"":String(d.targetValue);D.useEffect(()=>{const E=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!c;m(E)},[d.disableAutoComparative,d.comparativeMetricKey,c]);const j=D.useMemo(()=>{var E,L;return((L=(E=a==null?void 0:a.config)==null?void 0:E.metricColumns)==null?void 0:L.map(S=>{const V=S.label||S.name||S.alias||"";return{value:V,label:V}}))||[]},[(A=a==null?void 0:a.config)==null?void 0:A.metricColumns]);D.useEffect(()=>{var q,P;if(!t||j.length===0)return;const E={};let L=!1;const S=(q=j[1])==null?void 0:q.value;!d.targetMetricKey&&S&&(E.targetMetricKey=S,L=!0);const V=(P=j[2])==null?void 0:P.value;!d.comparativeMetricKey&&!d.disableAutoComparative&&V&&(E.comparativeMetricKey=V,L=!0);const K=j.slice(3),H={...d.rangeKeys||{}};let G=!1;if(us.forEach((z,J)=>{!H[z]&&K[J]&&(H[z]=K[J].value,G=!0)}),G&&(E.rangeKeys=H,L=!0,d.showRanges===void 0&&(E.showRanges=!0)),L){const z=ms({...d,...E});r({...t,bulletConfig:z})}},[j,d,t,r]);const C=E=>{const L=ms({...d,...E});r({...t,bulletConfig:L})},I=(E,L)=>{const S={...d.rangeKeys||{},[E]:L.trim()};L.trim()||delete S[E],C({rangeKeys:Object.keys(S).length>0?S:void 0})},O=(E,L)=>{const S=L===""?void 0:Number(L),V={...d.ranges||{}};S===void 0||Number.isNaN(S)?delete V[E]:V[E]=S,C({ranges:Object.keys(V).length?V:void 0})},R=E=>{if(E===""){C({targetValue:void 0});return}const L=Number(E);C({targetValue:Number.isNaN(L)?void 0:L})},v=(E,L)=>{const S=L.trim(),V={...d.rangeLabels||{}};S?V[E]=S:delete V[E],C({rangeLabels:Object.keys(V).length>0?V:void 0})},w=E=>{u(E),C({showRanges:E})},g=E=>{h(E),C({rangesArePercentages:E})},y=d.orientation||(((F=t==null?void 0:t.chartOptions)==null?void 0:F.indexAxis)==="y"?"horizontal":"vertical"),T=E=>{C({orientation:E}),l(E==="horizontal"?"y":"x")},M=[{value:"__none",label:"None"},...j.map(E=>({value:E.value,label:E.label}))],N=M,b=E=>{if(m(E),!E){C({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!c){C({disableAutoComparative:!1});return}if(d.comparativeMetricKey)C({disableAutoComparative:!1});else{const L=j.find(S=>S.value!==d.targetMetricKey);C({comparativeMetricKey:L==null?void 0:L.value,disableAutoComparative:!1})}};return e.jsxs(s.AccordionItem,{value:"bullet-config",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-6 border-t border-border/50 py-4",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"ORIENTATION"}),e.jsxs(s.Select,{value:y,onValueChange:E=>T(E),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"horizontal",className:"text-xs",children:"Horizontal"}),e.jsx(s.SelectItem,{value:"vertical",className:"text-xs",children:"Vertical"})]})]})]}),c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TARGET METRIC"}),e.jsxs(s.Select,{value:d.targetMetricKey||"__none",onValueChange:E=>C({targetMetricKey:E==="__none"?void 0:E}),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"}),j.map(E=>e.jsx(s.SelectItem,{value:E.value,className:"text-xs",children:E.label},E.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),c?e.jsxs(s.Select,{value:d.comparativeMetricKey||"__none",onValueChange:E=>C({comparativeMetricKey:E==="__none"?void 0:E,disableAutoComparative:E==="__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(E=>e.jsx(s.SelectItem,{value:E.value,className:"text-xs",children:E.label},E.value))})]}):e.jsxs("div",{className:"space-y-2 rounded-md border border-border/50 p-3 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between font-medium",children:[e.jsx("span",{children:"Show comparative"}),e.jsx(s.SmallSwitch,{checked:k,onCheckedChange:E=>b(E)})]}),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(ie,{type:"number",className:"h-8 text-xs",value:f,onCommit:R,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:w})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:x,disabled:!o,onChange:E=>g(E.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),o&&e.jsx("div",{className:"space-y-3",children:us.map(E=>{var L,S,V,K,H;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:[E," LABEL"]}),e.jsx(ie,{placeholder:`Display label (${E})`,value:((L=d.rangeLabels)==null?void 0:L[E])||"",onCommit:G=>v(E,G),className:"h-8 text-xs"})]}),c?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[E," COLUMN"]}),e.jsxs(s.Select,{value:((S=d.rangeKeys)==null?void 0:S[E])||"__none",onValueChange:G=>{G==="__none"?I(E,""):I(E,G)},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select column"})}),e.jsx(s.SelectContent,{children:N.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:[E," COLUMN KEY"]}),e.jsx(ie,{placeholder:"Column key",value:((V=d.rangeKeys)==null?void 0:V[E])||"",onCommit:G=>I(E,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:[E," VALUE"]}),e.jsx(ie,{type:"number",placeholder:x?"0.80":"Static value",value:((K=d.ranges)==null?void 0:K[E])===void 0?"":String((H=d.ranges)==null?void 0:H[E]),onCommit:G=>O(E,G),className:"h-8 text-xs"})]})]},E)})})]})]})]})}const xs=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],An=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Le({value:t,onChange:a,label:n}){const[r,l]=D.useState(!1),[d,i]=D.useState(!1),c=()=>{const o=xs.find(u=>u.value===t);return o?o.color:t.startsWith("#")?t:xs[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:c()},"aria-label":`Change color for ${n}`})}),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:An.map(o=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",c()===o?"border-gray-900":"border-transparent"),style:{backgroundColor:o},onClick:()=>{a(o),l(!1)},children:e.jsx("span",{className:"sr-only",children:o})},o))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{i(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:n})]}),d&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>i(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Ps,{color:c(),onColorChange:o=>{a(o),i(!1)},onClose:()=>i(!1)})})]})]})}const In=Object.keys(s.HEATMAP_PRESET_PALETTES);function Us(){const t=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>{var k;return(k=p.card)==null?void 0:k.preferences}),{setCardPreferences:n}=s.useEditorActions(),r=(t==null?void 0:t.type)==="heatmap",l=(a==null?void 0:a.heatmapConfig)||{},d=l.colorPalette??"green",i=l.legendPosition??"bottom",c=D.useMemo(()=>l.colorRange&&l.colorRange[0]&&l.colorRange[1]?[l.colorRange[0],l.colorRange[1]]:[...s.DEFAULT_HEATMAP_CUSTOM_RANGE],[l.colorRange]),o=p=>{const k={...l,...p};k.colorPalette!=="custom"?delete k.colorRange:(!k.colorRange||!k.colorRange[0]||!k.colorRange[1])&&(k.colorRange=[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]),n({...a||{},heatmapConfig:k})},u=p=>{o({colorPalette:p,colorRange:p==="custom"?l.colorRange??[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},x=(p,k)=>{const m=[...c];m[p]=k,o({colorPalette:"custom",colorRange:m})},h=p=>{o({legendPosition:p})};return r?e.jsxs(s.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(s.RadioGroup,{value:d,onValueChange:p=>u(p??"blue"),className:"space-y-3",children:[In.map(p=>{const k=s.HEATMAP_PRESET_PALETTES[p];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`heatmap-${p}`,value:p}),e.jsxs(s.Label,{htmlFor:`heatmap-${p}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:k.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${k.start}, ${k.end})`}})]})]},p)}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(s.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),d==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(Le,{value:c[0],onChange:p=>x(0,p),label:"Start color"}),e.jsx(Le,{value:c[1],onChange:p=>x(1,p),label:"End color"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Color scale position"}),e.jsxs(s.Select,{value:i,onValueChange:p=>h(p??"bottom"),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["top","bottom","left","right"].map(p=>e.jsx(s.SelectItem,{value:p,className:"text-xs",children:p[0].toUpperCase()+p.slice(1)},p))})]})]})]})]}):null}function hs(t){if(!t)return;const a={...t};if(a.xMetricKey||delete a.xMetricKey,a.yMetricKey||delete a.yMetricKey,a.radiusMetricKey||delete a.radiusMetricKey,a.labelKey||delete a.labelKey,a.groupKey||delete a.groupKey,a.enableGrouping===void 0&&delete a.enableGrouping,a.radiusScale||delete a.radiusScale,a.fixedRadius===void 0&&delete a.fixedRadius,a.minRadius===void 0&&delete a.minRadius,a.maxRadius===void 0&&delete a.maxRadius,Object.keys(a).length!==0)return a}function Hs(){var v,w,g,y,T,M,N,b,A,F,E,L;const t=s.useEditorStore(S=>S.card.preferences),a=s.useEditorStore(S=>S.card),n=s.useEditorStore(S=>S.card.type),r=s.useEditorStore(S=>S.isDevMode),{setCardPreferences:l,updateCardInFrame:d}=s.useEditorActions(),i=n==="bubble",c=n==="scatter",o=D.useMemo(()=>(t==null?void 0:t.bubbleScatterConfig)||{},[t==null?void 0:t.bubbleScatterConfig]),x=s.hasValidCardConfig(a==null?void 0:a.config)&&!r,h=D.useMemo(()=>{var S,V;return((V=(S=a==null?void 0:a.config)==null?void 0:S.metricColumns)==null?void 0:V.map(K=>{const H=K.label||K.name||K.alias||"";return{value:H,label:H}}))||[]},[(v=a==null?void 0:a.config)==null?void 0:v.metricColumns]),p=D.useMemo(()=>{var S,V;return((V=(S=a==null?void 0:a.config)==null?void 0:S.groupByColumns)==null?void 0:V.map(K=>{const H=K.label||K.name||K.alias||"";return{value:H,label:H}}))||[]},[(w=a==null?void 0:a.config)==null?void 0:w.groupByColumns]),k=D.useMemo(()=>o.enableGrouping!==void 0?o.enableGrouping:!r&&p.length>=2,[o.enableGrouping,r,p.length]),[m,f]=D.useState(k);D.useEffect(()=>{f(k)},[k]);const j=S=>{const V={...t||{},bubbleScatterConfig:S};l(V),a&&d({...a,preferences:V})},C=S=>{l(S),a&&d({...a,preferences:S})};D.useEffect(()=>{if(!t||h.length===0)return;const S={};let V=!1;if(!o.xMetricKey&&h[0]&&(S.xMetricKey=h[0].value,V=!0),!o.yMetricKey&&h[1]&&(S.yMetricKey=h[1].value,V=!0),i&&!o.radiusMetricKey&&h[2]&&(S.radiusMetricKey=h[2].value,V=!0),!o.labelKey&&p[0]&&(S.labelKey=p[0].value,V=!0),k&&!o.groupKey&&p[1]&&(S.groupKey=p[1].value,S.enableGrouping=!0,V=!0),V){const K=hs({...o,...S});j(K)}},[h,p,o,t,l,i,k]);const I=S=>{const V=hs({...o,...S});j(V)},O=S=>{f(S),I({enableGrouping:S,groupKey:S?o.groupKey:void 0})};if(!i&&!c)return null;const R=i?s.Circle:s.ChartScatter;return e.jsxs(s.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(s.AccordionTrigger,{className:"py-2 text-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R,{className:"h-4 w-4"}),e.jsxs("span",{children:[i?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-1 pb-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-muted-foreground",children:["Dimensions",e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(s.Info,{className:"h-3 w-3"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{children:"Label identifies each point. Group creates separate series in the legend."})})]})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Label Column"}),x?e.jsxs(s.Select,{value:o.labelKey||"",onValueChange:S=>I({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:p.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(ie,{className:"h-8 text-xs",placeholder:"Column name for labels",value:o.labelKey||"",onCommit:S=>I({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:m,onCheckedChange:O})]}),m&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Group By"}),x?e.jsxs(s.Select,{value:o.groupKey||"",onValueChange:S=>I({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:p.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(ie,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:o.groupKey||"",onCommit:S=>I({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"}),x?e.jsxs(s.Select,{value:o.xMetricKey||"",onValueChange:S=>I({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:h.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(ie,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:o.xMetricKey||"",onCommit:S=>I({xMetricKey:S})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Axis"}),x?e.jsxs(s.Select,{value:o.yMetricKey||"",onValueChange:S=>I({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:h.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(ie,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:o.yMetricKey||"",onCommit:S=>I({yMetricKey:S})})]}),i&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Radius"}),x?e.jsxs(s.Select,{value:o.radiusMetricKey||"",onValueChange:S=>I({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:h.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(ie,{className:"h-8 text-xs",placeholder:"Column name for radius",value:o.radiusMetricKey||"",onCommit:S=>I({radiusMetricKey:S})})]})]}),i&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Radius Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Scale Mode"}),e.jsxs(s.Select,{value:o.radiusScale||"sqrt",onValueChange:S=>I({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(ie,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((g=o.minRadius)==null?void 0:g.toString())||"",onCommit:S=>I({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(ie,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((y=o.maxRadius)==null?void 0:y.toString())||"",onCommit:S=>I({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])=>I({fixedRadius:S}),min:3,max:30,step:1,className:"py-2"})]})]}),c&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Point Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(s.Label,{className:"text-xs",children:["Point Size: ",o.fixedRadius||5]}),e.jsx(s.Slider,{value:[o.fixedRadius||5],onValueChange:([S])=>I({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=(T=t==null?void 0:t.xAxisConfig)==null?void 0:T.name)==null?void 0:M.enabled)??!1,onCheckedChange:S=>{var H,G,q,P;const V=o.xMetricKey||"X Axis",K=o.yMetricKey||"Y Axis";C({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{enabled:S,text:((G=(H=t==null?void 0:t.xAxisConfig)==null?void 0:H.name)==null?void 0:G.text)||V}},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{enabled:S,text:((P=(q=t==null?void 0:t.yAxisConfig)==null?void 0:q.name)==null?void 0:P.text)||K}}})}})]}),((b=(N=t==null?void 0:t.xAxisConfig)==null?void 0:N.name)==null?void 0:b.enabled)&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"X Title"}),e.jsx(ie,{className:"h-8 text-xs",placeholder:o.xMetricKey||"X Axis",value:((F=(A=t==null?void 0:t.xAxisConfig)==null?void 0:A.name)==null?void 0:F.text)||"",onCommit:S=>{var V;C({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{...(V=t==null?void 0:t.xAxisConfig)==null?void 0:V.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(ie,{className:"h-8 text-xs",placeholder:o.yMetricKey||"Y Axis",value:((L=(E=t==null?void 0:t.yAxisConfig)==null?void 0:E.name)==null?void 0:L.text)||"",onCommit:S=>{var V;C({...t??{},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{...(V=t==null?void 0:t.yAxisConfig)==null?void 0:V.name,enabled:!0,text:S||o.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const Dn=[{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 Js(){const t=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>{var k;return(k=p.card)==null?void 0:k.preferences}),{setCardPreferences:n}=s.useEditorActions(),r=(t==null?void 0:t.type)==="funnel",l=(a==null?void 0:a.funnelConfig)||{},d=l.percentMode??"percentOfTotal",i=l.shrinkFraction??1,c=l.labelThreshold??0,o=p=>{const k={...l,...p};n({...a||{},funnelConfig:k})},u=p=>{o({percentMode:p})},x=p=>{o({shrinkFraction:p[0]})},h=p=>{o({labelThreshold:p[0]})};return r?e.jsxs(s.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Filter,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Funnel Settings"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"PERCENTAGE MODE"}),e.jsx(s.RadioGroup,{value:d,onValueChange:p=>u(p),className:"space-y-2",children:Dn.map(p=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`funnel-${p.value}`,value:p.value,className:"mt-0.5"}),e.jsxs(s.Label,{htmlFor:`funnel-${p.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:p.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p.description})]})]},p.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SEGMENT SHRINK"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Same Width"}),e.jsx(s.Slider,{value:[i],onValueChange:x,min:0,max:1,step:.1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Full Shrink"})]}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Current: ",Math.round(i*100),"%"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABEL VISIBILITY THRESHOLD"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Show All"}),e.jsx(s.Slider,{value:[c],onValueChange:h,min:0,max:25,step:1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Hide Small"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:c===0?"Showing all labels":`Hide labels below ${c}%`})]})]})]}):null}function Mn(){const t=s.useEditorStore(a=>a.card);return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[(t==null?void 0:t.type)==="funnel"&&e.jsx(Js,{}),(t==null?void 0:t.type)==="heatmap"&&e.jsx(Us,{}),(t==null?void 0:t.type)==="bullet"&&e.jsx(qs,{}),((t==null?void 0:t.type)==="bubble"||(t==null?void 0:t.type)==="scatter")&&e.jsx(Hs,{}),e.jsx(zs,{}),e.jsx($s,{}),e.jsx(Ks,{}),e.jsx(Gs,{})]})]})}const Ln=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT dimension, cohort, metric FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),Fn=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),On=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function Rn(){const t=s.useEditorStore(n=>n.card.type);function a(n){const r=["kpi","table","text","map","custom"],l=d=>r.includes(n)?d:e.jsxs(e.Fragment,{children:[d,e.jsx(Mn,{})]});switch(n){case"stackedBar":case"stackedLine":return l(e.jsx(vn,{}));case"tornado":case"pyramid":return l(e.jsx(Oe,{docContent:Ln,cardType:n}));case"kpi":return e.jsx(hn,{});case"line":case"bar":return l(e.jsx(rn,{cardType:n}));case"range":return l(e.jsx(Oe,{docContent:Fn,cardType:n}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(Oe,{cardType:n}));case"bubble":case"scatter":return l(e.jsx(ln,{cardType:n}));case"table":return e.jsx(yn,{cardType:n});case"text":return e.jsx(Oe,{docContent:On,cardType:n,suffix:"Visual"});case"map":return e.jsx(jn,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Fs,{})});default:return l(e.jsx(dn,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[a(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Bn(){const t=D.useRef(null),a=D.useRef(null),n=s.useEditorStore(l=>l.isShowingVisual),r=s.useEditorStore(l=>l.showAIDialog);return D.useEffect(()=>{var l,d,i,c;r?((l=t.current)==null||l.resize(0),(d=a.current)==null||d.resize(0)):((i=t.current)==null||i.resize(25),(c=a.current)==null||c.resize(25))},[r]),e.jsxs(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Vt,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!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(Rn,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(os,{})})]}):e.jsx(os,{})})]})}function Vn(t){var ce;s.useAIInteractionStore($=>$.currentAIContext);const[a,n]=D.useState(""),[r,l]=D.useState(null),{authToken:d,tokenProps:i}=s.useSemaphorContext(),c=s.useEditorStore($=>{var se;return(se=$==null?void 0:$.card)==null?void 0:se.sql}),o=s.useEditorStore($=>$.isDevMode),u=s.useEditorStore($=>{var se;return(se=$==null?void 0:$.card)==null?void 0:se.python}),{setCardPython:x,setCardSql:h,setRunSql:p,switchCardType:k,setQueryConfig:m}=s.useEditorActions(),f=s.useEditorStore($=>$.currentAssitantScope)||[],j=s.useEditorStore($=>$.userInputForAI),C=s.useEditorStore($=>$.triggerAIRun),I=s.useEditorStore($=>$.card),O=s.useEditorStore($=>$.selectedDatabaseName),R=s.useEditorStore($=>$.selectedTableName),v=s.useEditorStore($=>$.selectedConnectionId),w=s.useEditorStore($=>$.selectedSchemaName),g=s.useDashboardStore($=>$.dashboard.aiScopeTables),{errorMessage:y,refetch:T,data:M}=s.useDashboardCardQuery(I),{setTriggerAIRun:N,setCurrentAssitantScope:b,setCardConfig:A}=s.useEditorActions(),{selectedDatamodelName:F,connectionType:E,selectedDatamodelId:L}=s.useEditorAside(),S=(ce=s.useDashboardQuery().data)==null?void 0:ce.assistantProfileId,{messages:V,setMessages:K,regenerate:H,error:G,sendMessage:q,status:P,addToolResult:z,stop:J,clearError:B}=s.useChat({transport:new s.DefaultChatTransport({api:`${i.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${d==null?void 0:d.accessToken}`}),body:()=>{const $=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:S,isDevMode:o,aiContext:$.currentAIContext,reasoningEffort:$.reasoningEffort,showReasoning:$.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:$,body:se})=>({body:{...se,messages:s.cleanupIncompleteMessages($)}})}),onError:$=>{var se;if($.name==="AbortError"||(se=$.message)!=null&&se.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",$)},onToolCall:W,onFinish({isAbort:$,isDisconnect:se,isError:de}){n(""),console.log($?"[Editor Assistant] Stream aborted by user":se?"[Editor Assistant] Stream disconnected (network error)":de?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});D.useEffect(()=>{C&&j&&(q({role:"user",parts:[{type:"text",text:j}]}),N(!1))},[C,j,q,N]);async function W({toolCall:$}){var se,de,ue,we,me,je,xe,be,ke,fe,Te,Ee,Ae,Ie,ve,ye;if(["createChartFromSql","createForecast"].includes($.toolName)){const Q=((se=$.input)==null?void 0:se.sql)??((de=$.args)==null?void 0:de.sql),ae=((ue=$.input)==null?void 0:ue.python)??((we=$.args)==null?void 0:we.python),re=((me=$.input)==null?void 0:me.chartType)??((je=$.args)==null?void 0:je.chartType);k(re),h(Q),x(ae),p(!0),z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if($.toolName==="getUserSql"){if(!c){z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",message:"No SQL found"}});return}z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",sql:c,python:u||""}})}else if($.toolName==="generateQueryConfig"){n("Generating query config...");const Q=((xe=$.input)==null?void 0:xe.chartType)??((be=$.args)==null?void 0:be.chartType),ae=((ke=$.input)==null?void 0:ke.queryConfig)??((fe=$.args)==null?void 0:fe.queryConfig);((Te=$.input)==null?void 0:Te.cardConfig)??((Ee=$.args)==null||Ee.cardConfig),k(Q),A(ae),h(void 0),x(void 0);const re=await T();if((Ae=re==null?void 0:re.data)!=null&&Ae.error){z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",queryConfig:ae,message:(Ie=re==null?void 0:re.data)==null?void 0:Ie.error.message}});return}if((ve=re==null?void 0:re.data)!=null&&ve.records){z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:ae,message:"The data has been visualized"}});return}z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:ae,message:"The data has been visualized",records:(ye=re==null?void 0:re.data)==null?void 0:ye.records}})}else n("Analyzing...")}function X($){const se=s.removeFromScopeArray(f,$);ee(se)}function ee($){const se=s.sanitizeAIScope($);b(se),K(de=>[...de,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(se)}`}]}])}function _(){const $={databaseName:O||"",schemaName:w||"",tableName:R||"",datamodelId:L||"",datamodelName:s.resolveDatamodelName(F),connectionId:v||"",connectionType:E||""},se=s.dedup([...f,$]);ee(se)}function ne(){const $={databaseName:O||"",schemaName:w||"",tableName:R||"",datamodelName:s.resolveDatamodelName(F),connectionId:v||"",connectionType:E||"",datamodelId:L||""};if(!s.isInAiScopeArray([...g||[],...f],$)||f.length===0){const de=s.dedup([...g||[],...f,$]).filter(ue=>ue.connectionId===$.connectionId);ee(de)}}const Y=!["ready","error"].includes(P),le=s.getErrorMessage(G);return{messages:V,setMessages:K,sendMessage:q,regenerate:H,isLoading:Y,handleSetAIScope:ne,handleAddCurrentTableToScope:_,removeFromCurrentSelections:X,currentAssitantScope:f,setCurrentAssitantScope:b,stop:J,status:P,toolStatus:a,llmUsage:r,onFinish:t,errorMessage:le,clearError:B}}const Pn=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function ps({isFullscreen:t,onFullscreenChange:a,fullscreenContainer:n}){const r=D.useRef(null),[l,d]=D.useState(!1),[i,c]=D.useState(s.isDevEnv),[o,u]=D.useState(!1),[x,h]=D.useState(!1),[p,k]=D.useState(!1),m=t??p,f=s.useCurrentAIContext(),{setCurrentAIContext:j}=s.useAIActions(),{clearQueue:C}=s.useQueueActions(),{clearFileAttachments:I}=s.useFileActions(),O=s.useFileAttachments("editor"),R=s.useDashboardStore(Q=>Q.dashboard.aiContext),v=s.useEditorStore(Q=>Q.card.dataSource),w=s.useEditorStore(Q=>Q.actions.setCardSql),g=s.useEditorStore(Q=>Q.actions.setRunSql),y=s.useEditorStore(Q=>Q.showAIDialog),T=s.useDashboardStore(Q=>Q.handleOpenAssistantProfile),{setShowAIDialog:M,setCardPython:N}=s.useEditorActions(),{setDataSource:b}=s.useEditorActions(),{assistantProfile:A}=s.useAssistantProfile(),{messages:F,setMessages:E,sendMessage:L,isLoading:S,stop:V,status:K,llmUsage:H,errorMessage:G,clearError:q}=Vn(),[P,z]=D.useState(""),J=Q=>{z(Q.target.value)},B=Q=>{Q.preventDefault();const ae=P.trim();if(!ae&&O.length===0)return;const re=[];ae&&re.push({type:"text",text:ae}),O.forEach(Ne=>{Ne.data&&re.push({type:"file",mediaType:Ne.type,filename:Ne.name,url:`data:${Ne.type};base64,${Ne.data}`})}),L({role:"user",parts:re}),z(""),I("editor"),se({force:!0})},{visibleMessages:W,hasMoreMessages:X,totalMessageCount:ee,loadMoreMessages:_,resetMessageWindow:ne}=s.useMessageWindow(F,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Y,isAtBottom:le,hasNewMessages:ce,newMessageCount:$,scrollToBottom:se,handleScroll:de,resetNewMessageCount:ue}=s.useAutoScroll(W,{threshold:50,behavior:"smooth",isStreaming:S});D.useEffect(()=>{var Q;y&&((Q=r.current)==null||Q.focus(),j({selectedEntities:(v==null?void 0:v.selectedEntities)||[]}))},[y,v,j]),s.useAutoSubmitQueue({assistantType:"editor",status:K,isLoading:S,sendMessage:L});const{hasActiveTools:we}=s.useActiveToolStatus(F),me=D.useCallback(Q=>{a==null||a(Q),t===void 0&&k(Q)},[t,a]);D.useEffect(()=>{if(!m)return;function Q(ae){ae.key==="Escape"&&me(!1)}return window.addEventListener("keydown",Q),()=>{window.removeEventListener("keydown",Q)}},[m,me]);const je=D.useCallback(Q=>{L({role:"user",parts:[{type:"text",text:Q}]}),se({force:!0})},[L,se]),xe=D.useCallback(async()=>{const Q=JSON.stringify(F??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Q),s.ue.success("Conversation copied")}catch(ae){console.error("Failed to copy conversation",ae),s.ue.error("Unable to copy conversation")}},[F]),be=D.useCallback(()=>{me(!m)},[m,me]);function ke(Q,ae){ae==="sql"?(w(Q),g(!0)):ae==="python"&&(N(Q),g(!0))}function fe(){f.selectedEntities.length===0&&j({selectedEntities:(R==null?void 0:R.selectedEntities)||[]})}function Te(Q){fe();const ae={role:"user",parts:[{type:"text",text:Q.title+" "+Q.subtitle}]};L(ae)}function Ee(Q){fe(),L({role:"user",parts:[{type:"text",text:Q}]})}function Ae(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:d,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:c,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:u,children:"System Message"})]})]})}function Ie(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const ve=(P==null?void 0:P.length)===0&&(F==null?void 0:F.filter(Q=>Q.role==="user").length)===0,ye=e.jsxs("div",{"data-role":"editor-assistant",className:s.cn("flex h-full w-full flex-col justify-between px-6 py-4",m&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Ie(),T&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:T,children:(A==null?void 0:A.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Ae(),i&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:xe,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:m?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:be,children:m?e.jsx(s.Minimize2,{className:"size-4"}):e.jsx(s.Maximize2,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{E([]),C("editor"),q(),ne()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{M(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:Y,className:"mt-2 flex w-full grow basis-0",onScroll:de,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[X&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:_,className:"text-xs",children:["Load ",Math.min(5,ee-W.length)," ","more messages (",ee-W.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:W,showTools:i,handleRun:ke,showSystemMessage:o,onQuickReply:je,disableQuickReplies:S}),!we&&e.jsx(s.AssistantStatus,{status:K,errorMessage:G})]})}),y&&!le&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{se({force:!0}),ue()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),ce&&$>0&&e.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:$>9?"9+":$})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[ve&&!A&&e.jsx(s.Placeholders,{onClick:Te,placeholders:Pn}),e.jsx("div",{children:ve&&A&&e.jsx(s.SeedQuestions,{seedQuestions:A.seedQuestions||[],handleSeedQuestionClick:Ee})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:z,stop:V,input:P,handleInputChange:J,handleSubmit:Q=>{fe(),B(Q),se({force:!0})},isLoading:S,status:K,assistantType:"editor",onFocus:()=>{}})]}),H&&l&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",H.inputTokens," prompt tokens, ",H.outputTokens," ","completion tokens, ",H.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(v==null?void 0:v.selectedEntities)||[],open:x,onOpenChange:h,dataSource:v||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return m&&n?nt.createPortal(e.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:e.jsx("div",{className:"flex h-full w-full",children:ye})}),n):ye}function zn({selectedChart:t,onChartChange:a}){const[n,r]=D.useState(!1),l=s.useEditorStore(c=>c.card),d=()=>{var o;if(t==="custom")return((o=l==null?void 0:l.customCardPreferences)==null?void 0:o.componentName)||"Custom Visual";const c=s.chartTypes.find(u=>u.id===t);return(c==null?void 0:c.label)||"Select chart type"},i=()=>{var o;if(t==="custom"){const u=(o=l==null?void 0:l.customCardPreferences)==null?void 0:o.componentName;if(u){const x=s.getAutoDetectedChartIcon(u);return x||e.jsx(s.ChartIcon,{chartName:u,isCustom:!0,className:"h-4 w-4"})}return e.jsx(s.Shapes,{className:"h-4 w-4"})}const c=s.chartTypes.find(u=>u.id===t);if(c){const u=c.icon;return e.jsx(u,{className:"h-4 w-4"})}return e.jsx(s.Shapes,{className:"h-4 w-4"})};return e.jsx("div",{children:e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[i(),e.jsx("span",{children:d()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[360px] p-3",align:"start",onOpenAutoFocus:c=>c.preventDefault(),children:e.jsx(Ds,{onChartSelect:c=>a(c),onClose:()=>r(!1)})})]})})}let $n=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce((a,n)=>(n&=63,n<36?a+=n.toString(36):n<62?a+=(n-26).toString(36).toUpperCase():n>62?a+="-":a+="_",a),"");const Be=[{id:"sum",label:"Sum",symbol:"+",description:"Add two metrics together",template:()=>"({field_0} + {field_1})",requiresTwoInputs:!0},{id:"difference",label:"Difference",symbol:"−",description:"Subtract one metric from another",template:()=>"({field_0} - {field_1})",requiresTwoInputs:!0},{id:"product",label:"Product (Multiplication)",symbol:"×",description:"Multiply two metrics",template:()=>"({field_0} * {field_1})",requiresTwoInputs:!0},{id:"ratio",label:"Ratio",symbol:"÷",description:"Divide one metric by another",template:()=>"({field_0} / NULLIF({field_1}, 0))",requiresTwoInputs:!0},{id:"change",label:"Change",symbol:"Δ",description:"Calculate percentage change from A to B",template:()=>"(({field_1} - {field_0}) / NULLIF({field_0}, 0))",requiresTwoInputs:!0},{id:"percentage",label:"Percentage",symbol:"%",description:"Calculate (A / B) × 100",template:()=>"(({field_0} / NULLIF({field_1}, 0)) * 100)",requiresTwoInputs:!0},{id:"scale",label:"Scale (Multiply by Factor)",symbol:"×n",description:"Multiply a metric by a constant factor",template:()=>"({field_0} * {constant})",requiresTwoInputs:!1},{id:"custom",label:"Custom Expression",symbol:"{}",description:"Drag fields to create custom expression with tokens",requiresTwoInputs:!1,allowsCustomExpression:!0}];function Kn(t,a,n,r,l,d,i,c,o){const u=Be.find(f=>f.id===a);if(!u)throw new Error(`Unknown operation: ${a}`);let x,h=[],p;if(a==="custom"){if(!(c!=null&&c.trim()))throw new Error("Custom expression is required");x=c.trim()}else if(a==="scale"){if(!n)throw new Error("Metric A is required for scale operation");if(o===void 0||o===0)throw new Error("Constant factor is required for scale operation");x=u.template().replace("{constant}",String(o)),h=[n],p=o}else{if(!n||!r)throw new Error("Metrics A and B are required for standard operations");x=u.template(),h=[n,r]}const k={operation:a,inputFields:h,...p!==void 0&&{constant:p}};return{id:i||`calc_${$n(10)}`,name:t.toLowerCase().replace(/\s+/g,"_"),label:t,alias:t.toLowerCase().replace(/\s+/g,"_"),qualifiedFieldName:t.toLowerCase().replace(/\s+/g,"_"),dataType:"number",role:"metric",aggregate:"SUM",expression:x,calculatedFormula:k,entityId:d,entityName:s.CALCULATED_FIELD_ENTITY_MARKER,entityType:"table",description:`Calculated field: ${t}`}}function fs(t){var r,l;const a=Be.find(d=>d.id===t.operation);if(!a)return"Unknown operation";if(t.operation==="custom")return"Custom expression";if(t.operation==="scale"){const d=((r=t.inputFields[0])==null?void 0:r.label)||((l=t.inputFields[0])==null?void 0:l.name)||"A",i=t.constant??1;return`${d} × ${i}`}return t.inputFields.map(d=>d.label||d.name).join(` ${a.symbol} `)}const Qe=({dataType:t})=>s.getFieldIconComponent(t);function Gn({aliasTemplate:t,onAliasTemplateChange:a}){var o;const[n,r]=D.useState(t),[l,d]=D.useState(!1),i=(o=s.useEditorStore(u=>{var x;return(x=u.card.config)==null?void 0:x.pivotByColumns}))==null?void 0:o[0],c=i?`e.g. Min Sales in {{${i.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input,{placeholder:c,value:l?n:t,onChange:u=>{r(u.target.value),d(!0)},onFocus:()=>d(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&l&&n!==t?(a(n),d(!1)):u.key==="Escape"&&(r(t),d(!1))},"aria-label":"Edit alias template"}),l&&n!==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:()=>{a(n),d(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),d(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function qn({valueAliases:t,onValueAliasesChange:a}){const[n,r]=D.useState(null),[l,d]=D.useState(""),[i,c]=D.useState(""),o=()=>{a({...t,"":""})},u=h=>{const p={...t};delete p[h],a(p)},x=h=>{const p={...t};delete p[h],p[l]=i,a(p),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,p],k)=>e.jsx("div",{className:"flex items-center gap-2",children:n===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input,{placeholder:"Value key",value:l,onChange:m=>d(m.target.value),className:"h-8 w-24 text-xs",onPointerDown:m=>m.stopPropagation(),onKeyDown:m=>{m.key==="Enter"?x(h):m.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input,{placeholder:"Alias label",value:i,onChange:m=>c(m.target.value),className:"h-8 w-24 text-xs",onPointerDown:m=>m.stopPropagation(),onKeyDown:m=>{m.key==="Enter"?x(h):m.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>x(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),d(h),c(p)},"aria-label":"Edit value alias key"}),e.jsx(s.Input,{placeholder:"Alias label",value:p,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),d(h),c(p)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+k)),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 Un({column:t}){const a=s.useEditorStore(o=>o.card.type),n=s.useEditorStore(o=>{var u,x;return(x=(u=o.card)==null?void 0:u.config)==null?void 0:x.metricColumns}),r=(n==null?void 0:n.map(o=>o.label))||[],l=r==null?void 0:r.find(o=>o===t.label||o===t.name),d=l?r.indexOf(l):-1;function i(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(Bs,{idx:d,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function c(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Vs,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&i(),["pie","doughnut"].includes(a)&&c()]})}function Hn({field:t,searchQuery:a="",limit:n=500}){const{authToken:r,tokenProps:l}=s.useSemaphorContext(),d=s.useEditorStore(u=>u.card),i=d==null?void 0:d.dataSource,c=["attribute-values",t.entityName,t.name,a,n],o=s.useQuery({queryKey:c,queryFn:async()=>{if(!(i!=null&&i.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:a?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:a}],groups:[]}:void 0,rowLimit:n},x={connection_id:i.connectionId,cardConfig:u,cardDataSource:i,cache_config:s.getCacheConfig({card:d})};console.log("requestBody",x);const h=await s.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",x);if(h!=null&&h.error)return console.error("Error fetching attribute values:",h.error),[];const p=t.name;return((h==null?void 0:h.records)||[]).map(m=>{const f=m[p]||m[t.alias||p]||m[t.label];return{id:f||"",value:f||"",label:String(f||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(i!=null&&i.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:o.data||[],isLoading:o.isLoading,isFetching:o.isFetching,isError:o.isError,error:o.error,refetch:o.refetch}}function _s({open:t,onOpenChange:a,availableFields:n,existingFilters:r,editingCondition:l,onSave:d}){var O,R;const i=!!l,[c,o]=D.useState(i?"values":"fields"),[u,x]=D.useState(""),[h,p]=D.useState({id:(l==null?void 0:l.id)||s.v4(),field:(l==null?void 0:l.field)||null,selectedValues:l?Array.isArray(l.value)?l.value:[l.value]:[]}),k=n.filter(v=>{var g;return i?!1:!((g=r==null?void 0:r.conditions)==null?void 0:g.some(y=>y.field.id===v.id))&&v.label.toLowerCase().includes(u.toLowerCase())}),m=v=>{p({...h,field:v}),o("values")},f=()=>{if(h.field&&h.selectedValues.length>0){const v={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let w;if(i){const g=((r==null?void 0:r.conditions)||[]).map(y=>y.id===l.id?v:y);w={...r,conditions:g}}else{const g=(r==null?void 0:r.conditions)||[];w={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...g,v],groups:[]}}d(w),a(!1)}},j=()=>{if(!i||!l)return;const v=((r==null?void 0:r.conditions)||[]).filter(w=>w.id!==l.id);if(v.length>0){const w={...r,conditions:v};d(w)}else d(void 0);a(!1)},C=v=>{p({...h,selectedValues:v})},I=()=>{i&&l?(p({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),o("values")):(p({id:s.v4(),field:null,selectedValues:[]}),o("fields")),x("")};return D.useEffect(()=>{t&&I()},[t,i,l]),e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:i?`Edit Filter: ${(O=h.field)==null?void 0:O.label}`:c==="fields"?"Select Field to Filter":`Select Values for ${(R=h.field)==null?void 0:R.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!i&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&c==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(v=>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:[v.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(v.value)?`${v.value.length} values`:String(v.value)})]},v.id))})]}),c==="fields"&&!i?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search fields...",value:u,onChange:v=>x(v.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:k.map(v=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>m(v),children:[e.jsx(Qe,{dataType:s.getDataType(v.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:v.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[v.entityName,".",v.name]})]})]},v.id))}),k.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),k.length===0&&!u&&n.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(Jn,{field:h.field,selectedValues:h.selectedValues,onValuesChange:C,onBack:i?void 0:()=>o("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:i?e.jsx(s.Button,{variant:"destructive",onClick:j,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:I,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:f,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Jn({field:t,selectedValues:a,onValuesChange:n,onBack:r}){const[l,d]=D.useState(""),{values:i,isLoading:c,isFetching:o}=Hn({field:t,searchQuery:l,limit:500}),u=l?i.filter(p=>String(p.value).toLowerCase().includes(l.toLowerCase())):i,x=p=>{const k=a.includes(p);n(k?a.filter(m=>m!==p):[...a,p])},h=()=>{a.length===u.length&&u.length>0?n([]):n(u.map(p=>p.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search values...",value:l,onChange:p=>d(p.target.value),className:"pl-10"})]}),c||o?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(s.Checkbox,{checked:a.length===u.length&&u.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",u.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:u.map(p=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>x(p.value),children:[e.jsx(s.Checkbox,{checked:a.includes(p.value),onCheckedChange:()=>x(p.value)}),e.jsx(Je,{className:"text-sm",children:p.label})]},p.id))})]})]})}function Qs({open:t,onOpenChange:a,availableMetrics:n,existingField:r,onSave:l,cardId:d}){const[i,c]=D.useState(""),[o,u]=D.useState("ratio"),[x,h]=D.useState(null),[p,k]=D.useState(null),[m,f]=D.useState(1),[j,C]=D.useState(""),[I,O]=D.useState({format:"number",decimalPlaces:2}),[R,v]=D.useState({}),w=Be.find(b=>b.id===o),g=n.find(b=>b.id===x),y=n.find(b=>b.id===p);D.useEffect(()=>{if(r&&t)if(c(r.label),r.calculatedFormula)if(u(r.calculatedFormula.operation),r.calculatedFormula.operation==="custom")C(r.expression||"");else if(r.calculatedFormula.operation==="scale"){const b=r.calculatedFormula.inputFields;if(b.length>=1){const A=n.find(F=>F.qualifiedFieldName===b[0].qualifiedFieldName);h((A==null?void 0:A.id)||null)}r.calculatedFormula.constant!==void 0&&f(r.calculatedFormula.constant)}else{const b=r.calculatedFormula.inputFields;if(b.length>=2){const A=n.find(E=>E.qualifiedFieldName===b[0].qualifiedFieldName),F=n.find(E=>E.qualifiedFieldName===b[1].qualifiedFieldName);h((A==null?void 0:A.id)||null),k((F==null?void 0:F.id)||null)}}else u("custom"),C(r.expression||"")},[r,t,n]);const T=()=>{const b={};return i.trim()||(b.name="Name is required"),o==="custom"?j.trim()||(b.customExpression="Custom expression is required"):o==="scale"?(x||(b.inputA="Please select a metric for input A"),(isNaN(m)||m===0)&&(b.constantFactor="Please enter a valid non-zero number"),r&&x===r.id&&(b.circular="Cannot reference the field being edited")):(x||(b.inputA="Please select a metric for input A"),p||(b.inputB="Please select a metric for input B"),x===p&&(b.inputs="Inputs A and B must be different metrics"),r&&(x===r.id||p===r.id)&&(b.circular="Cannot reference the field being edited")),v(b),Object.keys(b).length===0},M=()=>{if(!T())return;const b=Kn(i,o,g||null,y||null,I,d,r==null?void 0:r.id,o==="custom"?j:void 0,o==="scale"?m:void 0);l(b),N()},N=()=>{c(""),u("ratio"),h(null),k(null),f(1),C(""),v({}),a(!1)};return e.jsxs(s.Dialog,{modal:!1,open:t,onOpenChange:a,children:[t&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-w-md max-h-[90vh] overflow-y-auto",onInteractOutside:b=>{b.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsxs(s.DialogTitle,{children:[r?"Edit":"Create"," Calculated Metric"]}),e.jsx(s.DialogDescription,{children:"Combine existing metrics to create a new calculated field"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"name",children:"Name"}),e.jsx(s.Input$1,{id:"name",value:i,onChange:b=>c(b.target.value),placeholder:"e.g., Profit Margin",className:R.name?"border-red-500":""}),R.name&&e.jsx("p",{className:"text-xs text-red-500",children:R.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"operation",children:"Outcome is"}),e.jsxs(s.Select,{value:o,onValueChange:b=>{u(b),b==="custom"?(h(null),k(null)):o==="custom"&&C("")},children:[e.jsx(s.SelectTrigger,{id:"operation",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"CALCULATED"}),Be.map(b=>e.jsx(s.SelectItem,{value:b.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm",children:b.symbol}),e.jsx("span",{children:b.label})]})},b.id))]})})]}),w&&e.jsx("p",{className:"text-xs text-muted-foreground",children:w.description})]}),o==="custom"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"customExpression",children:"SQL Expression"}),e.jsx(s.Textarea,{id:"customExpression",value:j,onChange:b=>C(b.target.value),placeholder:"e.g., CASE WHEN revenue > 1000 THEN revenue - cost ELSE 0 END",className:s.cn("font-mono text-sm",R.customExpression&&"border-red-500"),rows:4}),R.customExpression&&e.jsx("p",{className:"text-xs text-red-500",children:R.customExpression}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Write a SQL expression using column names from your data source"})]}):e.jsxs("div",{className:"rounded-md bg-muted p-3 font-mono text-sm",children:["= ",x&&g?g.label:"A"," ",w==null?void 0:w.symbol," ",p&&y?y.label:"B"]}),o!=="custom"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"inputA",children:"Where"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded bg-muted font-mono text-sm font-medium",children:"A"}),e.jsxs(s.Select,{value:x||"",onValueChange:h,children:[e.jsx(s.SelectTrigger,{id:"inputA",className:R.inputA?"border-red-500":"",children:e.jsx(s.SelectValue,{placeholder:"+ Choose metric"})}),e.jsx(s.SelectContent,{children:n.filter(b=>!s.isCalculatedMetric(b)||b.id!==(r==null?void 0:r.id)).map(b=>e.jsxs(s.SelectItem,{value:b.id,children:[b.label||b.name,b.aggregate&&` (${b.aggregate})`]},b.id))})]})]}),R.inputA&&e.jsx("p",{className:"text-xs text-red-500",children:R.inputA})]}),o!=="custom"&&o!=="scale"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded bg-muted font-mono text-sm font-medium",children:"B"}),e.jsxs(s.Select,{value:p||"",onValueChange:k,children:[e.jsx(s.SelectTrigger,{id:"inputB",className:R.inputB?"border-red-500":"",children:e.jsx(s.SelectValue,{placeholder:"+ Choose metric"})}),e.jsx(s.SelectContent,{children:n.filter(b=>!s.isCalculatedMetric(b)||b.id!==(r==null?void 0:r.id)).map(b=>e.jsxs(s.SelectItem,{value:b.id,children:[b.label||b.name,b.aggregate&&` (${b.aggregate})`]},b.id))})]})]}),R.inputB&&e.jsx("p",{className:"text-xs text-red-500",children:R.inputB})]}),o==="scale"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"constantFactor",children:"Multiplication Factor"}),e.jsx(s.Input$1,{id:"constantFactor",type:"number",step:"any",value:m,onChange:b=>f(parseFloat(b.target.value)||0),placeholder:"e.g., 0.15",className:R.constantFactor?"border-red-500":""}),R.constantFactor&&e.jsx("p",{className:"text-xs text-red-500",children:R.constantFactor}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Enter the constant value to multiply the metric by (e.g., 0.15 for 15%)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"format",children:"Format"}),e.jsxs(s.Select,{value:I.format,onValueChange:b=>O({...I,format:b}),children:[e.jsx(s.SelectTrigger,{id:"format",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsxs(s.SelectItem,{value:"number",children:["Decimal (",I.decimalPlaces,")"]}),e.jsx(s.SelectItem,{value:"currency",children:"Currency"}),e.jsx(s.SelectItem,{value:"percent",children:"Percentage"})]})]})]}),(R.inputs||R.circular)&&e.jsxs(s.Alert,{variant:"destructive",children:[e.jsx(s.CircleAlert,{className:"h-4 w-4"}),e.jsx(s.AlertDescription,{children:R.inputs||R.circular})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:N,children:"Cancel"}),e.jsxs(s.Button,{onClick:M,children:[r?"Update":"Create"," Metric"]})]})]})]})}function _n({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:d=!1,cardType:i}){var We,Xe,Ze,es,ss;const{attributes:c,listeners:o,setNodeRef:u,transform:x,transition:h,isDragging:p}=s.useSortable({id:t.id}),k=s.useEditorStore(U=>U.card),{updateLabel:m,handleAggregationChange:f,handleDateFormatChange:j,handleGranularityChange:C,handleAliasTemplateChange:I,handleValueAliasesChange:O,removeField:R,handleKpiComparisonTypeChange:v,handleKpiShowTrendlineChange:w,handleKpiTrendlineWindowChange:g,handleKpiTrendlineGranularityChange:y,handleKpiTargetValueChange:T}=s.useFieldManagement(k),[M,N]=D.useState(!1),[b,A]=D.useState(!1),[F,E]=D.useState(!1),[L,S]=D.useState(null),[V,K]=D.useState(t.dateFormat||"YYYY-MM-DD"),[H,G]=D.useState(t.customFormat||""),[q,P]=D.useState(!!t.customFormat),[z,J]=D.useState(t.granularity||"day"),[B,W]=D.useState(t.aliasTemplate||""),[X,ee]=D.useState(t.valueAliases||{}),[_,ne]=D.useState((We=t.parameters)==null?void 0:We.filters),Y=U=>{U==="custom"?P(!0):(P(!1),K(U),a==="groupBy"&&j(n,U,""))},le=U=>{G(U),a==="groupBy"&&j(n,"custom",U)},ce=U=>{var oe;J(U);const Z=(oe=s.getDateFormatOptionsForGranularity(U)[0])==null?void 0:oe.value;Z&&!q&&(K(Z),a==="groupBy"&&j(n,Z,"")),a==="groupBy"&&C(n,U)},$=U=>{W(U),a==="metrics"&&I(n,U)},se=U=>{ee(U),a==="metrics"&&O(n,U)},de=U=>{m(a,n,U)},ue=U=>{var te;if(ne(U),a==="metrics"){const Z={...t,parameters:{...t.parameters,filters:U}},oe=[...((te=k.config)==null?void 0:te.metricColumns)||[]];oe[n]=Z,s.useEditorStore.getState().actions.updateCardConfig(k.id,{metricColumns:oe})}A(!1)},we=()=>{R(a,n)},me={transform:s.CSS.Transform.toString(x),transition:h},je=s.getDataType(t.dataType),xe=je==="date",be=i==="kpi",ke=s.getDateFormatOptionsForGranularity(z),fe=a!=="pivotBy",Te=xe&&a==="groupBy"&&(!be||((Xe=k.config)==null?void 0:Xe.comparisonType)==="start_vs_end"),Ee=!be&&xe&&a==="groupBy",Ae=i&&s.COMPARISON_SUPPORTED_CHART_TYPES.includes(i)&&xe&&a==="groupBy",Ie=i==="kpi"&&xe&&a==="groupBy",ve=i&&i!=="pivotTable"&&a==="metrics"&&((Ze=k.config)==null?void 0:Ze.comparisonType)==="target",ye=a==="metrics",Q=()=>{const U=t,te=a==="metrics"&&s.isCalculatedMetric(U);return e.jsxs("div",{className:"space-y-1",children:[!te&&e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:Z=>{Z.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),te&&U.calculatedFormula&&e.jsxs("div",{title:fs(U.calculatedFormula),onPointerDown:Z=>{Z.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:["= ",fs(U.calculatedFormula)]})]})},ae=()=>fe?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(pe,{value:t.label??"",onSave:de,placeholder:"Display label...",type:"text"})]}):null,re=()=>Te?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:z,onValueChange:ce,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(U=>e.jsx(s.SelectItem,{className:"text-xs",value:U,children:s.toTitleCase(U)},U))})]})]}):null,Ne=()=>Ee?e.jsxs(e.Fragment,{children:[re(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(s.Select,{value:q?"custom":V,onValueChange:Y,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:ke.map(U=>e.jsx(s.SelectItem,{className:"text-xs",value:U.value,children:U.label},U.value))})]}),q&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:H,onChange:U=>{U.stopPropagation(),le(U.target.value)},onClick:U=>U.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,Ws=()=>{var Z,oe,Ce,Me,ge;const U=Ae,te=Ie;return!U&&!te?null:e.jsxs(e.Fragment,{children:[U&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((Z=k.config)==null?void 0:Z.comparisonType)||"none",onValueChange:v,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"start_vs_end",children:"Start vs End"})]})]})]}),te&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((oe=k.config)==null?void 0:oe.showTrendline)||!1,onCheckedChange:w})]})}),((Ce=k.config)==null?void 0:Ce.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input,{type:"number",min:"1",max:"365",value:((Me=k.config)==null?void 0:Me.trendlineWindow)||30,onChange:Fe=>{const tt=parseInt(Fe.target.value)||30;g(tt)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(s.Select,{value:((ge=k.config)==null?void 0:ge.trendlineGranularity)||"day",onValueChange:y,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]})]})},Xs=()=>{var U,te;return ve?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(pe,{value:((U=k.config)==null?void 0:U.targetValue)!==void 0&&((te=k.config)==null?void 0:te.targetValue)!==null?String(k.config.targetValue):"",onSave:Z=>{!isNaN(Number(Z))&&Z!==null?T(Number(Z)):T(0)},placeholder:"Enter target value...",type:"text"})]}):null},Zs=()=>{if(!ye)return null;const U=t,te=s.isCalculatedMetric(U);return e.jsxs(e.Fragment,{children:[te&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Formula"}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>E(!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:Z=>{f(n,Z)},disabled:te,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(_==null?void 0:_.conditions)&&_.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:_.conditions.map(Z=>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:()=>{S(Z),A(!0)},children:[e.jsxs("span",{className:"font-medium",children:[Z.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(Z.value)?Z.value.length===1?String(Z.value[0]):Z.value.length<=2?Z.value.join(", "):`${Z.value.slice(0,2).join(", ")} +${Z.value.length-2}`:String(Z.value)})}),Array.isArray(Z.value)&&Z.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 (",Z.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:Z.value.map((oe,Ce)=>e.jsx("div",{children:String(oe)},Ce))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:oe=>{var Me;oe.stopPropagation();const Ce=_.conditions.filter(ge=>ge.id!==Z.id);if(Ce.length>0){const ge={..._,conditions:Ce};ue(ge)}else if(ne(void 0),a==="metrics"){const ge={...t,parameters:{...t.parameters,filters:void 0}},Fe=[...((Me=k.config)==null?void 0:Me.metricColumns)||[]];Fe[n]=ge,s.useEditorStore.getState().actions.updateCardConfig(k.id,{metricColumns:Fe})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},Z.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{S(null),A(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Un,{column:t}),d&&e.jsxs(e.Fragment,{children:[e.jsx(Gn,{aliasTemplate:B,onAliasTemplateChange:$}),e.jsx(qn,{valueAliases:X,onValueAliasesChange:se})]})]})},{columns:et=[]}=s.useColumns(),st=(_==null?void 0:_.conditions)&&_.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:me,...c,...o,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${p?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(Qe,{dataType:je}),e.jsx(Je,{className:s.cn("w-[140px] flex-1 text-sm",st&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),a==="metrics"&&((es=_==null?void 0:_.conditions)==null?void 0:es.length)&&!M&&e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:_.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:_.conditions.map(U=>e.jsxs("div",{children:[U.field.label,":"," ",Array.isArray(U.value)?`${U.value.length} values`:String(U.value)]},U.id))})})]})}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:U=>{U.stopPropagation(),N(!M)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${M?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:U=>{U.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const te=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",te),l(te)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:U=>{U.stopPropagation(),we()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),M&&e.jsxs("div",{className:"space-y-3",children:[Q(),ae(),i==="kpi"&&re(),Ne(),Ws(),Xs(),Zs()]})]}),b&&e.jsx(_s,{open:b,onOpenChange:U=>{A(U),U||S(null)},availableFields:et,existingFilters:_,editingCondition:L,onSave:U=>{var te;if(U)ue(U);else if(ne(void 0),a==="metrics"){const Z={...t,parameters:{...t.parameters,filters:void 0}},oe=[...((te=k.config)==null?void 0:te.metricColumns)||[]];oe[n]=Z,s.useEditorStore.getState().actions.updateCardConfig(k.id,{metricColumns:oe})}S(null)}}),F&&a==="metrics"&&e.jsx(Qs,{open:F,onOpenChange:E,availableMetrics:((ss=k.config)==null?void 0:ss.metricColumns)||[],existingField:t,onSave:U=>{var Z;const te=[...((Z=k.config)==null?void 0:Z.metricColumns)||[]];te[n]=U,s.useEditorStore.getState().actions.updateCardConfig(k.id,{metricColumns:te})},cardId:k.id})]})}function Qn({concept:t}){const a=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Pivot Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metric Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function Re({zone:t,fields:a,label:n,placeholder:r,shouldShow:l,hasPivotColumns:d=!1,activeField:i=null}){const{isOver:c,setNodeRef:o}=s.useDroppable({id:t}),{updateSortByColumn:u}=s.useEditorActions(),x=s.useEditorStore(j=>j.card),h=s.useEditorStore(j=>j.card.type),p=a.length>0,k=D.useMemo(()=>!i||!c?!0:s.validateFieldForChartType(i,t,h).isValid,[i,c,t,h]),m=(j,C)=>{var O;!((O=x.config)!=null&&O.sortByColumns)||x.config.sortByColumns.findIndex(R=>R.id===j)===-1||u(x.id,j,{direction:C})};if(t==="sortBy"&&l===!1)return null;const f=t!=="sortBy"&&h!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:n}),f&&e.jsx(Qn,{concept:t})]}),e.jsx("div",{ref:o,className:s.cn("rounded-lg border-2 border-dotted p-0.5 transition-all",{"border-green-500 bg-green-50 dark:bg-green-950":c&&k,"border-red-500 bg-red-50 dark:bg-red-950":c&&!k,"border-muted-foreground/30 bg-muted/40":!c&&p,"min-h-[60px] border-muted-foreground/20 bg-background":!c&&!p}),children:a.length===0?e.jsx("div",{className:"flex min-h-[60px] items-center justify-center text-sm text-muted-foreground/60",children:r}):e.jsx(s.SortableContext,{items:a.map(j=>j.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:a.map((j,C)=>{const O=j.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(_n,{field:j,zone:t,index:C,sortDirection:O,onSortDirectionChange:R=>m(j.id,R),hasPivotColumns:d,cardType:h})})},j.id)})})})})]})}const gs={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%
195
- 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 Yn(){var p,k,m,f,j,C,I,O,R,v,w;const t=s.useEditorStore(g=>g.card),{setCardPreferences:a}=s.useEditorActions(),n=((p=t.config)==null?void 0:p.metricColumns)||[],r=((k=t.config)==null?void 0:k.groupByColumns)||[],l=n.length===2&&r.length===0,d=n.length>=1&&r.length>0;if(!(t.type==="kpi"&&(l||d)))return null;const c=((f=(m=t.preferences)==null?void 0:m.kpiVisualOptions)==null?void 0:f.metricComparison)||{},o=g=>{var T;const y={...t.preferences,kpiVisualOptions:{...(T=t.preferences)==null?void 0:T.kpiVisualOptions,metricComparison:{...c,...g}}};a(y)},u=d||c.enabled,x=((j=t.config)==null?void 0:j.comparisonType)||"none",h=x==="previous_period"||x==="same_period_last_year"||x==="start_vs_end";return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xt,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[l&&n.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:c.enabled||!1,onCheckedChange:g=>o({enabled:g,...g&&!c.calculationType?{calculationType:"difference"}:{}})})]}),u&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const g=c.calculationType||"difference",y=gs[g];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:y==null?void 0:y.label}),e.jsx("p",{children:y==null?void 0:y.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:y==null?void 0:y.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",y==null?void 0:y.example]})]})})()})]})]}),e.jsxs(s.Select,{value:c.calculationType||"difference",onValueChange:g=>o({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(gs).map(([g,y])=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:y.label},g))})]})]}),e.jsx(_e,{formatOptions:c.formatOptions||{},onFormatOptionsChange:g=>o({formatOptions:g}),showTitle:!0,title:"COMPARISON FORMAT"}),(h||l)&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),l&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:c.position||"right",onValueChange:g=>o({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:c.showArrow!==!1,onCheckedChange:g=>o({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:c.showColor!==!1,onCheckedChange:g=>o({showColor:g})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),c.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Le,{value:((C=c.colorConfig)==null?void 0:C.increase)||"green",onChange:g=>o({colorConfig:{...c.colorConfig,increase:g}}),label:"Primary > Secondary"}),e.jsx(Le,{value:((I=c.colorConfig)==null?void 0:I.decrease)||"red",onChange:g=>o({colorConfig:{...c.colorConfig,decrease:g}}),label:"Primary < Secondary"}),e.jsx(Le,{value:((O=c.colorConfig)==null?void 0:O.noChange)||"neutral",onChange:g=>o({colorConfig:{...c.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:c.conditionalLabel||!1,onCheckedChange:g=>o({conditionalLabel:g})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),c.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input$1,{id:"label-increase",type:"text",value:((R=c.conditionalLabels)==null?void 0:R.increase)??"Increase",onChange:g=>o({conditionalLabels:{...c.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$1,{id:"label-decrease",type:"text",value:((v=c.conditionalLabels)==null?void 0:v.decrease)??"Decrease",onChange:g=>o({conditionalLabels:{...c.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$1,{id:"label-no-change",type:"text",value:((w=c.conditionalLabels)==null?void 0:w.noChange)??"No change",onChange:g=>o({conditionalLabels:{...c.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$1,{id:"label-name",type:"text",value:c.labelName??"",onChange:g=>o({labelName:g.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function Wn(){var l,d;const t=s.useEditorStore(i=>i.card),{setCardPreferences:a}=s.useEditorActions();if(t.type!=="kpi")return null;const n=((d=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:d.formatOptions)||{},r=i=>{var o;const c={...t.preferences,kpiVisualOptions:{...(o=t.preferences)==null?void 0:o.kpiVisualOptions,formatOptions:i}};a(c)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Hash,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(_e,{formatOptions:n,onFormatOptionsChange:r,showTitle:!1})})]})}function Xn(){var d;const t=s.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.type}),a=s.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.preferences}),{setCardPreferences:n}=s.useEditorActions();if(t!=="treemap")return null;const r=((d=a==null?void 0:a.chartOptions)==null?void 0:d.treemapColorMode)??"branch",l=i=>{const c={...a||{},chartOptions:{...a==null?void 0:a.chartOptions,treemapColorMode:i}};n(c)};return e.jsxs(s.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(s.RadioGroup,{value:r,onValueChange:i=>l(i??"branch"),className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:"treemap-color-branch",value:"branch"}),e.jsxs(s.Label,{htmlFor:"treemap-color-branch",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Shade by value (default)"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Keeps parent hue and adjusts lightness based on the node's share within the branch."})]})]}),e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:"treemap-color-category",value:"category"}),e.jsxs(s.Label,{htmlFor:"treemap-color-category",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Single color per category"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Applies the top-level color to all descendants without lightening/darkening."})]})]})]})})]})}function Zn({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r,activeField:l}){const[d,i]=D.useState(!1),c=s.useEditorStore(O=>{var R;return((R=O.card.customCardPreferences)==null?void 0:R.url)&&O.card.type==="custom"}),o=s.useEditorStore(O=>O.card),u=s.useEditorStore(O=>O.actions.updateCardConfig),x=o==null?void 0:o.type,h=t.length>0||n.length>0,p=x!=="kpi"||n.length<=2,k=x!=="kpi",m=x!=="kpi"&&h,f=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(x),j=k&&!f,C=()=>x==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},I=()=>x==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Columns",placeholder:"Drop fields to measure"};return e.jsxs(e.Fragment,{children:[e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.List,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[p&&e.jsx(Re,{zone:"groupBy",fields:t,label:C().label,placeholder:C().placeholder,activeField:l}),j&&e.jsx(Re,{zone:"pivotBy",fields:a,label:"Pivot Columns",placeholder:"Drop fields to pivot data",activeField:l}),e.jsx(Re,{zone:"metrics",fields:n,label:I().label,placeholder:I().placeholder,hasPivotColumns:a.length>0,activeField:l}),n.length>=1&&e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:()=>i(!0),className:"mt-2 w-full justify-start text-xs text-muted-foreground hover:text-foreground",children:[e.jsx(s.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),m&&e.jsx(Re,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics",activeField:l})]})]}),!c&&e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings2,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(Wn,{}),e.jsx(Yn,{}),e.jsx(zs,{}),e.jsx(Xn,{}),e.jsx(Us,{}),x==="bullet"&&e.jsx(qs,{}),x==="funnel"&&e.jsx(Js,{}),(x==="bubble"||x==="scatter")&&e.jsx(Hs,{}),e.jsx($s,{}),e.jsx(Ks,{}),e.jsx(Gs,{})]})})]}),c&&e.jsxs(s.AccordionItem,{value:"plugin",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vs,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsx(Fs,{})})]})]}),e.jsx(Qs,{open:d,onOpenChange:i,availableMetrics:n,onSave:O=>{u(o.id,{metricColumns:[...n,O]})},cardId:o.id})]})}function ea({onEditJoins:t}){const a=s.useEditorStore(c=>c.card),{autoJoinMetadata:n}=s.useDashboardCardQuery(a);if(!(n!=null&&n.autoResolved))return null;const{resolvedJoinPlan:r}=n,l=(r==null?void 0:r.joins)||[];if(l.length===0)return null;const d=c=>!c||c.length===0?"No conditions":c.map(o=>{var p,k,m,f;const u=`${(p=o.source)==null?void 0:p.entityName}.${(k=o.source)==null?void 0:k.name}`,x=`${(m=o.target)==null?void 0:m.entityName}.${(f=o.target)==null?void 0:f.name}`,h=o.operator||"=";return`${u} ${h} ${x}`}).join(" AND "),i=c=>!c.joinKeyGroups||c.joinKeyGroups.length===0?"No conditions defined":c.joinKeyGroups.length===1?d(c.joinKeyGroups[0].keys):c.joinKeyGroups.map((o,u)=>({id:u,operator:o.operator,condition:d(o.keys)}));return e.jsx(s.Card,{className:"border-blue-500/30 bg-blue-50/30 dark:bg-blue-950/20",children:e.jsxs("div",{className:"flex items-center justify-between p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(At,{className:"size-4 text-blue-600 dark:text-blue-400"}),e.jsx("h3",{className:"text-sm font-medium text-blue-900 dark:text-blue-100",children:"Auto-Resolved Joins"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"secondary",className:"cursor-help bg-blue-100 text-xs text-blue-700 dark:bg-blue-900 dark:text-blue-300",children:l.length})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:l.map((c,o)=>{const u=i(c),x=Array.isArray(u);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children:c.source.name}),e.jsx(s.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:c.target.name})]}),e.jsx(s.Badge,{variant:"outline",className:"border-green-500/40 bg-green-50/30 text-xs text-green-700 dark:bg-green-950/30 dark:text-green-300",children:c.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:x?u.map(h=>e.jsxs("div",{className:"rounded bg-muted/30 px-2 py-1",children:[e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:h.condition}),h.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",h.operator,")"]})]},h.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:u})})})]},c.id||o)})})})]})})]}),t&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:t,className:"h-7 gap-1 p-2 text-xs text-blue-700 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-100",children:e.jsx(s.SquarePen,{className:"size-3.5"})})]})})}const js={getItem(t){if(typeof window>"u")return null;try{return localStorage.getItem(t)}catch(a){return console.warn(`Failed to read from localStorage (${t}):`,a),null}},setItem(t,a){if(!(typeof window>"u"))try{localStorage.setItem(t,a)}catch(n){console.warn(`Failed to write to localStorage (${t}):`,n)}}};function sa({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:d,activeField:i}){var g,y;const[c,o]=D.useState(()=>js.getItem("chart-selector-expanded")==="true"),[u,x]=D.useState(!1),h=s.useEditorStore(T=>T.card),p=s.useEditorStore(T=>T.actions.updateCardConfig),k=n.length>0||r.length>0||l.length>0,{data:m,autoJoinMetadata:f}=s.useDashboardCardQuery(h),j=((g=h==null?void 0:h.config)==null?void 0:g.joinPlan)||(f!=null&&f.autoResolved?f.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),C=((y=h==null?void 0:h.dataSource)==null?void 0:y.selectedEntities)||[],I=T=>{p(h.id,{...h==null?void 0:h.config,joinPlan:T}),x(!1)},O=()=>{p(h.id,{...h==null?void 0:h.config,joinPlan:void 0}),x(!1)},R=()=>{x(!1)},v=()=>{x(!0)};D.useEffect(()=>{js.setItem("chart-selector-expanded",String(c))},[c]);const w=()=>{o(T=>!T)};return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col border-x border-border",children:[e.jsxs("div",{className:s.cn("px-6 pt-4",{"space-y-4":c}),children:[e.jsx("div",{className:s.cn("overflow-hidden transition-all duration-300 ease-in-out",c?"max-h-[200px] opacity-100":"max-h-0 opacity-0"),children:c&&e.jsx(zn,{selectedChart:t,onChartChange:a})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:"flex items-center justify-center",children:e.jsx(s.ChartQuickSelector,{selectedChart:t,onChartChange:a,isDropdownExpanded:c,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:k||m}),children:e.jsx(qe.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(ea,{onEditJoins:v}),e.jsx(Zn,{groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:d,activeField:i})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]}),e.jsx(ws,{open:u,onOpenChange:x,joinPlan:j,availableDataSources:C,onSave:I,onCancel:R,onRemove:O,children:e.jsx("div",{})})]})}function ta({initialFilters:t,availableFields:a}={}){const[n,r]=D.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(v=>v.card.dataSource);const{columns:l,isLoading:d}=s.useColumns(),c=a||l||[],o={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=v=>{const w=g=>{if(g.id===v){const y=c[0]||o,T=s.getDataType(y.dataType)==="date";return{...g,conditions:[...g.conditions,{id:`condition-${Date.now()}`,field:y,operator:T?"between":"=",value:T?[]:""}]}}return{...g,groups:g.groups.map(w)}};r(w(n))},x=v=>{const w=g=>{if(g.id===v){const y=c[0]||o,T=s.getDataType(y.dataType)==="date";return{...g,groups:[...g.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:y,operator:T?"between":"=",value:T?[]:""}],groups:[]}]}}return{...g,groups:g.groups.map(w)}};r(w(n))},h=(v,w)=>{const g=y=>y.id===v?{...y,conditions:y.conditions.filter(T=>T.id!==w)}:{...y,groups:y.groups.map(g)};r(g(n))},p=(v,w)=>{const g=y=>y.id===v?{...y,groups:y.groups.filter(T=>T.id!==w)}:{...y,groups:y.groups.map(g)};r(g(n))},k=(v,w,g,y)=>{if(g==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const T=M=>M.id===v?{...M,conditions:M.conditions.map(N=>N.id===w?{...N,[g]:y}:N)}:{...M,groups:M.groups.map(T)};r(T(n))},m=(v,w,g)=>{const y=T=>T.id===v?{...T,conditions:T.conditions.map(M=>M.id===w?{...M,...g}:M)}:{...T,groups:T.groups.map(y)};r(y(n))},f=(v,w)=>{const g=y=>y.id===v?{...y,logicalOperator:w}:{...y,groups:y.groups.map(g)};r(g(n))},j=(v,w)=>{const g=y=>y.id===v?{...y,negate:w}:{...y,groups:y.groups.map(g)};r(g(n))},C=(v,w,g)=>{const y=T=>T.id===v?{...T,conditions:s.arrayMove(T.conditions,w,g)}:{...T,groups:T.groups.map(y)};r(y(n))},I=(v,w,g)=>{const y=T=>T.id===v?{...T,groups:s.arrayMove(T.groups,w,g)}:{...T,groups:T.groups.map(y)};r(y(n))},O=v=>{if(!v||v.conditions.length===0&&v.groups.length===0)return"-- No filters defined";const w=y=>{let T="";typeof y.field=="object"?T=y.field.entityName?`${y.field.entityName}.${y.field.name}`:y.field.name:T=String(y.field);const M=y.operator;let N=y.value;if(y.field.dataType==="string"&&!["in","not in"].includes(y.operator))typeof N=="string"?N=`'${N}'`:Array.isArray(N)&&(N=`'${N.join(", ")}'`);else if(y.field.dataType==="date"||y.field.dataType==="datetime"||y.field.dataType==="timestamp")if(y.operator==="between"&&Array.isArray(N)&&N.length===2){const b=N[0]?`'${N[0]}'`:"NULL",A=N[1]?`'${N[1]}'`:"NULL";return`${T} BETWEEN ${b} AND ${A}`}else if((y.operator==="in"||y.operator==="not in")&&Array.isArray(N)){const b=N.map(A=>A?`'${A}'`:"NULL").join(", ");return`${T} ${M} (${b})`}else typeof N=="string"||N instanceof Date?N=`'${N}'`:Array.isArray(N)&&N.length>0&&(N=`'${N[0]}'`);else if(["in","not in"].includes(y.operator)){let b=[];Array.isArray(N)?b=N.map(A=>typeof A=="string"?`'${A}'`:String(A)):typeof N=="string"?b=N.split(",").map(A=>{const F=A.trim();return y.field.dataType==="string"?`'${F}'`:F}):typeof N=="number"&&(b=[String(N)]),N=`(${b.join(", ")})`}switch(M){case"contains":return typeof N=="string"?`${T} LIKE '%${N.replace(/'/g,"")}'`:`${T} LIKE '%${String(N)}'`;case"startsWith":return typeof N=="string"?`${T} LIKE '${N.replace(/'/g,"")}%'`:`${T} LIKE '${String(N)}%'`;case"endsWith":return typeof N=="string"?`${T} LIKE '%${N.replace(/'/g,"")}'`:`${T} LIKE '%${String(N)}'`;case"isNull":return`${T} IS NULL`;case"isNotNull":return`${T} IS NOT NULL`;default:return`${T} ${M} ${N}`}},g=y=>{const T=y.conditions.map(w),M=y.groups.map(F=>g(F)),N=[...T,...M].filter(Boolean);if(N.length===0)return"";const b=N.join(` ${y.logicalOperator} `),A=N.length>1?`(${b})`:b;return y.negate?`NOT ${A}`:A};return g(v)},R=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:c,isLoading:d,addCondition:u,addGroup:x,removeCondition:h,removeGroup:p,updateCondition:k,updateConditionFields:m,updateGroupOperator:f,updateGroupNegate:j,reorderConditions:C,reorderGroups:I,generateSQLPreview:O,hasAnyFilters:R}}function na({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const aa=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function ra({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:l="w-64"}){const[d,i]=D.useState(!1),c=D.useMemo(()=>{const o={};return n.forEach(u=>{const x=aa(u);o[x]||(o[x]={}),o[x][u.entityId]||(o[x][u.entityId]=[]),o[x][u.entityId].push(u)}),o},[n]);return e.jsxs(s.Popover,{modal:!0,open:d,onOpenChange:i,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":d,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(na,{children:[t.entityName,".",t.name]})}):r,e.jsx(it,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(c).map(([o,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),o]}),children:Object.entries(u).map(([x,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[s.getEntityIcon(h[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:h[0].entityName})]}),h.map((p,k)=>e.jsxs(s.CommandItem,{value:p.id,onSelect:()=>{a(p),i(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===p.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:p.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:p.description&&e.jsx("span",{children:p.description})})]})]},p.id+k))]},`${o}-${x}`))},o))})]})})]})}function Ye(t){var f;const a=s.useEditorStore(j=>j.card),{authToken:n,tokenProps:r}=s.useSemaphorContext(),l=s.useEditorStore(j=>j.card.config),d=l==null?void 0:l.joinPlan,i={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},o={...i,role:"sortby",direction:"asc"},u={joinPlan:d,groupByColumns:[i],metricColumns:[c],sortByColumns:[o]},x=((f=a.dataSource)==null?void 0:f.connectionId)||a.connectionId,{data:h,isPending:p,error:k}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(n==null?void 0:n.accessToken)||"",{connection_id:x,cardConfig:u,cardDataSource:a.dataSource})}catch(j){console.log(t),console.error("error",j)}},enabled:!!x,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(j=>({label:j.value||"BLANK",value:j.value||"BLANK",count:(j==null?void 0:j.count)||0})),isPending:p,error:k}}function la({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:l}){const[d,i]=Ke.useState(!1),{filterValues:c}=Ye(t),o=x=>{n(a.filter(h=>h!==x))},u=x=>{a.includes(x)?n(a.filter(h=>h!==x)):n([...a,x])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:d,onOpenChange:i,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":d,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(x=>{const h=c.find(p=>p.value===x);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:p=>{p.key==="Enter"&&o(x)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.stopPropagation(),o(x)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},x)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:c.map((x,h)=>e.jsxs(s.CommandItem,{onSelect:()=>u(x.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(x.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:x.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x.count})]})]},x.value+h))})]})]})})]})})}function oa({field:t,value:a,onChange:n,placeholder:r="Select value...",className:l}){const{filterValues:d,isPending:i,error:c}=Ye(t);return i?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):c?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:d.map((o,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:o.value,children:o.label},o.value+u))})]})}function ia({value:t,operator:a,onChange:n,className:r}){var o;const{tokenProps:l}=s.useSemaphorContext(),d=(o=l==null?void 0:l.params)==null?void 0:o.timezone,i=D.useMemo(()=>{if(t){if(a==="between"||a==="not between"){if(Array.isArray(t)&&t.length===2){const u=t[0]?new Date(t[0]):void 0,x=t[1]?new Date(t[1]):void 0;if(u&&x)return{from:u,to:x}}}else if(a==="="||a==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(a===">"||a===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(a==="<"||a==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((a==="in"||a==="not in")&&Array.isArray(t)&&t.length>0){const u=new Date(t[0]),x=t.length>1?new Date(t[t.length-1]):u;if(!isNaN(u.getTime()))return{from:u,to:x}}}},[t,a]),c=u=>{if(!u){n(void 0);return}if(u.from&&u.to)n([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const x=new Date(u.from);x.setHours(23,59,59,999),n([u.from.toISOString(),x.toISOString()])}else if(u.to){const x=new Date(u.to);x.setHours(0,0,0,0),n([x.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:i,onChange:c,timezone:d,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const ca=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],da=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],ua=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],ma=["=","!=","isNull","isNotNull"],xa=["between","isNull","isNotNull"],ha={"=":"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 bs(t){return ha[t]||s.titleCase(t)}function pa(t){switch(t){case"string":return da;case"number":return ua;case"boolean":return ma;case"date":return xa;default:return ca}}function Ys({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:d,onUpdateGroupOperator:i,availableFields:c,updateConditionFields:o}){const{attributes:u,listeners:x,setNodeRef:h,transform:p,transition:k,isDragging:m}=s.useSortable({id:t.id}),{isPending:f,error:j}=Ye(t.field),C={transform:s.CSS.Transform.toString(p),transition:k};return e.jsxs("div",{ref:h,style:C,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${m?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...x,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:I=>i(n,I),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"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(ra,{value:t.field,onValueChange:I=>{const O=I,R=s.getDataType(O.dataType)==="date";o(n,t.id,{field:O,value:"",operator:R?"between":"="})},availableFields:c,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:I=>{I==="in"||I==="not in"?o(n,t.id,{operator:I,value:[]}):I==="isNull"||I==="isNotNull"?o(n,t.id,{operator:I,value:null}):o(n,t.id,{operator:I,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?bs(t.operator):""})}),e.jsx(s.SelectContent,{children:pa(s.getDataType(t.field.dataType)).map(I=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:I,children:bs(I)},I))})]}),t.operator==="isNull"||t.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?f?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):j?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(la,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(I=>typeof I=="string")?t.value:[],onChange:I=>o(n,t.id,{value:I}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input,{value:typeof t.value=="string"?t.value:"",onChange:I=>o(n,t.id,{value:I.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(oa,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:I=>o(n,t.id,{value:I}),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:I=>o(n,t.id,{value:I==="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(ia,{value:t.value,operator:t.operator,onChange:I=>o(n,t.id,{value:I}),className:"flex-1"}):e.jsx(s.Input,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:I=>l(n,t.id,"value",I.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>d(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function fa({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:d,onUpdateCondition:i,onUpdateField:c,onRemoveCondition:o,onReorderConditions:u,onReorderGroups:x,onAddCondition:h,onAddGroup:p,availableFields:k,renderFilterGroup:m,updateConditionFields:f}){const{attributes:j,listeners:C,setNodeRef:I,transform:O,transition:R,isDragging:v}=s.useSortable({id:t.id}),w={transform:s.CSS.Transform.toString(O),transition:R},g=T=>{const{active:M,over:N}=T;if(N&&M.id!==N.id){const b=t.conditions.findIndex(F=>F.id===M.id),A=t.conditions.findIndex(F=>F.id===N.id);b!==-1&&A!==-1&&u(t.id,b,A)}},y=T=>{const{active:M,over:N}=T;if(N&&M.id!==N.id&&n){const b=t.groups.findIndex(F=>F.id===M.id),A=t.groups.findIndex(F=>F.id===N.id);b!==-1&&A!==-1&&x(n,b,A)}};return e.jsxs("div",{ref:I,style:w,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${v?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...j,...C,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>l(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:T=>r(t.id,T),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:()=>n&&d(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>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:g,children:e.jsx(s.SortableContext,{items:t.conditions.map(T=>T.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((T,M)=>e.jsx(Ys,{condition:T,index:M,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:i,onUpdateField:c,onRemoveCondition:o,onUpdateGroupOperator:r,availableFields:k,updateConditionFields:f},T.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:y,children:e.jsx(s.SortableContext,{items:t.groups.map(T=>T.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(T=>m(T,a+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>p(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function ga({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:l}){const{currentFilters:d,availableFields:i,isLoading:c,addCondition:o,addGroup:u,removeCondition:x,removeGroup:h,updateCondition:p,updateConditionFields:k,updateGroupOperator:m,updateGroupNegate:f,reorderConditions:j,reorderGroups:C,generateSQLPreview:I,hasAnyFilters:O,setCurrentFilters:R}=ta({initialFilters:t,availableFields:a}),v=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[w,g]=D.useState(!1),y=(N,b,A)=>{const F=E=>E.id===N?{...E,conditions:E.conditions.map(L=>L.id===b?{...L,field:A,dataType:A.dataType}:L)}:{...E,groups:E.groups.map(F)};R(F(d))},T=(N,b=0,A)=>b===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:v,collisionDetection:s.closestCenter,onDragEnd:F=>{const{active:E,over:L}=F;if(L&&E.id!==L.id){const S=N.conditions.findIndex(K=>K.id===E.id),V=N.conditions.findIndex(K=>K.id===L.id);S!==-1&&V!==-1&&j(N.id,S,V)}},children:e.jsx(s.SortableContext,{items:N.conditions.map(F=>F.id),strategy:s.verticalListSortingStrategy,children:N.conditions.map((F,E)=>e.jsx(Ys,{condition:F,index:E,groupId:N.id,groupLogicalOperator:N.logicalOperator,onUpdateCondition:p,onUpdateField:y,onRemoveCondition:x,onUpdateGroupOperator:m,availableFields:i,updateConditionFields:k},F.id))})}),e.jsx(s.DndContext,{sensors:v,collisionDetection:s.closestCenter,onDragEnd:F=>{const{active:E,over:L}=F;if(L&&E.id!==L.id){const S=N.groups.findIndex(K=>K.id===E.id),V=N.groups.findIndex(K=>K.id===L.id);S!==-1&&V!==-1&&C(N.id,S,V)}},children:e.jsx(s.SortableContext,{items:N.groups.map(F=>F.id),strategy:s.verticalListSortingStrategy,children:N.groups.map(F=>T(F,b+1,N.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(N.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),w&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(N.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},N.id):e.jsx(fa,{group:N,depth:b,parentGroupId:A,onUpdateGroupOperator:m,onUpdateGroupNegate:f,onRemoveGroup:h,onUpdateCondition:p,onUpdateField:y,onRemoveCondition:x,onReorderConditions:j,onReorderGroups:C,onAddCondition:o,onAddGroup:u,availableFields:i,renderFilterGroup:T,updateConditionFields:k},N.id),M=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[c?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):T(d),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{id:"advanced-mode",checked:w,onCheckedChange:N=>g(N)}),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)"})]})}),O&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:I(d)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),M>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(O?d:null),children:"Apply Filters"})]})]})}function ja({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:l,isOpen:d,onOpenChange:i}){const c=u=>{n(t,u),i(!1)},o=()=>{r(t),i(!1)};return e.jsxs(s.Dialog,{modal:!1,open:d,onOpenChange:i,children:[d&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(ga,{filters:a,availableFields:l,onSave:c,onCancel:()=>i(!1),onClearAll:o})]})]})}function ba({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var j,C;const[l,d]=D.useState(null),i=s.useEditorStore(I=>I.card),c=s.useEditorStore(I=>I.actions.updateCardConfig),o=(j=i==null?void 0:i.config)==null?void 0:j.joinPlan,u=(C=i==null?void 0:i.dataSource)==null?void 0:C.semanticDomainId,{data:x}=s.useJoinabilityMap(u),h=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],p=D.useCallback(I=>I.startsWith("card-")?null:I.startsWith("source-")||a.find(O=>O.id===I)?"source":n("groupBy").find(O=>O.id===I)?"groupBy":n("metrics").find(O=>O.id===I)?"metrics":n("pivotBy").find(O=>O.id===I)?"pivotBy":n("sortBy").find(O=>O.id===I)?"sortBy":null,[a,n]),k=D.useCallback(I=>{d(I.active.id)},[]),m=D.useCallback(I=>{var T;const{active:O,over:R}=I;if(!R||!t){d(null);return}const v=O.id,w=R.id,g=p(v),y=p(w)||w;if(y==="sortBy"){if(g==="source"){const M=a.find(b=>b.id===v);if(!M){d(null);return}if(!(n("groupBy").some(b=>b.name===M.name&&b.qualifiedEntityName===M.qualifiedEntityName)||n("metrics").some(b=>b.name===M.name&&b.qualifiedEntityName===M.qualifiedEntityName))){d(null);return}}else if(g==="pivotBy"){d(null);return}else if(g!=="groupBy"&&g!=="metrics"&&g!=="sortBy"){d(null);return}}if(g==="source"&&y==="sortBy"){const M=[...a].find(F=>F.id===v);if(!M){d(null);return}const N=n("sortBy");if(s.fieldAlreadyExists(M,N)){d(null);return}const b=s.validateFieldForChartType(M,"sortBy",i.type);if(!b.isValid){s.ue.error("Invalid Field Type",{description:b.reason,position:"top-center",duration:3e3}),d(null);return}const A=s.getNewField(M,"sortBy",N);d(null),r("sortBy",[...N,A]);return}if(g==="source"&&y!=="source"&&y!=="sortBy"){const M=[...a].find(L=>L.id===v);if(!M){d(null);return}const N=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(N.length>0){const L=N[0].qualifiedEntityName;if(!L){d(null);return}if(L!==M.qualifiedEntityName&&M.qualifiedEntityName)if(u&&(x!=null&&x.joinabilityMap)){if(s.calculateFieldState(M,{joinabilityMap:x.joinabilityMap,selectedFields:N,baseEntityName:(T=o==null?void 0:o.baseEntity)==null?void 0:T.name}).state==="unreachable"){s.showJoinRequiredNotification(),d(null);return}}else{if(!o){s.showJoinRequiredNotification(),d(null);return}if(!s.areEntitiesJoined(L,M.qualifiedEntityName,o)){s.showJoinRequiredNotification(),d(null);return}}}const b=n(y);if(s.fieldAlreadyExists(M,b)){d(null);return}const A=s.validateFieldForChartType(M,y,i.type);if(!A.isValid){s.ue.error("Invalid Field Type",{description:A.reason,position:"top-center",duration:3e3}),d(null);return}const F=s.getNewField(M,y,b),E=[...b,F];d(null),r(y,E),y==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(i.type,i.config,c,t,E);return}if(g&&y&&g!=="source"&&y!=="source"&&g!==y){const M=n(g),N=n(y),b=M.find(S=>S.id===v);if(!b){d(null);return}const A=s.validateFieldForChartType(b,y,i.type);if(!A.isValid){s.ue.error("Invalid Field Type",{description:A.reason,position:"top-center",duration:3e3}),d(null);return}const F=s.getNewField(b,y,N);if(d(null),y==="sortBy"){s.fieldAlreadyExists(b,N)||r(y,[...N,F]);return}const E=M.filter(S=>S.id!==v),L=[...N,F];r(g,E),r(y,L),y==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(i.type,i.config,c,t,L);return}if(g&&y&&g===y&&g!=="source"){const M=n(g),N=M.findIndex(A=>A.id===v),b=M.findIndex(A=>A.id===w);if(N!==b){const A=s.arrayMove(M,N,b);r(g,A)}}d(null)},[t,a,n,r,p,o,u,x,i.type,c,i.config]),f=l?h.find(I=>I.id===l):null;return{activeId:l,activeField:f,handleDragStart:k,handleDragEnd:m}}function va({activeView:t,onViewChange:a,splitViewEnabled:n}){const r=s.useEditorStore(o=>o.card),{config:l}=D.useContext(s.SemaphorContext).tokenProps,d=(l==null?void 0:l.showInfoTab)!==!1,{errorMessage:i}=s.useDashboardCardQuery(r),c=()=>n?!1:!["table","pivotTable","aggregateTable"].includes(r.type);return e.jsx(s.Tabs,{value:t,onValueChange:o=>a(o),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),c()&&e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),r.type!=="kpi"&&d&&e.jsx(s.TabsTrigger,{value:"info",className:s.cn("rounded-md transition data-[state=active]:bg-muted",i&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:i?"Error":"Info"})]})})}const ya=[{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 Na(){var o,u;const t=s.useEditorStore(x=>x.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=D.useState(!1),[l,d]=D.useState(""),i=x=>{if(x==="custom"){r(!0);return}r(!1),a(t.id,parseInt(x))},c=x=>{const h=x.target.value;d(h),h&&!isNaN(parseInt(h))&&a(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input$1,{type:"number",value:l,onChange:c,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(o=t.config)==null?void 0:o.rowLimit)==null?void 0:u.toString())||"100",onValueChange:i,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:ya.map(x=>e.jsx(s.SelectItem,{value:x.value,children:x.label},x.value))})]})})}function Ca({card:t,queryData:a,isLoading:n,isFetching:r,pagination:l,onPaginationChange:d,onSortChange:i,sortState:c,splitViewEnabled:o}){const u=D.useMemo(()=>(a==null?void 0:a.records)||[],[a==null?void 0:a.records]);return!o||["table","pivotTable","aggregateTable"].includes(t.type)?e.jsx(Ge,{}):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(Ge,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:(a==null?void 0:a.records)&&e.jsx(s.TableVisual,{card:t,data:u,paginationMetadata:l,onPaginationChange:d,isLoading:n||r,onSortChange:i,sortState:c})})})]})}const Sa="semaphor-split-view-enabled";function wa(){return ks(Sa,!0)}function ka({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onFiltersClick:l,activeCard:d,columns:i,columnsLoading:c,columnsError:o}){var ee,_,ne;const u=s.useEditorStore(Y=>Y.card),x=s.useDashboardStore(Y=>Y.filterValues),h=s.useDashboardStore(Y=>Y.selectedSheetId),p=s.useDashboardStore(Y=>Y.inlineFilterValuesMap[(d==null?void 0:d.id)||""]),{updateCardConfig:k,setCard:m,updateCardInFrame:f,setShowAIDialog:j}=s.useEditorActions(),C=s.useEditorStore(Y=>Y.showAIDialog),I=s.useDashboardStore(Y=>Y.isVisualEditing),[O,R]=D.useState(!1),[v,w]=D.useState(!1),[g,y]=D.useState(null),{config:T}=D.useContext(s.SemaphorContext).tokenProps,M=(T==null?void 0:T.showInfoTab)!==!1,[N,b]=wa();s.useEditorStore(Y=>{var le;return((le=Y.card.customCardPreferences)==null?void 0:le.url)&&Y.card.type==="custom"});const{data:A,errorMessage:F,isLoading:E,isFetching:L,errorSql:S,pagination:V,refetch:K,comparisonMetadata:H}=s.useDashboardCardQuery(d),G=D.useMemo(()=>(A==null?void 0:A.records)||[],[A==null?void 0:A.records]),[q,P]=D.useState(!1);D.useEffect(()=>{L||P(!1)},[L]);const z=()=>{const Y=!N;Y&&t==="table"&&a("chart"),b(Y)},J=(Y,le)=>{const ce={...d,paginationConfig:{page:Y+1,pageSize:le}};m(ce),f(ce)};function B(){return e.jsxs("div",{className:"relative border-b border-border bg-background p-4",children:[e.jsx("button",{onClick:r,className:"absolute right-4 top-4 rounded-md p-1 hover:bg-muted","aria-label":"Close Debug Panel",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsxs("div",{className:"space-y-4 pr-8",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(u.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(x||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(d.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",i.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:c?"Loading...":o?"Error loading columns":JSON.stringify(i.slice(0,5),null,2)})]})]})]})}const W=Y=>{if(!u.config)return;const le=s.sortStateToSortByColumns(Y,u.config.metricColumns,u.config.groupByColumns);k(u.id,{...u.config,sortByColumns:le})},X=D.useMemo(()=>{var Y;return s.sortByColumnsToSortState((Y=u.config)==null?void 0:Y.sortByColumns)},[(ee=u.config)==null?void 0:ee.sortByColumns]);return e.jsxs("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":C&&I}),children:[n&&B(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&C&&e.jsx(Ms,{variant:"outline"}),e.jsx(va,{activeView:t,onViewChange:a,splitViewEnabled:N}),e.jsx(s.FilterInfo,{cardId:d.id,cardFilters:(_=d.config)==null?void 0:_.filters,cardFilterCount:s.getFilterCount(((ne=d.config)==null?void 0:ne.filters)||null),onFiltersClick:l,inlineFilters:d.inlineFilters,inlineFilterValues:p,sheetId:h||""}),H&&e.jsx(s.ComparisonMetadataBadge,{metadata:H,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Na,{})}),C&&e.jsx(qe.EditorClearButton,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:E||L,onClick:()=>{P(!0),K()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":q})})}),t==="chart"&&e.jsx(s.IconButton,{tooltip:N?"Hide Results Table":"Show Results Table",onClick:z,children:N?e.jsx(mt,{className:"size-4"}):e.jsx(kt,{className:"size-4"})}),t==="chart"&&e.jsx(e.Fragment,{children:e.jsx(Ls,{})}),!C&&e.jsx(s.IconButton,{onClick:()=>j(!C),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":N&&!["table","pivotTable","aggregateTable"].includes(d.type)}),children:e.jsx(Ca,{card:d,queryData:A,isLoading:E,isFetching:L,pagination:V,onPaginationChange:J,onSortChange:W,sortState:X,splitViewEnabled:N})}),t==="table"&&(A==null?void 0:A.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:d,data:G,paginationMetadata:V,onPaginationChange:J,isLoading:E||L,onSortChange:W,sortState:X})}),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:F?e.jsx(He,{error:F,errorSql:S,onSendFeedback:()=>{const Y=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:u.config,dataSource:d.dataSource,dashboardFilters:x,errorMessage:F,errorSql:S,generatedSql:A==null?void 0:A.sql});y(Y),w(!0)},onOpenInEditor:()=>{j(!0),setTimeout(()=>{const Y=s.useEditorStore.getState().actions;Y.setIsDevMode(!0),Y.setCardSql(S||""),setTimeout(()=>{Y.setRunSql(!0)},100)},100)}}):e.jsx(Es,{sql:A==null?void 0:A.sql,error:F,errorSql:S})})})]}),g&&e.jsx(s.FeedbackDialog,{open:v,onOpenChange:w,feedbackData:g})]})]})}function Ta({activeField:t}){const[a,n]=D.useState(!0);return D.useEffect(()=>{t&&n(!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 ${a?"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(Qe,{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 Ea=()=>{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 a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Aa({column:t,isSelected:a,onSelect:n,availableFields:r,width:l,onWidthChange:d}){var K,H,G;const i=s.useEditorStore(q=>q.card),{updateCardConfig:c,removeGroupByColumn:o,removeMetricColumn:u,updateFilters:x}=s.useEditorActions(),[h,p]=D.useState(!1),[k,m]=D.useState(!1),f=D.useRef(null),j=D.useCallback(q=>{q.preventDefault(),q.stopPropagation(),m(!0),f.current={startX:q.clientX,startWidth:l||150};const P=J=>{if(!f.current)return;const B=J.clientX-f.current.startX,W=Math.max(80,f.current.startWidth+B);d==null||d(t.id,W)},z=()=>{m(!1),f.current=null,document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",z)};document.addEventListener("mousemove",P),document.addEventListener("mouseup",z)},[l,t.id,d]),C=(K=i==null?void 0:i.config)==null?void 0:K.filters,I=(H=C==null?void 0:C.conditions)==null?void 0:H.some(q=>q.field.name===t.name&&q.field.qualifiedEntityName===t.qualifiedEntityName),O=q=>{q?x(i.id,q):c(i.id,{filters:void 0})},{attributes:R,listeners:v,setNodeRef:w,transform:g,transition:y,isDragging:T}=s.useSortable({id:t.id}),M={transform:s.CSS.Transform.toString(g),transition:y},N=s.getDataType(t.dataType),b=Ia(N),A=()=>{var z;const q=((z=i==null?void 0:i.config)==null?void 0:z.sortByColumns)||[],P=q.findIndex(J=>J.name===t.name);if(P!==-1){const J=[...q];J[P]={...J[P],direction:"asc"},c(i.id,{sortByColumns:J})}else c(i.id,{sortByColumns:[...q,{...t,id:`sort-${t.id}`,role:"sortby",direction:"asc"}]})},F=()=>{var z;const q=((z=i==null?void 0:i.config)==null?void 0:z.sortByColumns)||[],P=q.findIndex(J=>J.name===t.name);if(P!==-1){const J=[...q];J[P]={...J[P],direction:"desc"},c(i.id,{sortByColumns:J})}else c(i.id,{sortByColumns:[...q,{...t,id:`sort-${t.id}`,role:"sortby",direction:"desc"}]})},E=()=>{var z;const q=((z=i==null?void 0:i.config)==null?void 0:z.groupByColumns)||[];if(!q.some(J=>J.name===t.name)){const J={...t,id:`groupby-${t.id}-${Date.now()}`,role:"groupby"};c(i.id,{groupByColumns:[...q,J]})}},L=q=>{var J;const P=((J=i==null?void 0:i.config)==null?void 0:J.metricColumns)||[];if(!P.some(B=>B.name===t.name&&B.aggregate===q)){const B={...t,id:`metric-${t.id}-${q}-${Date.now()}`,label:`${q} of ${t.label||t.name}`,role:"metric",aggregate:q};c(i.id,{metricColumns:[...P,B]})}},S=()=>{t.role==="groupby"?o(i.id,t.id):t.role==="metric"&&u(i.id,t.id)},V={...M,width:l?`${l}px`:void 0,minWidth:l?`${l}px`:"120px"};return e.jsxs("th",{ref:w,style:V,className:s.cn("group relative border-r border-border bg-background px-1 py-0",T&&"opacity-50",a&&"bg-primary/10",k&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...R,...v,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:n,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",a&&"bg-primary/10"),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(b,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:t.label||t.name}),t.role==="metric"&&t.aggregate&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",t.aggregate,")"]}),I&&e.jsx(s.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(s.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(s.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(s.DropdownMenuItem,{onClick:()=>p(!0),children:[e.jsx(s.Filter,{className:s.cn("mr-2 h-4 w-4",I&&"text-primary")}),I?"Edit Filter":"Filter"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:A,children:[e.jsx(lt,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(s.DropdownMenuItem,{onClick:F,children:[e.jsx(rt,{className:"mr-2 h-4 w-4"}),"Sort Z → A"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuSub,{children:[e.jsxs(s.DropdownMenuSubTrigger,{children:[e.jsx(s.Calculator,{className:"mr-2 h-4 w-4"}),"Summarize"]}),e.jsxs(s.DropdownMenuSubContent,{children:[e.jsx(s.DropdownMenuItem,{onClick:()=>L("SUM"),children:"Sum"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("AVG"),children:"Average"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("COUNT"),children:"Count"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("DISTINCT"),children:"Count Distinct"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("MIN"),children:"Min"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("MAX"),children:"Max"})]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:E,children:[e.jsx(Ue,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(s.DropdownMenuItem,{disabled:!0,children:[e.jsx(Ns,{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:j,className:s.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",k&&"bg-primary")}),e.jsx(_s,{open:h,onOpenChange:p,availableFields:r.length>0?r:[t],existingFilters:C,editingCondition:I?(G=C==null?void 0:C.conditions)==null?void 0:G.find(q=>q.field.name===t.name&&q.field.qualifiedEntityName===t.qualifiedEntityName):void 0,onSave:O})]})}function Ia(t){switch(t){case"number":return s.Hash;case"date":return s.Calendar;case"string":default:return s.Type}}function Da({selectedColumn:t,onColumnSelect:a,isLoading:n=!1,sourceFields:r=[]}){var y,T,M,N;const l=s.useEditorStore(b=>b.card),{updateCardConfig:d}=s.useEditorActions(),[i,c]=D.useState(null),[o,u]=D.useState({}),[x,h]=D.useState(!1),p=D.useMemo(()=>{var F,E;const b=((F=l==null?void 0:l.config)==null?void 0:F.groupByColumns)||[],A=((E=l==null?void 0:l.config)==null?void 0:E.metricColumns)||[];return[...b,...A]},[(y=l==null?void 0:l.config)==null?void 0:y.groupByColumns,(T=l==null?void 0:l.config)==null?void 0:T.metricColumns]),k=D.useMemo(()=>{const b=new Set(p.map(A=>`${A.qualifiedEntityName}.${A.name}`));return r.filter(A=>!b.has(`${A.qualifiedEntityName}.${A.name}`))},[r,p]),{data:m,isLoading:f}=s.useDashboardCardQuery(l),j=(m==null?void 0:m.records)||[],C=D.useCallback((b,A)=>{u(F=>({...F,[b]:A}))},[]),I=D.useCallback(b=>{var L,S;const A=s.getDataType(b.dataType),F=((L=l==null?void 0:l.config)==null?void 0:L.groupByColumns)||[],E=((S=l==null?void 0:l.config)==null?void 0:S.metricColumns)||[];if(A==="number"){const V={...b,id:`metric-${b.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};d(l.id,{metricColumns:[...E,V]})}else{const V={...b,id:`groupby-${b.id}-${Date.now()}`,role:"groupby"};d(l.id,{groupByColumns:[...F,V]})}h(!1)},[(M=l==null?void 0:l.config)==null?void 0:M.groupByColumns,(N=l==null?void 0:l.config)==null?void 0:N.metricColumns,l.id,d]),O=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),R=b=>{c(b.active.id)},v=b=>{const{active:A,over:F}=b;if(c(null),!F||A.id===F.id)return;const E=p.findIndex(S=>S.id===A.id),L=p.findIndex(S=>S.id===F.id);if(E!==-1&&L!==-1){const S=s.arrayMove(p,E,L),V=S.filter(H=>H.role==="groupby"),K=S.filter(H=>H.role==="metric");d(l.id,{groupByColumns:V,metricColumns:K})}},w=i?p.find(b=>b.id===i):null,g=b=>{let A="";for(;b>=0;)A=String.fromCharCode(b%26+65)+A,b=Math.floor(b/26)-1;return A};return n?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):p.length===0?e.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-4 p-8 text-center",children:e.jsxs("div",{className:"rounded-lg border-2 border-dashed border-muted-foreground/25 p-12",children:[e.jsx("h3",{className:"text-lg font-medium text-muted-foreground",children:"No columns selected"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground/75",children:"Select columns from the panel on the right to build your table"})]})}):e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(s.DndContext,{sensors:O,collisionDetection:s.closestCenter,onDragStart:R,onDragEnd:v,children:[e.jsxs("table",{className:"w-full border-collapse",children:[e.jsxs("thead",{children:[e.jsxs("tr",{className:"border-b border-border bg-muted/30",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-1 text-center text-xs font-medium text-muted-foreground"}),e.jsx(s.SortableContext,{items:p.map(b=>b.id),strategy:s.horizontalListSortingStrategy,children:p.map((b,A)=>e.jsx("th",{style:{width:o[b.id]?`${o[b.id]}px`:void 0,minWidth:o[b.id]?`${o[b.id]}px`:"120px"},className:"border-r border-border bg-muted/30 px-2 py-1 text-center text-xs font-medium text-muted-foreground",children:g(A)},`letter-${b.id}`))}),e.jsx("th",{className:"w-10 border-r border-border bg-muted/30 px-2 py-1"})]}),e.jsxs("tr",{className:"border-b-2 border-border bg-background",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-2 text-center text-xs font-medium text-muted-foreground",children:"#"}),e.jsx(s.SortableContext,{items:p.map(b=>b.id),strategy:s.horizontalListSortingStrategy,children:p.map(b=>e.jsx(Aa,{column:b,isSelected:(t==null?void 0:t.id)===b.id,onSelect:()=>a(b),availableFields:r,width:o[b.id],onWidthChange:C},b.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(s.Popover,{open:x,onOpenChange:h,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Add column",children:e.jsx(s.Plus,{className:"h-4 w-4"})})}),e.jsx(s.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search columns..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No columns available."}),e.jsx(s.CommandGroup,{heading:"Available Columns",children:k.map(b=>{const A=s.getDataType(b.dataType),F=A==="number"?s.Hash:A==="date"?s.Calendar:s.Type;return e.jsxs(s.CommandItem,{value:b.label||b.name,onSelect:()=>I(b),children:[e.jsx(F,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm",children:b.label||b.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:b.entityName})]})]},b.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:f?e.jsx("tr",{children:e.jsx("td",{colSpan:p.length+2,className:"h-32 text-center",children:e.jsx(s.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):j.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:p.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):j.slice(0,100).map((b,A)=>e.jsxs("tr",{className:s.cn("border-b border-border transition-colors hover:bg-muted/50",A%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:A+1}),p.map(F=>{const E=b[F.name]??b[F.label??""];return e.jsx("td",{style:{width:o[F.id]?`${o[F.id]}px`:void 0,minWidth:o[F.id]?`${o[F.id]}px`:"120px"},className:s.cn("border-r border-border px-3 py-2 text-sm",(t==null?void 0:t.id)===F.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:Ma(E,F)})},`${A}-${F.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},A))})]}),e.jsx(s.DragOverlay,{children:w&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:w.label||w.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(j.length,100)," of ",j.length," rows"]}),e.jsxs("span",{children:[p.length," columns"]})]})]})}function Ma(t,a){if(t==null)return"—";if(typeof t=="number")return a.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 n=new Date(t);if(!isNaN(n.getTime()))return n.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(t)}function La({entityGroups:t,isLoading:a=!1}){var O,R;const n=s.useEditorStore(v=>v.card),{updateCardConfig:r,removeGroupByColumn:l,removeMetricColumn:d}=s.useEditorActions(),[i,c]=D.useState(!0),[o,u]=D.useState(""),[x,h]=D.useState(new Set),p=((O=n==null?void 0:n.config)==null?void 0:O.groupByColumns)||[],k=((R=n==null?void 0:n.config)==null?void 0:R.metricColumns)||[],m=v=>{const w=new Set(x);w.has(v)?w.delete(v):w.add(v),h(w)},f=v=>p.some(w=>w.name===v.name&&w.qualifiedEntityName===v.qualifiedEntityName)||k.some(w=>w.name===v.name&&w.qualifiedEntityName===v.qualifiedEntityName),j=(v,w)=>{if(w)if(s.getDataType(v.dataType)==="number"){const y={...v,id:`metric-${v.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(n.id,{metricColumns:[...k,y]})}else{const y={...v,id:`groupby-${v.id}-${Date.now()}`,role:"groupby"};r(n.id,{groupByColumns:[...p,y]})}else{const g=p.findIndex(T=>T.name===v.name&&T.qualifiedEntityName===v.qualifiedEntityName),y=k.findIndex(T=>T.name===v.name&&T.qualifiedEntityName===v.qualifiedEntityName);g!==-1&&l(n.id,p[g].id),y!==-1&&d(n.id,k[y].id)}},C=v=>{if(!o)return v;const w=o.toLowerCase();return v.filter(g=>g.name.toLowerCase().includes(w)||g.label&&g.label.toLowerCase().includes(w))},I=v=>{switch(s.getDataType(v)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.Type}};return i?e.jsxs("div",{className:"flex h-full w-72 flex-col border-l border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Columns"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>c(!1),title:"Close panel",children:e.jsx(Ct,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search columns...",value:o,onChange:v=>u(v.target.value),className:"h-8 pl-8 text-sm"})]})}),(p.length>0||k.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[p.length>0&&e.jsxs(s.Collapsible,{defaultOpen:!0,children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(Ue,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsx("span",{children:"Groupings"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:p.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:p.map(v=>{const w=I(v.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(w,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:v.label||v.name}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>l(n.id,v.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},v.id)})})})]}),k.length>0&&e.jsxs(s.Collapsible,{defaultOpen:!0,children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(s.Calculator,{className:"h-3.5 w-3.5 text-green-500"}),e.jsx("span",{children:"Metrics"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:k.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:k.map(v=>{const w=I(v.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(w,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:v.label||v.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:v.aggregate}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>d(n.id,v.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},v.id)})})})]})]}),e.jsx(s.ScrollArea,{className:"flex-1",children:e.jsx("div",{className:"p-2",children:a?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(v=>{const w=C(v.columns);if(w.length===0)return null;const g=x.has(v.entityId)||o.length>0;return e.jsxs(s.Collapsible,{open:g,onOpenChange:()=>m(v.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",g&&"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:v.label||v.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:w.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:w.map(y=>{const T=I(y.dataType),M=f(y);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:N=>j(y,N),className:"h-3.5 w-3.5"}),e.jsx(T,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:y.label||y.name})]},y.id)})})})]},v.entityId)})})})]}):e.jsx("div",{className:"flex h-full items-start border-l border-border bg-muted/30 p-2",children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(!0),title:"Open panel",children:e.jsx(St,{className:"h-4 w-4"})})})}const Fa=[{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 Oa({value:t,onChange:a,onSubmit:n,onCancel:r,selectedColumn:l,availableColumns:d}){const[i,c]=D.useState(!1),[o,u]=D.useState("column"),x=D.useRef(null);D.useEffect(()=>{const m=f=>{f.key==="Escape"&&t?r():f.key==="Enter"&&t&&!i&&n(t)};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[t,r,n,i]);const h=m=>{const f=`[${m.label||m.name}]`,j=x.current;if(j){const C=j.selectionStart||0,I=j.selectionEnd||0,O=t.slice(0,C)+f+t.slice(I);a(O),setTimeout(()=>{j.setSelectionRange(C+f.length,C+f.length),j.focus()},0)}else a(t+f);c(!1)},p=m=>{const f=x.current;if(f){const j=f.selectionStart||0,C=f.selectionEnd||0,I=t.slice(0,j)+m.syntax+t.slice(C);a(I),setTimeout(()=>{f.setSelectionRange(j+m.name.length+1,j+m.syntax.length-1),f.focus()},0)}else a(t+m.syntax);c(!1)},k=m=>{switch(s.getDataType(m)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.Type}};return e.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-1.5",children:[e.jsx("div",{className:"flex min-w-[100px] items-center justify-center rounded border border-border bg-background px-2 py-1 text-xs font-medium text-muted-foreground",children:l?e.jsx("span",{className:"truncate",children:l.label||l.name}):e.jsx("span",{children:"—"})}),e.jsxs(s.Popover,{open:i&&o==="function",onOpenChange:m=>{c(m),m&&u("function")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Insert function",children:e.jsx(wt,{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:Fa.map(m=>e.jsx(s.CommandItem,{value:m.name,onSelect:()=>p(m),children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm font-medium",children:m.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:m.syntax})]})},m.name))})]})]})})]}),e.jsxs(s.Popover,{open:i&&o==="column",onOpenChange:m=>{c(m),m&&u("column")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",className:"h-7 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground",title:"Insert column reference",children:[e.jsx("span",{children:"Columns"}),e.jsx(s.ChevronDown,{className:"h-3 w-3"})]})}),e.jsx(s.PopoverContent,{className:"w-[250px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search columns..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No columns found."}),e.jsx(s.CommandGroup,{heading:"Available Columns",children:d.map(m=>{const f=k(m.dataType);return e.jsxs(s.CommandItem,{value:m.label||m.name,onSelect:()=>h(m),children:[e.jsx(f,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:m.label||m.name})]},m.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(s.Input$1,{ref:x,value:t,onChange:m=>a(m.target.value),placeholder:"Enter a formula or select a column...",className:"h-7 border-border bg-background font-mono text-sm"})}),t&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-destructive hover:bg-destructive/10 hover:text-destructive",onClick:r,title:"Cancel (Esc)",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-green-600 hover:bg-green-600/10 hover:text-green-600",onClick:()=>n(t),title:"Apply (Enter)",children:e.jsx(s.Check,{className:"h-4 w-4"})})]})]})}function Ra({className:t}){var p,k,m,f;const a=s.useEditorStore(j=>j.card),[n,r]=D.useState(null),[l,d]=D.useState(""),{columns:i=[],columnGroups:c=[],isLoading:o}=s.useColumns();(p=a==null?void 0:a.config)!=null&&p.groupByColumns,(k=a==null?void 0:a.config)!=null&&k.metricColumns,(m=a==null?void 0:a.config)!=null&&m.groupByColumns,(f=a==null?void 0:a.config)!=null&&f.pivotByColumns;const u=j=>{r(j),d(j?`[${j.label||j.name}]`:"")},x=j=>{console.log("Formula submitted:",j),d(""),r(null)},h=()=>{d(""),r(null)};return e.jsxs("div",{className:s.cn("flex h-full w-full flex-col",t),children:[e.jsx(Oa,{value:l,onChange:d,onSubmit:x,onCancel:h,selectedColumn:n,availableColumns:i}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(Da,{selectedColumn:n,onColumnSelect:u,isLoading:o,sourceFields:i})}),e.jsx(La,{entityGroups:c,isLoading:o})]})]})}function Ba(){var K,H;const[t,a]=D.useState("chart"),[n,r]=D.useState(!1),[l,d]=D.useState(!1),[i,c]=D.useState(!0),o=s.useEditorStore(G=>G.showAIDialog),u=s.useDashboardStore(G=>G.isVisualEditing),{setCardType:x}=s.useEditorActions(),h=s.useEditorStore(G=>G.card.type);D.useEffect(()=>Ea(),[]);const p=G=>{x(G)},k=s.useEditorStore(G=>G.frame),m=s.useEditorStore(G=>G.card);s.useEditorStore(G=>G.activeTabCardId),s.useEditorStore(G=>G.actions.getAvailableFields);const{addCard:f,removeCard:j,updateCard:C,setActiveCard:I,updateFilters:O}=s.useEditorActions(),{columns:R=[],isLoading:v,error:w}=s.useColumns(),g=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),y=m,{getFieldsForContainer:T,setFieldsForContainer:M}=s.useFieldManagement(y),{activeField:N,handleDragStart:b,handleDragEnd:A}=ba({activeCardId:k.activeCardId,sourceFields:R,getFieldsForContainer:T,setFieldsForContainer:M}),F=(G,q)=>{q&&O(G,q)},E=G=>{var q;C(G,{config:{...(q=k.cards.find(P=>P.id===G))==null?void 0:q.config,filters:void 0}})},L=R,S=G=>{if(!G)return 0;let q=G.conditions.length;return G.groups.forEach(P=>{q+=S(P)}),q},V=S(((K=y==null?void 0:y.config)==null?void 0:K.filters)||null);return e.jsxs(s.DndContext,{sensors:g,collisionDetection:s.closestCenter,onDragStart:b,onDragEnd:A,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Ts,{isVisible:i,onToggleVisibility:()=>c(!i)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:h==="tableBuilder"?e.jsx(Ra,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!o&&e.jsx(sa,{selectedChart:h,onChartChange:p,groupByFields:T("groupBy"),pivotByFields:T("pivotBy"),metricsFields:T("metrics"),sortByFields:T("sortBy"),activeField:N}),e.jsx(ka,{selectedChart:h,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onFiltersClick:()=>d(!0),filterCount:V,activeCard:y,dataSourceState:m.dataSource||s.EMPTY_DATA_SOURCE,columns:R,columnsLoading:v,columnsError:w,getFieldsForContainer:T,cards:k.cards,activeCardId:k.activeCardId,addCard:f,setActiveCard:I})]})}),!i&&u&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>c(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),y&&e.jsx(ja,{cardId:y.id,filters:((H=y.config)==null?void 0:H.filters)||null,onFiltersChange:F,onClearFilters:E,availableFields:L,isOpen:l,onOpenChange:d}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Ta,{activeField:N||null})})]})}function Va({authToken:t,onSave:a,onClose:n}){const r=D.useRef(null),l=s.useEditorStore(w=>w.showAIDialog),d=s.useEditorStore(w=>w.isDevMode),i=s.useAssistantLayoutStore(w=>w.setFullscreen),c=s.useAssistantLayoutStore(w=>w.setPanelOpen),o=s.useAssistantLayoutStore(w=>w.setContainer),u=s.useAssistantPanel("editor"),x=s.useFullscreenAssistant(),h=s.useAssistantContainer("editor"),p=x==="editor",k=D.useCallback(w=>{o("editor",w)},[o]),{setAuthToken:m}=s.useDashboardActions(),{setShowAIDialog:f,setOnSave:j,setOnClose:C}=s.useEditorActions(),{setActiveAssistantType:I}=s.useAIActions();D.useEffect(()=>{a&&j(a),n&&C(n)},[a,j,n,C]),D.useEffect(()=>{t&&t.accessToken&&m(t)},[t,m]),D.useEffect(()=>{var w,g;l?((w=r.current)==null||w.resize(40),c("editor",!0),I("editor")):((g=r.current)==null||g.resize(0),c("editor",!1),x==="editor"&&i(null),I(null))},[l,c,I,i,x]);function O(w){w<1?(f(!1),c("editor",!1),x==="editor"&&i(null),I(null)):(l||(f(!0),I("editor")),u.isOpen||c("editor",!0))}function R(){return e.jsxs(e.Fragment,{children:[e.jsx(Ts,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow border-l",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:s.cn("grow transition-opacity",p&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Bn,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:O,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(ps,{isFullscreen:p,onFullscreenChange:w=>i(w?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:k,className:s.cn("absolute inset-0",!p&&"pointer-events-none")})]})]})}function v(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:s.cn("flex grow transition-opacity",p&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Ba,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:O,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(ps,{isFullscreen:p,onFullscreenChange:w=>i(w?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:k,className:s.cn("absolute inset-0",!p&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:d?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:R()}):v()})}function Pa(){s.useDashboardStore(i=>i.selectedCardId);const t=s.useDashboardStore(i=>i.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(i=>i.actions),n=s.useDashboardStore(i=>i.isVisualEditing),r=s.useDashboardStore(i=>i.actions.updateFrame);function l(i){t&&(r(t,i),a(!1))}function d(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(Va,{onSave:l,onClose:d})})}exports.default=Pa;
193
+ `;C(V)}function K(){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:n?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(Rt,{})}),n&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),n&&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(Bt,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function H(){var V,G,U,$,J,B;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:T||L,onClick:()=>{M()},className:"h-8 shrink-0",size:"sm",children:[T||L?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(s.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(Ft,{errorSql:F,sql:j==null?void 0:j.sql,error:S,onDebugWithAssistant:P}),e.jsx(qe.EditorClearButton,{}),e.jsxs(s.Toggle,{pressed:n,onPressedChange:Q=>r(Q),className:"h-8",size:"sm",variant:"outline",children:[e.jsx(Ot,{className:"mr-2 size-4 text-foreground/70"}),"Python"]}),!d&&e.jsxs("button",{disabled:d,onClick:()=>{I(!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:((G=(V=l.preferences)==null?void 0:V.tablePrefs)==null?void 0:G.enableDevModePagination)??!1,onCheckedChange:Q=>{var Y;m({...l.preferences,tablePrefs:{...(Y=l.preferences)==null?void 0:Y.tablePrefs,enableDevModePagination:Q}})}}),e.jsx(s.Label,{htmlFor:"pagination",className:"cursor-pointer text-sm",children:"Paginate"}),(($=(U=l.preferences)==null?void 0:U.tablePrefs)==null?void 0:$.enableDevModePagination)&&e.jsxs(s.Select,{value:String(((B=(J=l.preferences)==null?void 0:J.tablePrefs)==null?void 0:B.pageSize)||50),onValueChange:Q=>{var X,ne,W;const Y=Number(Q),se={...l,preferences:{...l.preferences,tablePrefs:{...(X=l.preferences)==null?void 0:X.tablePrefs,pageSize:Y}},paginationConfig:{page:1,pageSize:Y}};O(se),R(se),l.sql&&((W=(ne=l.preferences)==null?void 0:ne.tablePrefs)!=null&&W.enableDevModePagination)&&k(!0)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"10",children:"10"}),e.jsx(s.SelectItem,{value:"25",children:"25"}),e.jsx(s.SelectItem,{value:"50",children:"50"}),e.jsx(s.SelectItem,{value:"100",children:"100"}),e.jsx(s.SelectItem,{value:"500",children:"500"}),e.jsx(s.SelectItem,{value:"1000",children:"1000"})]})]})]}),o&&o.length>0&&e.jsxs(s.HoverCard,{openDelay:200,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",className:"h-8 gap-2 px-2",children:[e.jsx(s.Filter,{className:"size-4"}),e.jsx(s.Badge,{className:"h-5 min-w-5 bg-purple-100 px-1.5 text-purple-700 hover:bg-purple-100 dark:bg-purple-950 dark:text-purple-300",children:o.length})]})}),e.jsx(s.HoverCardContent,{className:"mr-4 max-h-[400px] w-[500px] overflow-auto p-0",children:e.jsxs("div",{className:"p-3",children:[e.jsx("div",{className:"mb-2 text-sm font-semibold",children:"Active Dashboard Filters"}),e.jsx(s.CodeHighlighter,{code:JSON.stringify(o,null,2),language:"json"})]})})]})]})]})})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsx("div",{className:"relative flex grow overflow-y-scroll",children:K()}),H()]})}const Pt=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:s.Grid3x3}];function zt({className:t}){const a=s.useEditorStore(o=>o.card),{setCardType:n,setCard:r,updateCardInFrame:l}=s.useEditorActions(),d=["table","aggregateTable","pivotTable"].includes(a.type),i=s.hasValidCardConfig(a.config);if(!d||!i)return null;const c=o=>{var x;const u=o;if(u==="aggregateTable"&&((x=a.config)!=null&&x.pivotByColumns)&&a.config.pivotByColumns.length>0){const h={...a,type:u,config:{...a.config,pivotByColumns:[]}};r(h),l(h)}else{n(u);const h={...a,type:u};l(h)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:a.type,onValueChange:c,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:Pt.map(o=>{const u=o.icon,x=a.type===o.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:o.value,id:`table-type-${o.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${o.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all",x?"bg-muted text-foreground shadow-sm":"text-muted-foreground hover:bg-muted/50"),children:[e.jsx(u,{className:"h-3.5 w-3.5"}),o.label]})]},o.value)})})})}function $t({type:t,isLinked:a,className:n}){const r=s.useDashboardStore(p=>p.selectedFrameId),l=s.useManagementStore(p=>p.selectedVisual),d=s.useEditorStore(p=>p.frame);let i;if(t)i=t;else if(a!==void 0)i=a?"linked":"library";else if(!!!(d!=null&&d.visualId||l!=null&&l.id)&&r)i="local";else if(l&&!r)i="library";else if(d!=null&&d.visualId&&r)i="linked";else if(l!=null&&l.id&&r)i="library";else return null;if(i==="local")return null;const c={linked:"border-purple-200/70 bg-gradient-to-r from-purple-50/50 to-purple-100/30 text-purple-900 shadow-sm hover:from-purple-100/60 hover:to-purple-100/50 hover:shadow-md dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100 dark:hover:from-purple-950/60 dark:hover:to-purple-900/50",library:"border-blue-200/70 bg-gradient-to-r from-blue-50/50 to-blue-100/30 text-blue-900 shadow-sm hover:from-blue-100/60 hover:to-blue-100/50 hover:shadow-md dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30 dark:text-blue-100 dark:hover:from-blue-950/60 dark:hover:to-blue-900/50"},o={linked:"Linked to library: Changes made here update the library visual and all linked instances.",library:"Library visual: Share and reuse this visual across multiple dashboards."},u={linked:"border-purple-200 bg-purple-50 text-purple-900 dark:border-purple-800 dark:bg-purple-950 dark:text-purple-100",library:"border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-800 dark:bg-blue-950 dark:text-blue-100"},x={linked:"fill-purple-50 dark:fill-purple-950",library:"fill-blue-50 dark:fill-blue-950"},h={linked:e.jsx(gt,{className:"h-3.5 w-3.5"}),library:e.jsx(ft,{className:"h-3.5 w-3.5"})};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:s.cn("cursor-help select-none transition-all",c[i],n),children:h[i]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:s.cn("max-w-xs",u[i]),children:[e.jsx(s.TooltipArrow,{className:x[i]}),e.jsx("p",{children:o[i]})]})]})})}function Is({className:t,...a}){var V,G,U;const n=s.useEditorStore($=>$.card),r=((V=n.customCardPreferences)==null?void 0:V.showCardHeader)??!0,l=((U=(G=n.preferences)==null?void 0:G.displayOptions)==null?void 0:U.showInlineFilterBar)??!0,d=s.useEditorStore($=>$.frame),i=s.useDashboardStore($=>$.dashboard.filters),c=s.useDashboardStore($=>$.selectedSheetId),[o,u]=D.useState(!1),{currentUser:x}=s.useCurrentUserInfo(),{tokenProps:h}=D.useContext(s.SemaphorContext),p=s.useEditorStore($=>$.actions.setRunSql),{updateFilter:w}=s.useDashboardActions(),m=i==null?void 0:i.find($=>$.id===d.filterId),{data:f,isLoading:b,isFetching:C,errorMessage:I,errorSql:O,pagination:R}=s.useDashboardCardQuery(n),y=D.useMemo(()=>(f==null?void 0:f.records)||[],[f==null?void 0:f.records]),{setCard:k,updateCardInFrame:g,setIsDevMode:j,setCardSql:T}=s.useEditorActions(),{data:L}=s.useTopoJson(n),N=D.useMemo(()=>{var $;return n.type!=="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}},[n.type,f==null?void 0:f.records,f==null?void 0:f.columnSubtotalMeta,f==null?void 0:f.subtotalColumns,f==null?void 0:f.pivotSchema,f==null?void 0:f.groupByColumns]),v=s.usePivotTableConfig(n,N),A=$=>{j(!0),T($||O||n.sql||n.python||""),setTimeout(()=>{p(!0)},100)},F=()=>{u(!0)},E=D.useMemo(()=>{const $=typeof window<"u"?window.location.href:"",J=typeof navigator<"u"?navigator.userAgent:"",B=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:s.FeedbackCategory.QUERY_GENERATION,user:x,tokenContext:h,systemState:{cardConfig:n.config,dataSource:n.dataSource,dashboardFilters:i,errorMessage:I||void 0,errorSql:O||n.sql||n.python,generatedSql:O||n.sql},metadata:{url:$,userAgent:J,timestamp:new Date().toISOString(),viewport:B}}},[x,h,n,i,I,O]),M=($,J)=>{var Q,Y;const B={...n,paginationConfig:{page:$+1,pageSize:J}};k(B),g(B),n.sql&&((Y=(Q=n.preferences)==null?void 0:Q.tablePrefs)!=null&&Y.enableDevModePagination)&&p(!0)},S=$=>{var Q,Y,se,X;const J=s.sortStateToSortByColumns($,(Q=n.config)==null?void 0:Q.metricColumns,(Y=n.config)==null?void 0:Y.groupByColumns),B={...n,config:{...n.config||{},sortByColumns:J}};k(B),g(B),n.sql&&((X=(se=n.preferences)==null?void 0:se.tablePrefs)!=null&&X.enableDevModePagination)&&p(!0)},P=D.useMemo(()=>!n.id||!(f!=null&&f.records)?null:s.createChartConfig({card:n,data:f==null?void 0:f.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:L}),[n.id,f==null?void 0:f.records,n.type,n.customCfg,n.preferences,L]);function K($){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(s.EditorCustomVisual,{card:$})})}function H(){if(f!=null&&f.records&&(f==null?void 0:f.records.length)===0&&!b&&!C)return I?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(He,{error:I,errorSql:O||n.sql||n.python,onOpenInEditor:A,onSendFeedback:F,showFeedbackButton:!0,errorTitle:"Unable to Create Visual"})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((b||C)&&(!(f!=null&&f.records)||f.records.length===0))return n.type==="table"?e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableSkeleton,{})}):e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!n.id)return null;if(n.type==="custom")return K(n);if(!["table","pivotTable","aggregateTable","custom"].includes(n.type)&&P)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:b||C?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:P})});if(n.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:n,data:y,paginationMetadata:R,onPaginationChange:M,onSortChange:S,isLoading:b||C})});if(n.type==="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:n,data:v.data,options:v.options,onAggregationChange:$=>{const J=s.handleAggregationChange($,n.config),B={...n,config:J};k(B),g(B)},onAggregationLabelChange:$=>{const J=s.handleAggregationLabelChange($,n.config),B={...n,config:J};k(B),g(B)}})});if(n.type==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:n,data:(f==null?void 0:f.records)||[],groupByColumns:f==null?void 0:f.groupByColumns,pivotSchema:f==null?void 0:f.pivotSchema,paginationMetadata:R,onPaginationChange:M,onAggregationChange:$=>{const J=s.handleAggregationChange($,n.config),B={...n,config:J};k(B),g(B)},isLoading:b||C})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...a,children:[(b||C)&&(f==null?void 0:f.records)&&f.records.length>0&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),r&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:n.title,onSave:$=>k({...n,title:$}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx($t,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(zt,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:n.description||"",onSave:$=>k({...n,description:$}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),m&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:m.title||m.column,onSave:$=>w({...m,title:$}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:m})]})]}),l&&n.inlineFilters&&n.inlineFilters.length>0&&e.jsx("div",{className:"px-6 pb-3",children:e.jsx(s.InlineFilterBar,{card:n,sheetId:c||""})}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:H()}),e.jsx(s.FeedbackDialog,{open:o,onOpenChange:u,feedbackData:E,showDebugInfo:!0})]})}const ze=({language:t,value:a,onChange:n,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:a,onChange:n}),Kt=()=>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."})]})]}),Gt=({customCode:t,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:l})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ze,{language:"json",value:n,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ze,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ze,{language:"javascript",value:t,onChange:l})})]}),qt=({error:t,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:l})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:l,variant:"outline",children:"Close"})]});function Ut(){const[t,a]=D.useState(!1),[n,r]=D.useState(""),[l,d]=D.useState(""),[i,c]=D.useState(""),[o,u]=D.useState(""),x=s.useEditorStore(y=>y.card),h=s.useEditorStore(y=>y.card.customCfg),p=h?JSON.stringify(h,null,2):"",{data:w}=s.useDashboardCardQuery(x),{data:m}=s.useTopoJson(x),{setCardCustomCfg:f,setCustomVisualCode:b}=s.useEditorActions(),C=y=>{var k,g;return JSON.stringify({...y,data:{...y.data,datasets:(g=(k=y.data)==null?void 0:k.datasets)==null?void 0:g.map(j=>({...j,data:[]}))}},null,2)},I=()=>{var k,g;if(!((k=w==null?void 0:w.records)!=null&&k.length))return;const y=s.createChartConfig({card:x,data:w.records,cardType:x.type,queryConfig:x.queryConfig,preferences:x.preferences,topoJson:m});if(y){r(C(y)),c(((g=x.preferences)==null?void 0:g.customVisualCode)||"");const j=s.merge(y,h);d(C(j))}},O=()=>{try{if(i&&b(i),l){const y=JSON.parse(l),k=s.getObjectDiff(JSON.parse(n),y);f(k),u("")}}catch{u("Invalid JSON configuration")}},R=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:a,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:I,className:R?"":"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(Kt,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Is,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Gt,{customCode:i,cardCustomCfgString:p,mergedConfig:l,onConfigChange:y=>d(y??""),onCodeChange:y=>c(y??"")})]}),e.jsx(qt,{error:o,hasCardCustomConfig:!!h,onReset:()=>{d(n),f(null)},onApply:O,onClose:()=>a(!1)})]})]})}function Ht({isStarred:t,onClick:a,className:n}){const r=l=>{l.stopPropagation(),l.preventDefault(),a(l)};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",n),"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 rs({chartType:t,chartName:a,isCustom:n=!1,pluginName:r,isStarred:l,showStar:d=!0,onSelect:i,onToggleStar:c}){return e.jsxs("button",{onClick:i,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:[d&&e.jsx("div",{className:s.cn("absolute left-1 top-1 transition-opacity",l?"opacity-100":"opacity-0 group-hover:opacity-100"),children:e.jsx(Ht,{isStarred:l,onClick:()=>c()})}),n&&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:a,isCustom:n,className:"h-6 w-6"}),e.jsx("span",{title:a,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:a})]})}const ls=[{id:"table",name:"Table"},{id:"bar",name:"Bar Chart"},{id:"line",name:"Line Chart"},{id:"stackedBar",name:"Stacked Bar"},{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 Ds({onChartSelect:t,onClose:a}){const[n,r]=D.useState(""),{starredCharts:l,isStarred:d,toggleStar:i}=s.useStarredChartsStore(),{data:c=[],isLoading:o}=s.useCustomVisualsQuery(),{setCardType:u,setCardPreferences:x,setIsDevMode:h}=s.useEditorStore(y=>y.actions),{setCardCustomCfg:p,setCustomCardPreferences:w,setQueryConfig:m}=s.useEditorActions(),f=D.useMemo(()=>{if(!n)return ls;const y=n.toLowerCase();return ls.filter(k=>k.name.toLowerCase().includes(y))},[n]),b=D.useMemo(()=>{const y=c.filter(g=>g.componentType==="chart");if(!n)return y;const k=n.toLowerCase();return y.filter(g=>g.name.toLowerCase().includes(k))},[c,n]),C=y=>{p(null),x({}),u(y),["custom","text","map"].includes(y)&&(h(!0),m(void 0)),t==null||t(y),a==null||a()},I=y=>{p(null),x({}),u("custom"),w({type:"component",visualType:"single",url:y.url,componentName:y.name,icon:y.icon,pluginChartType:y.chartType}),m(void 0),t==null||t("custom",y),a==null||a()},O=y=>{const k={type:"default",id:y.id,name:y.name};i(k)},R=y=>{const k={type:"custom",id:y.name,url:y.url,icon:y.icon,name:y.name};i(k)};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,{placeholder:"Search charts...",value:n,onChange:y=>r(y.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:[f.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:f.map(y=>e.jsx(rs,{chartType:y.id,chartName:y.name,isCustom:!1,isStarred:d("default",y.id),onSelect:()=>C(y.id),onToggleStar:()=>O(y)},y.id))})]}),b.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:b.map((y,k)=>e.jsx(rs,{chartName:y.name,isCustom:!0,pluginName:y.pluginName,isStarred:d("custom",y.name),onSelect:()=>I(y),onToggleStar:()=>R(y)},`${y.url}-${y.name}-${k}`))})]})]}),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..."})]}),f.length===0&&b.length===0&&!o&&e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No charts found"})]})]})}function Ms({variant:t="ghost"}){var d,i;const[a,n]=D.useState(!1),r=s.useEditorStore(c=>c.card),l=r.type;return e.jsxs(s.Popover,{open:a,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(s.SelectedChartIcon,{className:"size-4",chartType:l,customIcon:(d=r.customCardPreferences)==null?void 0:d.icon,componentName:(i=r.customCardPreferences)==null?void 0:i.componentName})})}),e.jsx(s.PopoverContent,{onOpenAutoFocus:c=>c.preventDefault(),className:"z-[70] w-[360px] p-3",children:e.jsx(Ds,{onClose:()=>n(!1)})})]})}function Jt({error:t,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[l,d]=D.useState(!1),i=D.useRef(null),c=D.useRef(!1);function o(){t&&!c.current&&navigator.clipboard.writeText(t)}function u(p){(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),o())}function x(){const p=window.getSelection();if(p&&p.toString().trim()!==""){const w=p.toString();navigator.clipboard.writeText(w),d(!0),c.current=!0,setTimeout(()=>{d(!1),c.current=!1},1e3)}else c.current=!1}function h(){d(!1),c.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${a}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:i,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${n}`,onClick:o,onKeyDown:u,onMouseUp:x,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function _t(){const t=s.useEditorStore(o=>{var u,x;return(x=(u=o.card.preferences)==null?void 0:u.chartOptions)==null?void 0:x.indexAxis}),a=s.useEditorStore(o=>o.card.type),{setChartOrientation:n,setCardPreferences:r}=s.useEditorStore(o=>o.actions),l=o=>{if(n(o),a!=="bullet")return;const u=o==="y"?"horizontal":"vertical",x=s.useEditorStore.getState().card.preferences,h={...x||{},bulletConfig:{...(x==null?void 0:x.bulletConfig)||{},orientation:u}};r(h)};function d(){const o=t??"x",u=()=>{l(o==="x"?"y":"x")};return e.jsx(s.IconButton,{onClick:u,tooltip:"Chart Orientation",children:o==="x"?e.jsx(Pe,{className:"size-4"}):e.jsx(Ve,{className:"size-4"})})}function i(){const o=()=>{l(t==="y"||t===void 0?"x":"y")};return e.jsx(s.IconButton,{onClick:o,tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(Pe,{className:"size-4"}):e.jsx(Ve,{className:"size-4"})})}function c(){const o=t??"y",u=()=>{l(o==="y"?"x":"y")};return e.jsx(s.IconButton,{onClick:u,tooltip:"Chart Orientation",children:o==="y"?e.jsx(Ve,{className:"size-4"}):e.jsx(Pe,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?i():a==="bullet"?c():d()})}function Qt({className:t}){var w,m,f,b,C,I,O,R,y,k;const a=s.useEditorStore(g=>g.card),{setCardPreferences:n,updateCardInFrame:r,setCard:l}=s.useEditorActions(),[d,i]=D.useState(!1),c=((m=(w=a.preferences)==null?void 0:w.displayOptions)==null?void 0:m.showFilterInfo)??!0,o=((b=(f=a.preferences)==null?void 0:f.displayOptions)==null?void 0:b.showCardToolbar)??!0,u=((I=(C=a.preferences)==null?void 0:C.displayOptions)==null?void 0:I.showChrome)??!0,x=((R=(O=a.preferences)==null?void 0:O.displayOptions)==null?void 0:R.allowScroll)??!0,h=((k=(y=a.preferences)==null?void 0:y.displayOptions)==null?void 0:k.showInlineFilterBar)??!0,p=(g,j)=>{var N;const T={...a.preferences,displayOptions:{...(N=a.preferences)==null?void 0:N.displayOptions,[g]:j}};n(T);const L={...a,preferences:T};l(L),r(L)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:d,onOpenChange:i,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(Ss,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"Display Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Changes apply to dashboard view only"})}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:g=>{p("showFilterInfo",g)},onSelect:g=>g.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:g=>{p("showCardToolbar",g)},onSelect:g=>g.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Toolbar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Hover actions"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:g=>{p("showChrome",g)},onSelect:g=>g.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Chrome"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Frame & padding"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:g=>{p("allowScroll",g)},onSelect:g=>g.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Allow Scroll"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card content scroll"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:h,onCheckedChange:g=>{p("showInlineFilterBar",g)},onSelect:g=>g.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 Yt(){const[t,a]=D.useState(!1),n=s.useEditorStore(h=>h.card),r=s.useEditorStore(h=>h.selectedConnectionId),{setCard:l}=s.useEditorActions(),d=s.useDashboardStore(h=>h.actions.removeCardInlineFilterValue),i=(n==null?void 0:n.inlineFilters)||[];function c(h){const p=h.qualifiedFieldName||h.name;if(i.find(I=>I.column===p))return;const m=h.qualifiedFieldName?h.qualifiedFieldName.split(".").slice(0,-1).join("."):h.qualifiedEntityName||h.entityName,f=s.fmt(h.name),b=h.qualifiedFieldName||f,C={id:s.v4(),column:p,title:h.label||h.name,dataType:h.dataType,table:h.entityName||"",database:"",connectionId:r||"",operation:"in",sql:s.getDefaultFilterSql(h.dataType,m,b),width:250};l({...n,inlineFilters:[...i,C]})}function o(h){const p=i.filter(w=>w.id!==h);l({...n,inlineFilters:p}),d(n.id,h)}function u(h,p){const w=i.map(m=>m.id===h?{...m,...p}:m);l({...n,inlineFilters:w})}return["bar","line","pie","doughnut","table","stackedBar","stackedLine","horizontalBar","radar","polarArea","scatter","bubble","funnel","aggregateTable","custom"].includes(n==null?void 0:n.type)?e.jsx("div",{className:"flex items-center gap-1",children:e.jsxs(s.Popover,{open:t,onOpenChange:a,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.IconButton,{tooltip:"Add Inline Filter",className:s.cn("relative",{"text-primary":i.length>0}),children:[e.jsx(bt,{className:"h-4 w-4"}),i.length>0&&e.jsx("span",{className:"absolute -right-1 -top-1 flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] font-medium text-primary-foreground",children:i.length})]})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80 p-0",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"border-b px-4 py-3",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Inline Filters"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"On-card filters for fast, focused exploration."})]}),e.jsx("div",{className:"flex max-h-[300px] flex-col overflow-hidden",children:e.jsx(s.DndContext,{collisionDetection:s.closestCenter,children:e.jsx(s.SortableContext,{items:[],strategy:s.verticalListSortingStrategy,children:e.jsx(s.FieldsList,{context:"inline-filter",onFieldSelect:c,inlineFilters:i})})})}),i.length>0&&e.jsxs("div",{className:"border-t px-4 py-3",children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Active Filters"}),e.jsx("div",{className:"space-y-1",children:i.map(h=>e.jsx(Wt,{filter:h,onUpdate:p=>u(h.id,p),onRemove:()=>o(h.id)},h.id))})]})]})})]})}):null}function Wt({filter:t,onUpdate:a,onRemove:n}){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=>a(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:n,children:e.jsx(s.X,{className:"h-3 w-3"})})]})]})}function Ls(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var i,c;return(c=(i=d.card)==null?void 0:i.preferences)==null?void 0:c.chartOptions}),n=s.getChartGridStyle(a),{setChartGrid:r}=s.useEditorActions();function l(){const d=["xy","none","x","y"],c=(d.indexOf(n)+1)%d.length;r(d[c])}return e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(_t,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsx(e.Fragment,{}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:l,children:[(n==="xy"||!n)&&e.jsx(s.Grid3x3,{className:"size-4"}),n==="x"&&e.jsx(Ns,{className:"size-4"}),n==="y"&&e.jsx(Ue,{className:"size-4"}),n==="none"&&e.jsx(Tt,{className:"size-4"})]}),e.jsx(Yt,{}),e.jsx(Qt,{})]})}function Xt(){const t=s.useEditorStore(m=>m.frame),a=s.useEditorStore(m=>m.card),{setFrame:n,setActiveTabCardId:r,setCard:l,updateCardInFrame:d}=s.useEditorActions(),i=(m,f)=>{m.dataTransfer.setData("tabIndex",f.toString())},c=m=>{m.preventDefault()},o=(m,f)=>{const b=m.dataTransfer.getData("tabIndex");if(b===f.toString())return;const C=Array.from(t.cards),[I]=C.splice(parseInt(b),1);C.splice(f,0,I),n({...t,cards:C})};function u(m){const f=t.cards.filter(I=>I.id!==m),b=f[0],C={...t,cards:f,activeCardId:b.id};n(C),r(b.id),l(b)}function x(m,f){const b={...t,cards:[...t.cards,f],activeCardId:m.id};n(b),r(f.id)}function h(){const m={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};x(a,m)}function p(m){const f={dataSource:m.dataSource,connectionId:m.connectionId,lastSelectedDatabase:m.lastSelectedDatabase,lastSelectedSchema:m.lastSelectedSchema,lastSelectedTable:m.lastSelectedTable,lastSelectedDatamodelId:m.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};x(m,f)}function w(m,f){return m.cards.length===1&&(f.displayTab===!0||f.displayTab===void 0)||m.activeCardId!==f.id&&(f.displayTab===!0||f.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const b=f.displayTab===void 0?!1:!f.displayTab;l({...f,displayTab:b}),d({...f,displayTab:b})},children:f.displayTab===!0||f.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(dt,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((m,f)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:b=>i(b,f),onDragOver:c,onDrop:b=>o(b,f),className:"",value:m.id,children:[w(t,m),e.jsx(s.Editable,{enabled:t.activeCardId===m.id,text:m.tabTitle||m.title,onSave:b=>{l({...a,tabTitle:b}),d({...a,tabTitle:b})},children:m.tabTitle||m.title},m.id),t.activeCardId===m.id&&e.jsx(s.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:b=>{b.stopPropagation(),h()}}),t.activeCardId===m.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(m.id)})]},m.id)),e.jsx(s.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>p(a),children:e.jsx(s.Plus,{className:"h-4 w-4"})})]})})}function Ge(){const t=s.useEditorStore(b=>b.frame),a=s.useEditorStore(b=>b.card),n=s.useEditorStore(b=>b.isSqlRunning),r=s.useEditorStore(b=>b.isDevMode),{setFrame:l,setActiveTabCardId:d,setCard:i,setIsDevMode:c,setRunSql:o}=s.useEditorActions(),{data:u,isLoading:x,isFetching:h,isError:p}=s.useDashboardCardQuery(a);function w(b){const C=t.cards.find(I=>I.id===b);if(C!=null&&C.sql){r||c(!0),d(b);return}if(C!=null&&C.queryConfig){r&&c(!1),m(b),d(b);return}r||m(b),d(b)}function m(b){const C={...t,cards:t.cards.map(O=>O.id===a.id?a:O),activeCardId:b};l(C);const I=C.cards.find(O=>O.id===b);I.sql&&o(!0),i(I)}function f(){return a.type==="kpi"?x||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:a,data:u==null?void 0:u.records,isPending:x||h,isError:p})})}):a.type==="text"?x||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:n,card:a,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Is,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:w,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(b=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:b.id,children:f()},b.id)),e.jsx(Xt,{})]})}function os({children:t}){const a=s.useEditorStore(v=>v.frame),n=s.useEditorStore(v=>v.card),r=s.useEditorStore(v=>v.isDevMode),l=s.useEditorStore(v=>v.isShowingVisual),d=s.useDashboardStore(v=>v.isVisualEditing),i=s.useEditorStore(v=>v.pythonStdOut),c=s.useEditorStore(v=>v.actions.setRunSql),{setFrame:o,setCard:u,setActiveTabCardId:x,runAssistant:h,setIsDevMode:p,setCardPreferences:w}=s.useEditorActions(),{data:m,isLoading:f,isFetching:b,errorMessage:C,refetch:I,pagination:O}=s.useDashboardCardQuery(n),R=D.useMemo(()=>(m==null?void 0:m.records)||[],[m==null?void 0:m.records]),[y,k]=D.useState(!1);D.useEffect(()=>{b||k(!1)},[b]);function g(v,A){var M,S;const F={...n,paginationConfig:{page:v+1,pageSize:A}};u(F);const E={...a,cards:a.cards.map(P=>P.id===n.id?F:P)};o(E),n.sql&&((S=(M=n.preferences)==null?void 0:M.tablePrefs)!=null&&S.enableDevModePagination)&&c(!0)}function j(v){var M,S,P,K;const A=s.sortStateToSortByColumns(v,(M=n.config)==null?void 0:M.metricColumns,(S=n.config)==null?void 0:S.groupByColumns),F={...n,config:{...n.config||{},sortByColumns:A}};u(F);const E={...a,cards:a.cards.map(H=>H.id===n.id?F:H)};o(E),n.sql&&((K=(P=n.preferences)==null?void 0:P.tablePrefs)!=null&&K.enableDevModePagination)&&c(!0)}function T(){const v=JSON.stringify(m==null?void 0:m.records,null,2),A=new Blob([v],{type:"application/json"}),F=URL.createObjectURL(A),E=document.createElement("a");E.href=F,E.download=`${n.title}.json`,E.click()}function L(){const A=[Object.keys(m==null?void 0:m.records.reduce((S,P)=>({...S,...P}),{})).join(","),...((m==null?void 0:m.records)||[]).map(S=>Object.values(S).join(","))].join(`
194
+ `),F=new Blob([A],{type:"text/csv"}),E=URL.createObjectURL(F),M=document.createElement("a");M.href=E,M.download=`${n.title}.csv`,M.click()}function N(){const v=`Can you get the documentation for ${n.type} chart?`;h(v)}return n?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[l&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(Ms,{}),d&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:N,children:e.jsx(ot,{className:"size-4"})}),!["table","custom"].includes(n.type)&&d&&e.jsx(Ut,{})]}),!l&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:L,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:T,children:e.jsx(ut,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(m==null?void 0:m.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(s.IconButton,{tooltip:"Refresh",disabled:f||b,onClick:()=>{k(!0),I()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":y})})}),e.jsx(Ls,{})]}),r&&e.jsx(en,{})]}),l?e.jsx(Ge,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[i&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:i&&e.jsx(Zt,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":i}),children:[(m==null?void 0:m.records)&&(m==null?void 0:m.records.length)>0&&e.jsx(s.TableVisual,{card:n,data:R,paginationMetadata:O,onPaginationChange:g,onSortChange:j,isLoading:f||b}),C&&e.jsx(Jt,{error:C})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function Zt(){const t=s.useEditorStore(n=>n.pythonStdOut);if(!t)return null;const a=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:a}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function en(){const t=s.useEditorStore(n=>n.isShowingVisual),a=s.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs(s.Toggle,{pressed:!t,onPressedChange:()=>a(!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 oe({value:t,onCommit:a,type:n="text",placeholder:r,className:l}){const[d,i]=D.useState(t),c=D.useRef(!1);D.useEffect(()=>{i(t)},[t]);const o=()=>{if(c.current){c.current=!1;return}d!==t&&a(d)},u=x=>{if(x.key==="Enter"){x.currentTarget.blur();return}x.key==="Escape"&&(c.current=!0,i(t),x.currentTarget.blur())};return e.jsx(s.Input$1,{type:n,placeholder:r,value:d,onChange:x=>i(x.target.value),onBlur:o,onKeyDown:u,className:l})}function he({defaultValue:t,label:a,options:n,value:r,onValueChange:l,className:d,icon:i,showPlaceholderLabel:c=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",d),children:e.jsxs("div",{className:"flex items-center gap-2",children:[i&&e.jsx("span",{children:i}),c&&e.jsx(s.SelectValue,{placeholder:a})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:a}),n.map(o=>e.jsx(s.SelectItem,{value:o.value,children:o.label},o.value))]})})]})}const sn={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:a})=>(a==null?void 0:a.includes("language-"))?e.jsx("pre",{className:"my-3 overflow-x-auto rounded-md bg-muted p-3 text-xs",children:e.jsx("code",{children:t})}):e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:t}),pre:({children:t})=>e.jsx(e.Fragment,{children:t})};function Fs(){var f,b;const t=s.useEditorStore(C=>C.card.customCardPreferences),{data:a}=s.usePluginQuery(),n=(a==null?void 0:a.plugins)||[],r=s.useEditorStore(C=>C.card),l=s.useEditorStore(C=>C.frame),d=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:i}=s.useEditorActions(),{components:c,manifest:o}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(f=o==null?void 0:o.visuals)==null?void 0:f.find(C=>C.name===(t==null?void 0:t.componentName));function x(C,I){if(!t)return;const R={...(t==null?void 0:t.dataInputCardIds)||{},[C]:{cardId:I,hookRef:null}};i({...t,dataInputCardIds:R})}function h(C){var O,R;const I=(O=l==null?void 0:l.cards)==null?void 0:O.filter(y=>{var k;return((k=y==null?void 0:y.customCardPreferences)==null?void 0:k.visualType)!=="multiple"}).map(y=>({value:y.id,label:y.tabTitle||y.title}));return e.jsx("div",{className:"space-y-2",children:(R=C==null?void 0:C.dataInputs)==null?void 0:R.map((y,k)=>{var g,j;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:y}),e.jsx(he,{className:"col-span-6 h-8 w-full justify-between",label:"",options:I||[],value:((j=(g=t==null?void 0:t.dataInputCardIds)==null?void 0:g[k])==null?void 0:j.cardId)||"",onValueChange:T=>x(k,T)})]},k+Math.random())})})}function p(C,I,O=[],R=""){var y,k;return t?C==="input"?e.jsx(oe,{className:`h-8 w-full ${s.removeRing}`,value:String(((y=t==null?void 0:t.settings)==null?void 0:y[I])??R??""),onCommit:g=>{i({...t,settings:{...t==null?void 0:t.settings,[I]:g}})}},I):C==="select"?e.jsx(he,{className:"h-8 w-full",label:"",options:O,value:((k=t==null?void 0:t.settings)==null?void 0:k[I])||R,onValueChange:g=>{i({...t,settings:{...t==null?void 0:t.settings,[I]:g}})}}):null:null}function w(C){const I=Object.entries((C==null?void 0:C.settings)||{});return e.jsx("div",{className:"space-y-3",children:I.map(([O,R])=>{var y;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:R.title}),((y=R.docs)==null?void 0:y.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:R.docs.description})})]})})]}),p(R.ui,O,R.options,R.defaultValue)]},O)})})}function m(C){t&&i({...t,visualType:C,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"",children:[e.jsxs(s.AccordionItem,{value:"plugin-settings",children:[e.jsx(s.AccordionTrigger,{children:"Plugin"}),e.jsx(s.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(he,{icon:e.jsx(vs,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(t==null?void 0:t.url)||"",onValueChange:C=>i({...t||{url:"",componentName:""},url:C})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:d,onValueChange:m,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:c&&e.jsx(he,{icon:e.jsx(ct,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(c==null?void 0:c.filter(C=>C.type===d).map(C=>({value:C.name,label:C.name})))||[],value:t.componentName,onValueChange:C=>{console.log("changing value",C),i({...t,componentName:C})}})})]})})]}),((b=r==null?void 0:r.customCardPreferences)==null?void 0:b.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:(u==null?void 0:u.name)||"Settings"}),(u==null?void 0:u.docs)&&e.jsxs(s.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,onClick:C=>C.stopPropagation(),children:e.jsx(s.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground transition-colors hover:text-foreground"})}),e.jsx(s.HoverCardContent,{side:"right",align:"start",className:"max-h-[40vh] w-[500px] overflow-y-auto text-left",children:e.jsxs("div",{className:"space-y-4 text-left",children:[u.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:u.docs.description}),u.docs.dataSchema&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Data Schema"}),e.jsx("div",{className:"prose prose-sm dark:prose-invert prose-pre:bg-muted prose-pre:text-xs max-w-none",children:e.jsx(s.Markdown,{remarkPlugins:[s.remarkGfm],components:sn,children:u.docs.dataSchema})})]}),u.docs.useCases&&u.docs.useCases.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Use Cases"}),e.jsx("ul",{className:"space-y-1 text-sm",children:u.docs.useCases.map((C,I)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:C})]},I))})]})]})})]})]})}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:w(u)})})]})]})]})}function Se(){const[t,a]=D.useState([]),n=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(u=>u.actions),d=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var x;return(x=u.card.preferences)==null?void 0:x.filterOnClickColumnIndex}),D.useEffect(()=>{d&&a(new Array(d.length).fill(!1))},[d]);function i(u,x){var h,p;x?n!=null&&n.onClickFilter&&((h=n==null?void 0:n.onClickFilter)==null?void 0:h.length)>0?l({...n,onClickFilter:[...n.onClickFilter,{columnIndex:u,expression:""}]}):l({...n,onClickFilter:[{columnIndex:u,expression:""}]}):(l({...n,onClickFilter:(p=n==null?void 0:n.onClickFilter)==null?void 0:p.filter(w=>w.columnIndex!==u)}),a(w=>{const m=[...w];return m[u]=!1,m}))}function c(u,x){var p;const h=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.map(w=>w.columnIndex===u?{...w,expression:x.target.value}:w);l({...n,onClickFilter:h})}function o(u){var x,h,p,w;if(t!=null&&t[u]||(h=(x=n==null?void 0:n.onClickFilter)==null?void 0:x.find(m=>m.columnIndex===u))!=null&&h.expression)return e.jsx(s.Input$1,{value:(w=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(m=>m.columnIndex===u))==null?void 0:w.expression,onChange:m=>c(u,m),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:d==null?void 0:d.map((u,x)=>{var h,p;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=n==null?void 0:n.onClickFilter)!=null&&h.find(w=>w.columnIndex===x)),onCheckedChange:w=>i(x,w)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(w=>w.columnIndex===x))&&e.jsx(s.Pencil,{onClick:()=>{a(w=>{const m=[...w];return m[x]=!w[x],m})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),o(x)]})},u)})})}function tn({idx:t}){var c;const a=s.useEditorStore(o=>{var u;return(u=o.card)==null?void 0:u.preferences}),n=s.useEditorStore(o=>{var u;return(u=o.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(o=>o.actions.setCardPreferences),l=(c=a==null?void 0:a.chartOptions)==null?void 0:c.indexAxis,d=n==null?void 0:n.find(o=>o.idx===t);function i(o,u){(o==="end"||o==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const x={display:o!=="none",align:o,anchor:o,clamp:!0};if(!d)r({...a,datasetOptions:[...n||[],{idx:u,datalabels:x}]});else{const h={...d};h.datalabels=x;const p=n==null?void 0:n.map(w=>w.idx===u?h:w);r({...a,datasetOptions:p})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(s.Tag,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>i("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>i("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(jt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>i("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(yt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>i("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(vt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function nn(){const t=s.useEditorStore(d=>d.card),{data:a}=s.useDashboardCardQuery(t),{keys:n}=s.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(d=>!s.METADATA_KEYS.includes(d));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const d=s.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:i}=s.getKeys(d);l=i.slice(1)}return{transformedMetricKeys:l,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function Je({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Os(){const t=s.useEditorStore(o=>o.card),a=s.useEditorStore(o=>{var u,x,h;return(h=(x=(u=o==null?void 0:o.card)==null?void 0:u.preferences)==null?void 0:x.chartOptions)==null?void 0:h.indexAxis}),{data:n}=s.useDashboardCardQuery(t),r=a==="y"?"Metric":"Dimension",l=a==="y"?"Dimension":"Metric",{dimensionKeys:d,transformedMetricKeys:i,keys:c}=nn();return c.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:d.map(o=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:o,children:Rs(o)},o))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:l}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:i.map((o,u)=>e.jsx(Bs,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:o,idx:u},o))})]})]})}function Rs(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function Bs({col:t,idx:a,className:n,iconClassName:r,children:l}){const d=s.useEditorStore(x=>{var h;return(h=x.card)==null?void 0:h.preferences}),i=s.useEditorStore(x=>{var h,p;return(p=(h=x.card)==null?void 0:h.preferences)==null?void 0:p.datasetOptions}),c=i==null?void 0:i.find(x=>x.idx===a),{setCardPreferences:o}=s.useEditorStore(x=>x.actions);function u(x){if(!c)o({...d,datasetOptions:[...i||[],{idx:a,type:x==="area"?"line":x,fill:x==="area"?"origin":""}]});else{const h={...c};h.type=x==="area"?"line":x,h.fill=x==="area"?"origin":"";const p=i==null?void 0:i.map(w=>w.idx===a?h:w);o({...d,datasetOptions:p})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[l||e.jsx(Je,{className:"max-w-[100px]",title:t,children:Rs(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>u("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>u("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>u("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(tn,{idx:a})]})]})}function De(){const t=s.useDashboardStore(c=>c.dashboard.filters),a=s.useEditorStore(c=>c.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=s.useAssignFilter();function d(c){const o=l(c,"frame");n({...a,filterId:o})}const i=t==null?void 0:t.find(c=>c.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(an,{onSelect:d,columns:r}),i&&e.jsx(s.FilterHeader,{filter:i})]})}function an({columns:t,onSelect:a}){var i;const[n,r]=Ke.useState(!1),[l,d]=Ke.useState("");return e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[l?(i=t.find(c=>c.column_name===l))==null?void 0:i.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(c=>e.jsxs(s.CommandItem,{value:c.column_name,onSelect:o=>{const u=o===l?"":o;d(u),r(!1),u&&a(c)},children:[c.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===c.column_name?"opacity-100":"opacity-0")})]},c.column_name))})]})]})})]})}function rn({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:a=>a.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(Os,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(De,{})]})]})]})})}function ln({cardType:t}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:d=>d.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:a(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(De,{})]})]})]})})}function Vs(){const t=s.useEditorStore(c=>c.card.type),a=s.useEditorStore(c=>c.isDevMode),n=s.useEditorStore(c=>c.card.preferences),{setCardPreferences:r}=s.useEditorStore(c=>c.actions);function l(c){var x;const o={datalabels:{display:c!=="none",align:c,anchor:c,clamp:!0}},u={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(x=n==null?void 0:n.chartOptions)==null?void 0:x.plugins,...o}}};r(u)}function d(){var c,o,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(o=(c=n==null?void 0:n.chartOptions)==null?void 0:c.plugins)==null?void 0:o.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function i(){var c,o,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(o=(c=n==null?void 0:n.chartOptions)==null?void 0:c.plugins)==null?void 0:o.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?d():i()})}const on={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},cn={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function dn(){const t=s.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:un(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Vs,{}),e.jsx(Se,{}),e.jsx(De,{})]})]})}function un(t){if(["line","bar"].includes(t))return e.jsxs(e.Fragment,{children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT x-axis, y-axis-1, y-axis-2, y-axis-3,... FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"X-axis - Category (ex. city)"}),e.jsx("li",{children:"Y-axis - Number (ex. population)"})]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and change the `type` property in the dataset."]}),e.jsx("pre",{children:JSON.stringify(on,null,2)})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and add `fill` property to the dataset. See",e.jsx("a",{className:"mx-1 text-blue-500 hover:underline",href:"https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html",target:"_blank",children:"docs"}),"for more options."]}),e.jsx("pre",{children:JSON.stringify(cn,null,2)})]})]})]});if(t==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis, radius FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Bubble Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"}),e.jsx("li",{children:"Radius - Number (ex. population)"})]})]})]})});if(t==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"})]})]})]})});if(["pie","doughnut","polarArea","funnel"].includes(t))return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:t==="polarArea"?"Polar":t.charAt(0).toUpperCase()+t.slice(1)})," ","chart query"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Measure - Number (ex. population)"})]})]})]})})}function mn({colorRanges:t,setColorRanges:a}){const n={start:-1/0,end:100,color:""};function r(i,c,o){const u=[...t];u[i]={...u[i],[c]:o},a(u)}function l(i){const c=[...t];c.splice(i,1),a(c)}function d(){a([...t,n])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:"Color Range"}),e.jsx(s.Button,{onClick:d,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((i,c)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input$1,{onChange:o=>r(c,"start",o.target.value),value:i.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input$1,{value:i.end,onChange:o=>r(c,"end",o.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input$1,{onChange:o=>r(c,"color",o.target.value),value:i.color,className:s.cn(`h-7 min-w-14 p-0 ${s.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:s.colors.green[600]}),e.jsx("option",{children:s.colors.red[500]}),e.jsx("option",{children:s.colors.yellow[400]}),e.jsx("option",{children:s.colors.orange[500]})]}),e.jsx(s.Button,{onClick:()=>l(c),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},c))]})}function xn(){var x,h,p,w,m;const t=s.useEditorStore(f=>f.card.preferences),a=s.useEditorStore(f=>f.actions.setCardPreferences),n=s.useEditorStore(f=>f.card),r=s.hasValidCardConfig(n.config),l=s.useEditorStore(f=>f.actions.setNumberFormat);s.useEditorStore(f=>{var b,C;return(C=(b=f.card.preferences)==null?void 0:b.formatNumber)==null?void 0:C.decimalPlaces});const d=s.useEditorStore(f=>{var b,C;return(C=(b=f.card.preferences)==null?void 0:b.formatNumber)==null?void 0:C.locale}),i=s.useEditorStore(f=>{var b,C;return(C=(b=f.card.preferences)==null?void 0:b.formatNumber)==null?void 0:C.currency});s.useEditorStore(f=>f.actions.setFilterOnClickField);const c=s.useEditorStore(f=>{var b,C;return(C=(b=f.card.preferences)==null?void 0:b.formatNumber)==null?void 0:C.colorRanges})||[],o=s.useEditorStore(f=>f.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(f=>f.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((x=t==null?void 0:t.formatNumber)!=null&&x.enabled),onCheckedChange:f=>{a({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:f}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:d||"none",onValueChange:f=>{var b,C,I;return l(((b=t==null?void 0:t.formatNumber)==null?void 0:b.decimalPlaces)||0,((C=t==null?void 0:t.formatNumber)==null?void 0:C.currency)||"",f,((I=t==null?void 0:t.formatNumber)==null?void 0:I.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Format"}),e.jsx(s.SelectItem,{value:"none",children:"Auto"},"none"),s.LOCALE_CURRENCY_PAIRS.map(f=>e.jsx(s.SelectItem,{value:f.locale,children:f.locale},f.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:i||"none",onValueChange:f=>{var b,C,I;console.log("currency",f),l(((b=t==null?void 0:t.formatNumber)==null?void 0:b.decimalPlaces)||0,f==="none"?"":f,((C=t==null?void 0:t.formatNumber)==null?void 0:C.locale)||"",((I=t==null?void 0:t.formatNumber)==null?void 0:I.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),u.map(f=>e.jsx(s.SelectItem,{value:f,children:f},f))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Decimals"}),e.jsxs(s.Select,{value:((w=(p=t==null?void 0:t.formatNumber)==null?void 0:p.decimalPlaces)==null?void 0:w.toString())||"0",onValueChange:f=>{var b,C,I;return l(Number(f),((b=t==null?void 0:t.formatNumber)==null?void 0:b.currency)||"",((C=t==null?void 0:t.formatNumber)==null?void 0:C.locale)||"",((I=t==null?void 0:t.formatNumber)==null?void 0:I.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["0","1","2","3","4"].map(f=>e.jsx(s.SelectItem,{value:f,children:f},f))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input$1,{value:((m=t==null?void 0:t.formatNumber)==null?void 0:m.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:f=>{var b,C,I;return l(((b=t==null?void 0:t.formatNumber)==null?void 0:b.decimalPlaces)||0,((C=t==null?void 0:t.formatNumber)==null?void 0:C.currency)||"",((I=t==null?void 0:t.formatNumber)==null?void 0:I.locale)||"",f.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(mn,{colorRanges:c,setColorRanges:o})]})]})}function hn(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{type:"single",collapsible:!0,children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(s.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(xn,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function $e({children:t,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,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:a}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const pn=[{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"}],fn=["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"],gn=fn.map(t=>({label:t,value:t}));function jn(){var o,u,x,h,p,w,m,f,b,C,I,O,R,y,k,g,j,T;const t=s.useEditorStore(L=>L.card),a=(u=(o=t==null?void 0:t.preferences)==null?void 0:o.mapVisualOptions)==null?void 0:u.topoJsonUrl,[n,r]=D.useState(((h=(x=t==null?void 0:t.preferences)==null?void 0:x.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:d}=s.useTopoJson(t),i=Object.keys((d==null?void 0:d.objects)||{}).map(L=>({label:L,value:L}))||[],c=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx($e,{summary:"Map Chart",children:e.jsx("p",{className:"rounded-md bg-muted p-2 font-mono text-xs",children:"SELECT country, value FROM table"})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx($e,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(he,{className:"h-9",options:c,onValueChange:L=>{console.log("value",L),l({...t.preferences,mapVisualOptions:{topoJsonUrl:L}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(s.Input$1,{onChange:L=>{r(L.target.value)},onBlur:()=>{var L;console.log("onBlur",n),l({...t.preferences,mapVisualOptions:{...(L=t.preferences)==null?void 0:L.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),d&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(he,{className:"h-9",options:i,value:((w=(p=t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:w.objectKey)||"",label:"Map Object",onValueChange:L=>{var N;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,objectKey:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(he,{className:"h-9",options:pn,value:((f=(m=t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:f.projection)||"",label:"Projection",onValueChange:L=>{var N;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,projection:L}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(he,{className:"h-9",options:gn,value:((C=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:C.colorScale)||"",label:"Select Color Scale",onValueChange:L=>{var N;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,colorScale:L}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx($e,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input$1,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((O=(I=t.preferences)==null?void 0:I.mapVisualOptions)==null?void 0:O.projectionScale)||1,onChange:L=>{var N;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,projectionScale:Number(L.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input$1,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((k=(y=(R=t.preferences)==null?void 0:R.mapVisualOptions)==null?void 0:y.projectionOffset)==null?void 0:k[0])||0,onChange:L=>{var N,v,A,F;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,projectionOffset:[Number(L.target.value),((F=(A=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:F[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input$1,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((T=(j=(g=t.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:j.projectionOffset)==null?void 0:T[1])||0,onChange:L=>{var N,v,A,F;l({...t.preferences,mapVisualOptions:{...(N=t.preferences)==null?void 0:N.mapVisualOptions,projectionOffset:[((F=(A=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:F[0])||0,Number(L.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Se,{})]})}function bn(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:a}=s.useEditorStore(l=>l.actions);function n(l){a({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Oe({cardType:t,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${n}`}),e.jsx(s.AccordionContent,{children:a||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(bn,{})})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(De,{})]})]})]})})}function vn(){const t=s.useEditorStore(r=>{var l,d;return(d=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:d.sortChart}),{setSortChart:a}=s.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(he,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(Os,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(De,{})]})]})]})})}function yn({cardType:t="table"}){console.log("cardType",t);const a=s.useEditorStore(l=>{var d;return(d=l.card)==null?void 0:d.preferences}),n=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{n({...a,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Se,{}),e.jsx(De,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}function Ps({color:t,onColorChange:a,onClose:n}){const[r,l]=D.useState(0),[d,i]=D.useState(100),[c,o]=D.useState(50),[u,x]=D.useState(t);D.useEffect(()=>{const b=is(t);if(b){const C=cs(b.r,b.g,b.b);l(C.h),i(C.s),o(C.l),x(t)}},[t]);const h=b=>{l(b),w(b,d,c)},p=b=>{const C=b.currentTarget.getBoundingClientRect(),I=Math.max(0,Math.min(1,(b.clientX-C.left)/C.width)),O=Math.max(0,Math.min(1,(b.clientY-C.top)/C.height)),R=I*100,y=(1-O)*100;i(R),o(y),w(r,R,y)},w=(b,C,I)=>{const O=Cn(b,C,I),R=Nn(O.r,O.g,O.b);x(R)},m=b=>{if(x(b),/^#[0-9A-Fa-f]{6}$/.test(b)){const C=is(b);if(C){const I=cs(C.r,C.g,C.b);l(I.h),i(I.s),o(I.l)}}},f=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(a(u),n())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:p,onMouseMove:b=>{b.buttons===1&&p(b)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${d}%`,top:`${100-c}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:b=>h(Number(b.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"HEX"}),e.jsx(s.Input$1,{value:u,onChange:b=>m(b.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:u}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(s.Button,{onClick:f,children:"OK"})]})]})}function is(t){const a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return a?{r:parseInt(a[1],16),g:parseInt(a[2],16),b:parseInt(a[3],16)}:null}function Nn(t,a,n){return"#"+((1<<24)+(t<<16)+(a<<8)+n).toString(16).slice(1)}function cs(t,a,n){t/=255,a/=255,n/=255;const r=Math.max(t,a,n),l=Math.min(t,a,n);let d=0,i=0;const c=(r+l)/2;if(r!==l){const o=r-l;switch(i=c>.5?o/(2-r-l):o/(r+l),r){case t:d=((a-n)/o+(a<n?6:0))/6;break;case a:d=((n-t)/o+2)/6;break;case n:d=((t-a)/o+4)/6;break}}return{h:Math.round(d*360),s:Math.round(i*100),l:Math.round(c*100)}}function Cn(t,a,n){t/=360,a/=100,n/=100;let r,l,d;if(a===0)r=l=d=n;else{const i=(u,x,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?u+(x-u)*6*h:h<.5?x:h<.6666666666666666?u+(x-u)*(.6666666666666666-h)*6:u),c=n<.5?n*(1+a):n+a-n*a,o=2*n-c;r=i(o,c,t+1/3),l=i(o,c,t),d=i(o,c,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(d*255)}}const Sn=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function zs(){var O,R,y,k,g,j,T,L,N,v;const t=s.useEditorStore(A=>A.card),a=s.useEditorStore(A=>{var F;return(F=A.card)==null?void 0:F.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[d,i]=D.useState({}),[c,o]=D.useState(null),[u,x]=D.useState(null),h=D.useMemo(()=>{var M,S,P,K,H,V,G;if(!(l!=null&&l.records)||l.records.length===0)return[];const A=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",F=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line"||(t==null?void 0:t.type)==="horizontalBar"||(t==null?void 0:t.type)==="bullet",E=((M=t==null?void 0:t.config)==null?void 0:M.pivotByColumns)&&t.config.pivotByColumns.length>0;if((A||F)&&E){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const U=new Set;return l.pivotSchema.forEach($=>{$.alias&&U.add($.alias)}),Array.from(U)}if(l.records.length>0){const U=l.records[0],$=Object.keys(U),J=new Set;(S=t==null?void 0:t.config)!=null&&S.groupByColumns&&t.config.groupByColumns.forEach(Y=>{J.add(Y.label||Y.name),J.add(Y.alias||Y.name)});const B=new Set;return(P=t==null?void 0:t.config)!=null&&P.metricColumns&&t.config.metricColumns.forEach(Y=>{const se=Y.alias||Y.name;B.add(se),B.add(`${se}_count`),B.add(`${se}_sum`),B.add(`${se}_avg`),B.add(`${se}_min`),B.add(`${se}_max`);const X=Y.entityName||Y.qualifiedEntityName;X&&(B.add(`${X}_${se}`),B.add(`${X}_${se}_count`))}),$.filter(Y=>!J.has(Y)&&!B.has(Y))}}if((F||A)&&!E&&((H=(K=t==null?void 0:t.config)==null?void 0:K.metricColumns)!=null&&H.length))return t.config.metricColumns.map(U=>U.alias||U.label||U.name);if((G=(V=t==null?void 0:t.config)==null?void 0:V.groupByColumns)!=null&&G.length){const U=t.config.groupByColumns[0],$=U.label||U.name,J=new Set;return l.records.forEach(B=>{const Q=B[$];Q!=null&&J.add(String(Q))}),Array.from(J)}return[]},[l,(O=t==null?void 0:t.config)==null?void 0:O.groupByColumns,(R=t==null?void 0:t.config)==null?void 0:R.pivotByColumns,(y=t==null?void 0:t.config)==null?void 0:y.metricColumns,t==null?void 0:t.type]),p=D.useMemo(()=>s.getDefaultChartColors(),[]);D.useEffect(()=>{const A={};h.forEach((F,E)=>{A[F]=s.getColorForValue(F,E,a==null?void 0:a.colorConfig)}),i(A)},[h,a==null?void 0:a.colorConfig,p]);const w=(A,F)=>{const E={...d,[A]:F};i(E);const M={...a||{},colorConfig:{segments:E}};n(M);const S={...t,preferences:M};r(S)},m=(A,F)=>{var H;const E=p[F%p.length],{[A]:M,...S}=((H=a==null?void 0:a.colorConfig)==null?void 0:H.segments)||{},P={...a||{},colorConfig:{segments:S}};n(P);const K={...t,preferences:P};r(K),i(V=>({...V,[A]:E}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((g=(k=t==null?void 0:t.config)==null?void 0:k.groupByColumns)==null?void 0:g.length)||((T=(j=t==null?void 0:t.config)==null?void 0:j.pivotByColumns)==null?void 0:T.length):(N=(L=t==null?void 0:t.config)==null?void 0:L.groupByColumns)==null?void 0:N.length)||["table","kpi","text","custom","heatmap"].includes(t.type))return null;const C=()=>{const A={...a||{},colorConfig:{segments:{}}};n(A);const F={...t,preferences:A};r(F);const E={};h.forEach((M,S)=>{E[M]=s.getColorForValue(M,S,void 0)}),i(E)},I=Object.keys(((v=a==null?void 0:a.colorConfig)==null?void 0:v.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(Nt,{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:I&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:C,children:[e.jsx(ts,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((A,F)=>{const E=s.isDefaultColor(d[A],F),M=!E;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:c===A,onOpenChange:S=>o(S?A: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[A]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:p.slice(0,10).map((S,P)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",d[A]===S?"border-gray-900":"border-transparent"),style:{backgroundColor:S},onClick:()=>{w(A,S),o(null)},children:[P===F%p.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:S})]},`default-${P}`))})]}),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:Sn.map((S,P)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",d[A]===S?"border-2 border-gray-900":S==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:S},onClick:()=>{w(A,S),o(null)},children:e.jsx("span",{className:"sr-only",children:S})},`preset-${P}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{x({value:A,color:d[A]}),o(null)},children:"Custom color"}),!E&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{m(A,F),o(null)},children:[e.jsx(ts,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:A}),M&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},A)})}),u&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>x(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Ps,{color:u.color,onColorChange:A=>{w(u.value,A),x(null)},onClose:()=>x(null)})})]})]})})]})}function pe({value:t,onSave:a,placeholder:n="",type:r="text",className:l=""}){const[d,i]=D.useState(t??""),[c,o]=D.useState(!1);D.useEffect(()=>{i(t??"")},[t]);const u=()=>{a(d),o(!1)},x=()=>{i(t??""),o(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input,{placeholder:n,type:r,value:c?d:t??"",onChange:h=>{i(h.target.value),o(!0)},onFocus:()=>o(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&c&&d!==t?u():h.key==="Escape"&&x()},"aria-label":n||"Edit field"}),c&&d!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:x,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const wn=["auto","number","currency","percent","scientific","date"],kn=[{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"}],Tn=[{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"}],En=t=>t.charAt(0).toUpperCase()+t.slice(1);function _e({formatOptions:t={},onFormatOptionsChange:a,showTitle:n=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",d=(c,o)=>{a({...t,[c]:o})},i=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[n&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:c=>d("type",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:wn.map(c=>e.jsx(s.SelectItem,{value:c,className:"text-xs",children:c==="auto"?"Auto (Default)":En(c)},c))})]})]}),l!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(l)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??i(),onChange:c=>d("decimalPlaces",parseInt(c.target.value)||0),className:"h-8 text-xs"})})]}),l==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:c=>d("currency",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:kn.map(c=>e.jsx(s.SelectItem,{value:c.value,className:"text-xs",children:c.label},c.value))})]})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:c=>d("useSuffix",c)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:c=>d("locale",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Tn.map(c=>e.jsx(s.SelectItem,{value:c.value,className:"text-xs",children:c.label},c.value))})]})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{placeholder:"e.g., $",value:t.prefix||"",onChange:c=>d("prefix",c.target.value),className:"h-8 text-xs"})})]}),l==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{placeholder:"e.g., units",value:t.suffix||"",onChange:c=>d("suffix",c.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(l)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:c=>d("negativeInParentheses",c)})]}),l==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:c=>d("multiplyBy",c.target.value?parseFloat(c.target.value):void 0),className:"h-8 text-xs"})})]}),l==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input$1,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:c=>d("dateFormat",c.target.value),className:"h-8 text-xs"})})]})]})]})}function ds({axis:t,label:a,type:n,config:r,onChange:l}){var h,p,w,m,f,b,C,I,O,R,y,k;const d=(g,j)=>{l({...r,[g]:j})},i=(g,j)=>{var T,L;l({...r,name:{enabled:g==="enabled"?j:((T=r==null?void 0:r.name)==null?void 0:T.enabled)??!1,text:g==="text"?j:(L=r==null?void 0:r.name)==null?void 0:L.text}})},c=(g,j)=>{var T,L;l({...r,labels:{enabled:g==="enabled"?j:((T=r==null?void 0:r.labels)==null?void 0:T.enabled)??!0,rotation:g==="rotation"?j:(L=r==null?void 0:r.labels)==null?void 0:L.rotation}})},o=(g,j)=>{l({...r,scale:{...r==null?void 0:r.scale,[g]:j===""?"auto":Number(j)}})},u=t==="x"?["auto","top","bottom"]:["auto","left","right"],x=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:a})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:g=>d("enabled",g),onClick:g=>g.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:g=>i("enabled",g)})]}),((p=r==null?void 0:r.name)==null?void 0:p.enabled)&&e.jsx(pe,{placeholder:`${a} title`,value:((w=r==null?void 0:r.name)==null?void 0:w.text)||"",onSave:g=>i("text",g),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:g=>d("position",g),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(g=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:g==="auto"?"Auto (Default)":s.titleCase(g)},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",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((m=r==null?void 0:r.labels)==null?void 0:m.enabled)!==!1,onCheckedChange:g=>c("enabled",g)})]}),((f=r==null?void 0:r.labels)==null?void 0:f.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((b=r==null?void 0:r.labels)==null?void 0:b.rotation)||"auto"),onValueChange:g=>c("rotation",g==="auto"?"auto":Number(g)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:x.map(g=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:g==="auto"?"Auto (Default)":`${g}°`},g))})]})]})]}),n==="value"&&e.jsx(_e,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:g=>l({...r,formatOptions:g}),showTitle:!0,title:"FORMAT"}),n==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"auto",value:((C=r==null?void 0:r.scale)==null?void 0:C.min)==="auto"||((I=r==null?void 0:r.scale)==null?void 0:I.min)===void 0?"":String(r.scale.min),onSave:g=>o("min",g),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"auto",value:((O=r==null?void 0:r.scale)==null?void 0:O.max)==="auto"||((R=r==null?void 0:r.scale)==null?void 0:R.max)===void 0?"":String(r.scale.max),onSave:g=>o("max",g),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"auto",value:((y=r==null?void 0:r.scale)==null?void 0:y.stepSize)==="auto"||((k=r==null?void 0:r.scale)==null?void 0:k.stepSize)===void 0?"":String(r.scale.stepSize),onSave:g=>o("stepSize",g),className:""})})]})]})]})]})]})}function $s(){const t=s.useEditorStore(i=>i.card),a=s.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi","treemap"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,a);if(!l.hasXAxis&&!l.hasYAxis)return null;const d=(i,c)=>{const u={...a||{},[i==="x"?"xAxisConfig":"yAxisConfig"]:c};n(u);const x={...t,preferences:u};r(x)};return e.jsxs(s.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ss,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[l.hasXAxis&&e.jsx(ds,{axis:"x",label:"X-Axis",type:l.xAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(t.type,"x"),a==null?void 0:a.xAxisConfig),onChange:i=>d("x",i)}),l.hasYAxis&&e.jsx(ds,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(t.type,"y"),a==null?void 0:a.yAxisConfig),onChange:i=>d("y",i)})]})})]})}function Ks(){const t=s.useEditorStore(x=>x.card),a=s.useEditorStore(x=>{var h,p,w,m;return(m=(w=(p=(h=x.card)==null?void 0:h.preferences)==null?void 0:p.chartOptions)==null?void 0:w.plugins)==null?void 0:m.legend}),{setLegendOptions:n}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r=s.getDefaultLegendConfig(t.type),l=(r==null?void 0:r.display)??!0,d=(r==null?void 0:r.position)??"top",i=(r==null?void 0:r.align)??"center",c=(x,h)=>{const p={...a,[x]:h};n(p)},o=["top","bottom","left","right"],u=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pt,{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)??l,onCheckedChange:x=>c("display",x)})]}),((a==null?void 0:a.display)??l)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(a==null?void 0:a.position)||d,onValueChange:x=>c("position",x),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:o.map(x=>e.jsx(s.SelectItem,{value:x,className:"text-xs",children:s.titleCase(x)},x))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(a==null?void 0:a.align)||i,onValueChange:x=>c("align",x),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(x=>e.jsx(s.SelectItem,{value:x,className:"text-xs",children:s.titleCase(x)},x))})]})]})]})]})})]})}function Gs(){var E,M,S,P,K,H,V,G,U,$,J;const t=s.useEditorStore(B=>B.card),a=s.useEditorStore(B=>{var Q,Y;return(Y=(Q=B.card)==null?void 0:Q.preferences)==null?void 0:Y.dataLabelsConfig}),n=s.useEditorStore(B=>{var Q;return(Q=B.card)==null?void 0:Q.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const d=t.type==="bullet"?((E=n==null?void 0:n.bulletConfig)==null?void 0:E.orientation)??(((M=n==null?void 0:n.chartOptions)==null?void 0:M.indexAxis)==="x"?"vertical":"horizontal"):void 0,i=d!=null?d==="horizontal":((S=n==null?void 0:n.chartOptions)==null?void 0:S.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",o=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",u=!o,x=t.type==="bubble"||t.type==="scatter",h=(K=(P=n==null?void 0:n.chartOptions)==null?void 0:P.plugins)==null?void 0:K.datalabels,p=(h==null?void 0:h.display)!==!1&&((h==null?void 0:h.anchor)||(h==null?void 0:h.align)),w=s.getDefaultDataLabelsConfig(t.type,t.preferences),m=a??w,f=(w==null?void 0:w.enabled)??p??!1,b=(a==null?void 0:a.enabled)!==void 0?a.enabled:f,C=(B,Q)=>{const X={...w??{},...a??{},[B]:Q};B==="enabled"&&(X.display=Q,Q&&x&&!X.position&&(X.position="bottom")),B==="position"&&x&&(X.position="bottom");const ne={...t.preferences||{},dataLabelsConfig:X};r(ne);const W={...t,preferences:ne};l(W)},I=(B,Q)=>{const Y=a??{},X={...w??{},...Y,font:{...Y.font||{},[B]:Q}},ne={...t.preferences||{},dataLabelsConfig:X};r(ne);const W={...t,preferences:ne};l(W)},O=(B,Q)=>{const Y=a??{},X={...w??{},...Y,formatOptions:{...Y.formatOptions||{},[B]:Q}},ne={...t.preferences||{},dataLabelsConfig:X};r(ne);const W={...t,preferences:ne};l(W)},R=()=>{const B=t.type;return B==="stackedBar"||B==="stackedLine"||B==="pie"||B==="doughnut"?"center":i?"right":"top"},y=t.type!=="treemap"&&t.type!=="heatmap",k=t.type!=="treemap",g=R();let j=[];if(y)if(x)j=["bottom"];else if(c||o)j=["center"];else{const B=i?["center","left","right"]:["center","top","bottom"];j=["auto",...t.type==="bullet"?B:B.filter(Y=>Y!==g),"custom"]}const T=()=>s.titleCase(g),L=["center","start","end"],N=["center","start","end","top","bottom"],v=u?["auto","number","currency","percent","none"]:["number","currency","percent","none"],A=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"}],F=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Et,{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:b,onCheckedChange:B=>C("enabled",B)})]}),b&&e.jsxs(e.Fragment,{children:[y&&!c&&!o&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:x?(m==null?void 0:m.position)||"bottom":(m==null?void 0:m.position)||"auto",onValueChange:B=>C("position",B),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:j.map(B=>e.jsx(s.SelectItem,{value:B,className:"text-xs",children:B==="auto"?T():B==="custom"?"Custom (Advanced)":s.titleCase(B)},B))})]})]}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(a==null?void 0:a.showTotal)??!1,onCheckedChange:B=>C("showTotal",B)})]}),(m==null?void 0:m.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(s.Select,{value:(m==null?void 0:m.anchor)||"center",onValueChange:B=>C("anchor",B),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:L.map(B=>e.jsx(s.SelectItem,{value:B,className:"text-xs",children:s.titleCase(B)},B))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(s.Select,{value:String((m==null?void 0:m.align)||"center"),onValueChange:B=>C("align",B),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:N.map(B=>e.jsx(s.SelectItem,{value:B,className:"text-xs",children:s.titleCase(B)},B))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(m==null?void 0:m.format)||(u?"auto":"none"),onValueChange:B=>C("format",B),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:v.map(B=>e.jsx(s.SelectItem,{value:B,className:"text-xs",children:B==="auto"&&u?"Auto (Use Axis)":B==="none"?"None (Raw Value)":s.titleCase(B)},B))})]})]}),(m==null?void 0:m.format)&&!["auto","none"].includes(m.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(m.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"0",value:String(((H=m==null?void 0:m.formatOptions)==null?void 0:H.decimalPlaces)??(m.format==="currency"?2:m.format==="percent"?1:0)),onSave:B=>O("decimalPlaces",Number(B)),className:""})})]}),m.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((V=m==null?void 0:m.formatOptions)==null?void 0:V.currency)||"USD",onValueChange:B=>O("currency",B),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:A.map(B=>e.jsx(s.SelectItem,{value:B.value,className:"text-xs",children:B.label},B.value))})]})]}),["number","currency"].includes(m.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((G=m==null?void 0:m.formatOptions)==null?void 0:G.useSuffix)??!1,onCheckedChange:B=>O("useSuffix",B)})]}),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:((U=m==null?void 0:m.formatOptions)==null?void 0:U.locale)||"en-US",onValueChange:B=>O("locale",B),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:F.map(B=>e.jsx(s.SelectItem,{value:B.value,className:"text-xs",children:B.label},B.value))})]})]})]}),k&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"12",value:String((($=m==null?void 0:m.font)==null?void 0:$.size)||12),onSave:B=>I("size",Number(B)),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:((J=m==null?void 0:m.font)==null?void 0:J.weight)||"normal",onValueChange:B=>I("weight",B),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(s.Select,{value:(m==null?void 0:m.color)==="auto"||!(m!=null&&m.color)?"auto":"custom",onValueChange:B=>{B==="auto"&&C("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{type:"number",placeholder:"0",value:String((m==null?void 0:m.rotation)||0),onSave:B=>C("rotation",Number(B)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const us=["poor","satisfactory","good"];function ms(t){if(!t)return;const a={...t};return a.targetMetricKey||delete a.targetMetricKey,a.comparativeMetricKey||delete a.comparativeMetricKey,!a.targetValue&&a.targetValue!==0&&delete a.targetValue,(!a.rangeKeys||Object.keys(a.rangeKeys).length===0)&&delete a.rangeKeys,(!a.ranges||Object.keys(a.ranges).length===0)&&delete a.ranges,(!a.rangeLabels||Object.keys(a.rangeLabels).length===0)&&delete a.rangeLabels,a}function qs(){var A,F;const t=s.useEditorStore(E=>E.card.preferences),a=s.useEditorStore(E=>E.card),n=s.useEditorStore(E=>E.isDevMode),{setCardPreferences:r,setChartOrientation:l}=s.useEditorActions(),d=D.useMemo(()=>(t==null?void 0:t.bulletConfig)||{},[t==null?void 0:t.bulletConfig]),c=s.hasValidCardConfig(a==null?void 0:a.config)&&!n,[o,u]=D.useState(d.showRanges??!1),[x,h]=D.useState(d.rangesArePercentages??!1),p=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!c,[w,m]=D.useState(p);D.useEffect(()=>{u(d.showRanges??!1)},[d.showRanges]),D.useEffect(()=>{h(d.rangesArePercentages??!1)},[d.rangesArePercentages]);const f=d.targetValue===void 0?"":String(d.targetValue);D.useEffect(()=>{const E=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!c;m(E)},[d.disableAutoComparative,d.comparativeMetricKey,c]);const b=D.useMemo(()=>{var E,M;return((M=(E=a==null?void 0:a.config)==null?void 0:E.metricColumns)==null?void 0:M.map(S=>{const P=S.label||S.name||S.alias||"";return{value:P,label:P}}))||[]},[(A=a==null?void 0:a.config)==null?void 0:A.metricColumns]);D.useEffect(()=>{var G,U;if(!t||b.length===0)return;const E={};let M=!1;const S=(G=b[1])==null?void 0:G.value;!d.targetMetricKey&&S&&(E.targetMetricKey=S,M=!0);const P=(U=b[2])==null?void 0:U.value;!d.comparativeMetricKey&&!d.disableAutoComparative&&P&&(E.comparativeMetricKey=P,M=!0);const K=b.slice(3),H={...d.rangeKeys||{}};let V=!1;if(us.forEach(($,J)=>{!H[$]&&K[J]&&(H[$]=K[J].value,V=!0)}),V&&(E.rangeKeys=H,M=!0,d.showRanges===void 0&&(E.showRanges=!0)),M){const $=ms({...d,...E});r({...t,bulletConfig:$})}},[b,d,t,r]);const C=E=>{const M=ms({...d,...E});r({...t,bulletConfig:M})},I=(E,M)=>{const S={...d.rangeKeys||{},[E]:M.trim()};M.trim()||delete S[E],C({rangeKeys:Object.keys(S).length>0?S:void 0})},O=(E,M)=>{const S=M===""?void 0:Number(M),P={...d.ranges||{}};S===void 0||Number.isNaN(S)?delete P[E]:P[E]=S,C({ranges:Object.keys(P).length?P:void 0})},R=E=>{if(E===""){C({targetValue:void 0});return}const M=Number(E);C({targetValue:Number.isNaN(M)?void 0:M})},y=(E,M)=>{const S=M.trim(),P={...d.rangeLabels||{}};S?P[E]=S:delete P[E],C({rangeLabels:Object.keys(P).length>0?P:void 0})},k=E=>{u(E),C({showRanges:E})},g=E=>{h(E),C({rangesArePercentages:E})},j=d.orientation||(((F=t==null?void 0:t.chartOptions)==null?void 0:F.indexAxis)==="y"?"horizontal":"vertical"),T=E=>{C({orientation:E}),l(E==="horizontal"?"y":"x")},L=[{value:"__none",label:"None"},...b.map(E=>({value:E.value,label:E.label}))],N=L,v=E=>{if(m(E),!E){C({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!c){C({disableAutoComparative:!1});return}if(d.comparativeMetricKey)C({disableAutoComparative:!1});else{const M=b.find(S=>S.value!==d.targetMetricKey);C({comparativeMetricKey:M==null?void 0:M.value,disableAutoComparative:!1})}};return e.jsxs(s.AccordionItem,{value:"bullet-config",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-6 border-t border-border/50 py-4",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"ORIENTATION"}),e.jsxs(s.Select,{value:j,onValueChange:E=>T(E),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"horizontal",className:"text-xs",children:"Horizontal"}),e.jsx(s.SelectItem,{value:"vertical",className:"text-xs",children:"Vertical"})]})]})]}),c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TARGET METRIC"}),e.jsxs(s.Select,{value:d.targetMetricKey||"__none",onValueChange:E=>C({targetMetricKey:E==="__none"?void 0:E}),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"}),b.map(E=>e.jsx(s.SelectItem,{value:E.value,className:"text-xs",children:E.label},E.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),c?e.jsxs(s.Select,{value:d.comparativeMetricKey||"__none",onValueChange:E=>C({comparativeMetricKey:E==="__none"?void 0:E,disableAutoComparative:E==="__none"}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsx(s.SelectContent,{children:L.map(E=>e.jsx(s.SelectItem,{value:E.value,className:"text-xs",children:E.label},E.value))})]}):e.jsxs("div",{className:"space-y-2 rounded-md border border-border/50 p-3 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between font-medium",children:[e.jsx("span",{children:"Show comparative"}),e.jsx(s.SmallSwitch,{checked:w,onCheckedChange:E=>v(E)})]}),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(oe,{type:"number",className:"h-8 text-xs",value:f,onCommit:R,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:k})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:x,disabled:!o,onChange:E=>g(E.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),o&&e.jsx("div",{className:"space-y-3",children:us.map(E=>{var M,S,P,K,H;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:[E," LABEL"]}),e.jsx(oe,{placeholder:`Display label (${E})`,value:((M=d.rangeLabels)==null?void 0:M[E])||"",onCommit:V=>y(E,V),className:"h-8 text-xs"})]}),c?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[E," COLUMN"]}),e.jsxs(s.Select,{value:((S=d.rangeKeys)==null?void 0:S[E])||"__none",onValueChange:V=>{V==="__none"?I(E,""):I(E,V)},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select column"})}),e.jsx(s.SelectContent,{children:N.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.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[E," COLUMN KEY"]}),e.jsx(oe,{placeholder:"Column key",value:((P=d.rangeKeys)==null?void 0:P[E])||"",onCommit:V=>I(E,V),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:[E," VALUE"]}),e.jsx(oe,{type:"number",placeholder:x?"0.80":"Static value",value:((K=d.ranges)==null?void 0:K[E])===void 0?"":String((H=d.ranges)==null?void 0:H[E]),onCommit:V=>O(E,V),className:"h-8 text-xs"})]})]},E)})})]})]})]})}const xs=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],An=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Le({value:t,onChange:a,label:n}){const[r,l]=D.useState(!1),[d,i]=D.useState(!1),c=()=>{const o=xs.find(u=>u.value===t);return o?o.color:t.startsWith("#")?t:xs[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:c()},"aria-label":`Change color for ${n}`})}),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:An.map(o=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",c()===o?"border-gray-900":"border-transparent"),style:{backgroundColor:o},onClick:()=>{a(o),l(!1)},children:e.jsx("span",{className:"sr-only",children:o})},o))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{i(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:n})]}),d&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>i(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Ps,{color:c(),onColorChange:o=>{a(o),i(!1)},onClose:()=>i(!1)})})]})]})}const In=Object.keys(s.HEATMAP_PRESET_PALETTES);function Us(){const t=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>{var w;return(w=p.card)==null?void 0:w.preferences}),{setCardPreferences:n}=s.useEditorActions(),r=(t==null?void 0:t.type)==="heatmap",l=(a==null?void 0:a.heatmapConfig)||{},d=l.colorPalette??"green",i=l.legendPosition??"bottom",c=D.useMemo(()=>l.colorRange&&l.colorRange[0]&&l.colorRange[1]?[l.colorRange[0],l.colorRange[1]]:[...s.DEFAULT_HEATMAP_CUSTOM_RANGE],[l.colorRange]),o=p=>{const w={...l,...p};w.colorPalette!=="custom"?delete w.colorRange:(!w.colorRange||!w.colorRange[0]||!w.colorRange[1])&&(w.colorRange=[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]),n({...a||{},heatmapConfig:w})},u=p=>{o({colorPalette:p,colorRange:p==="custom"?l.colorRange??[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},x=(p,w)=>{const m=[...c];m[p]=w,o({colorPalette:"custom",colorRange:m})},h=p=>{o({legendPosition:p})};return r?e.jsxs(s.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(s.RadioGroup,{value:d,onValueChange:p=>u(p??"blue"),className:"space-y-3",children:[In.map(p=>{const w=s.HEATMAP_PRESET_PALETTES[p];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`heatmap-${p}`,value:p}),e.jsxs(s.Label,{htmlFor:`heatmap-${p}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:w.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${w.start}, ${w.end})`}})]})]},p)}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(s.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),d==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(Le,{value:c[0],onChange:p=>x(0,p),label:"Start color"}),e.jsx(Le,{value:c[1],onChange:p=>x(1,p),label:"End color"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Color scale position"}),e.jsxs(s.Select,{value:i,onValueChange:p=>h(p??"bottom"),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["top","bottom","left","right"].map(p=>e.jsx(s.SelectItem,{value:p,className:"text-xs",children:p[0].toUpperCase()+p.slice(1)},p))})]})]})]})]}):null}function hs(t){if(!t)return;const a={...t};if(a.xMetricKey||delete a.xMetricKey,a.yMetricKey||delete a.yMetricKey,a.radiusMetricKey||delete a.radiusMetricKey,a.labelKey||delete a.labelKey,a.groupKey||delete a.groupKey,a.enableGrouping===void 0&&delete a.enableGrouping,a.radiusScale||delete a.radiusScale,a.fixedRadius===void 0&&delete a.fixedRadius,a.minRadius===void 0&&delete a.minRadius,a.maxRadius===void 0&&delete a.maxRadius,Object.keys(a).length!==0)return a}function Hs(){var y,k,g,j,T,L,N,v,A,F,E,M;const t=s.useEditorStore(S=>S.card.preferences),a=s.useEditorStore(S=>S.card),n=s.useEditorStore(S=>S.card.type),r=s.useEditorStore(S=>S.isDevMode),{setCardPreferences:l,updateCardInFrame:d}=s.useEditorActions(),i=n==="bubble",c=n==="scatter",o=D.useMemo(()=>(t==null?void 0:t.bubbleScatterConfig)||{},[t==null?void 0:t.bubbleScatterConfig]),x=s.hasValidCardConfig(a==null?void 0:a.config)&&!r,h=D.useMemo(()=>{var S,P;return((P=(S=a==null?void 0:a.config)==null?void 0:S.metricColumns)==null?void 0:P.map(K=>{const H=K.label||K.name||K.alias||"";return{value:H,label:H}}))||[]},[(y=a==null?void 0:a.config)==null?void 0:y.metricColumns]),p=D.useMemo(()=>{var S,P;return((P=(S=a==null?void 0:a.config)==null?void 0:S.groupByColumns)==null?void 0:P.map(K=>{const H=K.label||K.name||K.alias||"";return{value:H,label:H}}))||[]},[(k=a==null?void 0:a.config)==null?void 0:k.groupByColumns]),w=D.useMemo(()=>o.enableGrouping!==void 0?o.enableGrouping:!r&&p.length>=2,[o.enableGrouping,r,p.length]),[m,f]=D.useState(w);D.useEffect(()=>{f(w)},[w]);const b=S=>{const P={...t||{},bubbleScatterConfig:S};l(P),a&&d({...a,preferences:P})},C=S=>{l(S),a&&d({...a,preferences:S})};D.useEffect(()=>{if(!t||h.length===0)return;const S={};let P=!1;if(!o.xMetricKey&&h[0]&&(S.xMetricKey=h[0].value,P=!0),!o.yMetricKey&&h[1]&&(S.yMetricKey=h[1].value,P=!0),i&&!o.radiusMetricKey&&h[2]&&(S.radiusMetricKey=h[2].value,P=!0),!o.labelKey&&p[0]&&(S.labelKey=p[0].value,P=!0),w&&!o.groupKey&&p[1]&&(S.groupKey=p[1].value,S.enableGrouping=!0,P=!0),P){const K=hs({...o,...S});b(K)}},[h,p,o,t,l,i,w]);const I=S=>{const P=hs({...o,...S});b(P)},O=S=>{f(S),I({enableGrouping:S,groupKey:S?o.groupKey:void 0})};if(!i&&!c)return null;const R=i?s.Circle:s.ChartScatter;return e.jsxs(s.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(s.AccordionTrigger,{className:"py-2 text-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R,{className:"h-4 w-4"}),e.jsxs("span",{children:[i?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-1 pb-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-muted-foreground",children:["Dimensions",e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(s.Info,{className:"h-3 w-3"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{children:"Label identifies each point. Group creates separate series in the legend."})})]})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Label Column"}),x?e.jsxs(s.Select,{value:o.labelKey||"",onValueChange:S=>I({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:p.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(oe,{className:"h-8 text-xs",placeholder:"Column name for labels",value:o.labelKey||"",onCommit:S=>I({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:m,onCheckedChange:O})]}),m&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Group By"}),x?e.jsxs(s.Select,{value:o.groupKey||"",onValueChange:S=>I({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:p.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(oe,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:o.groupKey||"",onCommit:S=>I({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"}),x?e.jsxs(s.Select,{value:o.xMetricKey||"",onValueChange:S=>I({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:h.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(oe,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:o.xMetricKey||"",onCommit:S=>I({xMetricKey:S})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Axis"}),x?e.jsxs(s.Select,{value:o.yMetricKey||"",onValueChange:S=>I({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:h.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(oe,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:o.yMetricKey||"",onCommit:S=>I({yMetricKey:S})})]}),i&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Radius"}),x?e.jsxs(s.Select,{value:o.radiusMetricKey||"",onValueChange:S=>I({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:h.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(oe,{className:"h-8 text-xs",placeholder:"Column name for radius",value:o.radiusMetricKey||"",onCommit:S=>I({radiusMetricKey:S})})]})]}),i&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Radius Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Scale Mode"}),e.jsxs(s.Select,{value:o.radiusScale||"sqrt",onValueChange:S=>I({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(oe,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((g=o.minRadius)==null?void 0:g.toString())||"",onCommit:S=>I({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(oe,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((j=o.maxRadius)==null?void 0:j.toString())||"",onCommit:S=>I({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])=>I({fixedRadius:S}),min:3,max:30,step:1,className:"py-2"})]})]}),c&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Point Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(s.Label,{className:"text-xs",children:["Point Size: ",o.fixedRadius||5]}),e.jsx(s.Slider,{value:[o.fixedRadius||5],onValueChange:([S])=>I({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:((L=(T=t==null?void 0:t.xAxisConfig)==null?void 0:T.name)==null?void 0:L.enabled)??!1,onCheckedChange:S=>{var H,V,G,U;const P=o.xMetricKey||"X Axis",K=o.yMetricKey||"Y Axis";C({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{enabled:S,text:((V=(H=t==null?void 0:t.xAxisConfig)==null?void 0:H.name)==null?void 0:V.text)||P}},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{enabled:S,text:((U=(G=t==null?void 0:t.yAxisConfig)==null?void 0:G.name)==null?void 0:U.text)||K}}})}})]}),((v=(N=t==null?void 0:t.xAxisConfig)==null?void 0:N.name)==null?void 0:v.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(oe,{className:"h-8 text-xs",placeholder:o.xMetricKey||"X Axis",value:((F=(A=t==null?void 0:t.xAxisConfig)==null?void 0:A.name)==null?void 0:F.text)||"",onCommit:S=>{var P;C({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{...(P=t==null?void 0:t.xAxisConfig)==null?void 0:P.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(oe,{className:"h-8 text-xs",placeholder:o.yMetricKey||"Y Axis",value:((M=(E=t==null?void 0:t.yAxisConfig)==null?void 0:E.name)==null?void 0:M.text)||"",onCommit:S=>{var P;C({...t??{},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{...(P=t==null?void 0:t.yAxisConfig)==null?void 0:P.name,enabled:!0,text:S||o.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const Dn=[{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 Js(){const t=s.useEditorStore(p=>p.card),a=s.useEditorStore(p=>{var w;return(w=p.card)==null?void 0:w.preferences}),{setCardPreferences:n}=s.useEditorActions(),r=(t==null?void 0:t.type)==="funnel",l=(a==null?void 0:a.funnelConfig)||{},d=l.percentMode??"percentOfTotal",i=l.shrinkFraction??1,c=l.labelThreshold??0,o=p=>{const w={...l,...p};n({...a||{},funnelConfig:w})},u=p=>{o({percentMode:p})},x=p=>{o({shrinkFraction:p[0]})},h=p=>{o({labelThreshold:p[0]})};return r?e.jsxs(s.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Filter,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Funnel Settings"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"PERCENTAGE MODE"}),e.jsx(s.RadioGroup,{value:d,onValueChange:p=>u(p),className:"space-y-2",children:Dn.map(p=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`funnel-${p.value}`,value:p.value,className:"mt-0.5"}),e.jsxs(s.Label,{htmlFor:`funnel-${p.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:p.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p.description})]})]},p.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SEGMENT SHRINK"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Same Width"}),e.jsx(s.Slider,{value:[i],onValueChange:x,min:0,max:1,step:.1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Full Shrink"})]}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Current: ",Math.round(i*100),"%"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABEL VISIBILITY THRESHOLD"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Show All"}),e.jsx(s.Slider,{value:[c],onValueChange:h,min:0,max:25,step:1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Hide Small"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:c===0?"Showing all labels":`Hide labels below ${c}%`})]})]})]}):null}function Mn(){const t=s.useEditorStore(a=>a.card);return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[(t==null?void 0:t.type)==="funnel"&&e.jsx(Js,{}),(t==null?void 0:t.type)==="heatmap"&&e.jsx(Us,{}),(t==null?void 0:t.type)==="bullet"&&e.jsx(qs,{}),((t==null?void 0:t.type)==="bubble"||(t==null?void 0:t.type)==="scatter")&&e.jsx(Hs,{}),e.jsx(zs,{}),e.jsx($s,{}),e.jsx(Ks,{}),e.jsx(Gs,{})]})]})}const Ln=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT dimension, cohort, metric FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),Fn=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),On=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function Rn(){const t=s.useEditorStore(n=>n.card.type);function a(n){const r=["kpi","table","text","map","custom"],l=d=>r.includes(n)?d:e.jsxs(e.Fragment,{children:[d,e.jsx(Mn,{})]});switch(n){case"stackedBar":case"stackedLine":return l(e.jsx(vn,{}));case"tornado":case"pyramid":return l(e.jsx(Oe,{docContent:Ln,cardType:n}));case"kpi":return e.jsx(hn,{});case"line":case"bar":return l(e.jsx(rn,{cardType:n}));case"range":return l(e.jsx(Oe,{docContent:Fn,cardType:n}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(Oe,{cardType:n}));case"bubble":case"scatter":return l(e.jsx(ln,{cardType:n}));case"table":return e.jsx(yn,{cardType:n});case"text":return e.jsx(Oe,{docContent:On,cardType:n,suffix:"Visual"});case"map":return e.jsx(jn,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Fs,{})});default:return l(e.jsx(dn,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[a(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Bn(){const t=D.useRef(null),a=D.useRef(null),n=s.useEditorStore(l=>l.isShowingVisual),r=s.useEditorStore(l=>l.showAIDialog);return D.useEffect(()=>{var l,d,i,c;r?((l=t.current)==null||l.resize(0),(d=a.current)==null||d.resize(0)):((i=t.current)==null||i.resize(25),(c=a.current)==null||c.resize(25))},[r]),e.jsxs(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Vt,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!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(Rn,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(os,{})})]}):e.jsx(os,{})})]})}function Vn(t){var de;s.useAIInteractionStore(z=>z.currentAIContext);const[a,n]=D.useState(""),[r,l]=D.useState(null),{authToken:d,tokenProps:i}=s.useSemaphorContext(),c=s.useEditorStore(z=>{var ee;return(ee=z==null?void 0:z.card)==null?void 0:ee.sql}),o=s.useEditorStore(z=>z.isDevMode),u=s.useEditorStore(z=>{var ee;return(ee=z==null?void 0:z.card)==null?void 0:ee.python}),{setCardPython:x,setCardSql:h,setRunSql:p,switchCardType:w,setQueryConfig:m}=s.useEditorActions(),f=s.useEditorStore(z=>z.currentAssitantScope)||[],b=s.useEditorStore(z=>z.userInputForAI),C=s.useEditorStore(z=>z.triggerAIRun),I=s.useEditorStore(z=>z.card),O=s.useEditorStore(z=>z.selectedDatabaseName),R=s.useEditorStore(z=>z.selectedTableName),y=s.useEditorStore(z=>z.selectedConnectionId),k=s.useEditorStore(z=>z.selectedSchemaName),g=s.useDashboardStore(z=>z.dashboard.aiScopeTables),{errorMessage:j,refetch:T,data:L}=s.useDashboardCardQuery(I),{setTriggerAIRun:N,setCurrentAssitantScope:v,setCardConfig:A}=s.useEditorActions(),{selectedDatamodelName:F,connectionType:E,selectedDatamodelId:M}=s.useEditorAside(),S=(de=s.useDashboardQuery().data)==null?void 0:de.assistantProfileId,{messages:P,setMessages:K,regenerate:H,error:V,sendMessage:G,status:U,addToolResult:$,stop:J,clearError:B}=s.useChat({transport:new s.DefaultChatTransport({api:`${i.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${d==null?void 0:d.accessToken}`}),body:()=>{const z=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:S,isDevMode:o,aiContext:z.currentAIContext,reasoningEffort:z.reasoningEffort,showReasoning:z.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:z,body:ee})=>({body:{...ee,messages:s.cleanupIncompleteMessages(z)}})}),onError:z=>{var ee;if(z.name==="AbortError"||(ee=z.message)!=null&&ee.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",z)},onToolCall:Q,onFinish({isAbort:z,isDisconnect:ee,isError:ce}){n(""),console.log(z?"[Editor Assistant] Stream aborted by user":ee?"[Editor Assistant] Stream disconnected (network error)":ce?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});D.useEffect(()=>{C&&b&&(G({role:"user",parts:[{type:"text",text:b}]}),N(!1))},[C,b,G,N]);async function Q({toolCall:z}){var ee,ce,ue,we,me,je,xe,be,ke,fe,Te,Ee,Ae,Ie,ve,ye;if(["createChartFromSql","createForecast"].includes(z.toolName)){const _=((ee=z.input)==null?void 0:ee.sql)??((ce=z.args)==null?void 0:ce.sql),ae=((ue=z.input)==null?void 0:ue.python)??((we=z.args)==null?void 0:we.python),re=((me=z.input)==null?void 0:me.chartType)??((je=z.args)==null?void 0:je.chartType);w(re),h(_),x(ae),p(!0),$({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(z.toolName==="getUserSql"){if(!c){$({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"error",message:"No SQL found"}});return}$({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",sql:c,python:u||""}})}else if(z.toolName==="generateQueryConfig"){n("Generating query config...");const _=((xe=z.input)==null?void 0:xe.chartType)??((be=z.args)==null?void 0:be.chartType),ae=((ke=z.input)==null?void 0:ke.queryConfig)??((fe=z.args)==null?void 0:fe.queryConfig);((Te=z.input)==null?void 0:Te.cardConfig)??((Ee=z.args)==null||Ee.cardConfig),w(_),A(ae),h(void 0),x(void 0);const re=await T();if((Ae=re==null?void 0:re.data)!=null&&Ae.error){$({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"error",queryConfig:ae,message:(Ie=re==null?void 0:re.data)==null?void 0:Ie.error.message}});return}if((ve=re==null?void 0:re.data)!=null&&ve.records){$({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",queryConfig:ae,message:"The data has been visualized"}});return}$({tool:z.toolName,toolCallId:z.toolCallId,output:{status:"success",queryConfig:ae,message:"The data has been visualized",records:(ye=re==null?void 0:re.data)==null?void 0:ye.records}})}else n("Analyzing...")}function Y(z){const ee=s.removeFromScopeArray(f,z);se(ee)}function se(z){const ee=s.sanitizeAIScope(z);v(ee),K(ce=>[...ce,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(ee)}`}]}])}function X(){const z={databaseName:O||"",schemaName:k||"",tableName:R||"",datamodelId:M||"",datamodelName:s.resolveDatamodelName(F),connectionId:y||"",connectionType:E||""},ee=s.dedup([...f,z]);se(ee)}function ne(){const z={databaseName:O||"",schemaName:k||"",tableName:R||"",datamodelName:s.resolveDatamodelName(F),connectionId:y||"",connectionType:E||"",datamodelId:M||""};if(!s.isInAiScopeArray([...g||[],...f],z)||f.length===0){const ce=s.dedup([...g||[],...f,z]).filter(ue=>ue.connectionId===z.connectionId);se(ce)}}const W=!["ready","error"].includes(U),ie=s.getErrorMessage(V);return{messages:P,setMessages:K,sendMessage:G,regenerate:H,isLoading:W,handleSetAIScope:ne,handleAddCurrentTableToScope:X,removeFromCurrentSelections:Y,currentAssitantScope:f,setCurrentAssitantScope:v,stop:J,status:U,toolStatus:a,llmUsage:r,onFinish:t,errorMessage:ie,clearError:B}}const Pn=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function ps({isFullscreen:t,onFullscreenChange:a,fullscreenContainer:n}){const r=D.useRef(null),[l,d]=D.useState(!1),[i,c]=D.useState(s.isDevEnv),[o,u]=D.useState(!1),[x,h]=D.useState(!1),[p,w]=D.useState(!1),m=t??p,f=s.useCurrentAIContext(),{setCurrentAIContext:b}=s.useAIActions(),{clearQueue:C}=s.useQueueActions(),{clearFileAttachments:I}=s.useFileActions(),O=s.useFileAttachments("editor"),R=s.useDashboardStore(_=>_.dashboard.aiContext),y=s.useEditorStore(_=>_.card.dataSource),k=s.useEditorStore(_=>_.actions.setCardSql),g=s.useEditorStore(_=>_.actions.setRunSql),j=s.useEditorStore(_=>_.showAIDialog),T=s.useDashboardStore(_=>_.handleOpenAssistantProfile),{setShowAIDialog:L,setCardPython:N}=s.useEditorActions(),{setDataSource:v}=s.useEditorActions(),{assistantProfile:A}=s.useAssistantProfile(),{messages:F,setMessages:E,sendMessage:M,isLoading:S,stop:P,status:K,llmUsage:H,errorMessage:V,clearError:G}=Vn(),[U,$]=D.useState(""),J=_=>{$(_.target.value)},B=_=>{_.preventDefault();const ae=U.trim();if(!ae&&O.length===0)return;const re=[];ae&&re.push({type:"text",text:ae}),O.forEach(Ne=>{Ne.data&&re.push({type:"file",mediaType:Ne.type,filename:Ne.name,url:`data:${Ne.type};base64,${Ne.data}`})}),M({role:"user",parts:re}),$(""),I("editor"),ee({force:!0})},{visibleMessages:Q,hasMoreMessages:Y,totalMessageCount:se,loadMoreMessages:X,resetMessageWindow:ne}=s.useMessageWindow(F,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:W,isAtBottom:ie,hasNewMessages:de,newMessageCount:z,scrollToBottom:ee,handleScroll:ce,resetNewMessageCount:ue}=s.useAutoScroll(Q,{threshold:50,behavior:"smooth",isStreaming:S});D.useEffect(()=>{var _;j&&((_=r.current)==null||_.focus(),b({selectedEntities:(y==null?void 0:y.selectedEntities)||[]}))},[j,y,b]),s.useAutoSubmitQueue({assistantType:"editor",status:K,isLoading:S,sendMessage:M});const{hasActiveTools:we}=s.useActiveToolStatus(F),me=D.useCallback(_=>{a==null||a(_),t===void 0&&w(_)},[t,a]);D.useEffect(()=>{if(!m)return;function _(ae){ae.key==="Escape"&&me(!1)}return window.addEventListener("keydown",_),()=>{window.removeEventListener("keydown",_)}},[m,me]);const je=D.useCallback(_=>{M({role:"user",parts:[{type:"text",text:_}]}),ee({force:!0})},[M,ee]),xe=D.useCallback(async()=>{const _=JSON.stringify(F??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(_),s.ue.success("Conversation copied")}catch(ae){console.error("Failed to copy conversation",ae),s.ue.error("Unable to copy conversation")}},[F]),be=D.useCallback(()=>{me(!m)},[m,me]);function ke(_,ae){ae==="sql"?(k(_),g(!0)):ae==="python"&&(N(_),g(!0))}function fe(){f.selectedEntities.length===0&&b({selectedEntities:(R==null?void 0:R.selectedEntities)||[]})}function Te(_){fe();const ae={role:"user",parts:[{type:"text",text:_.title+" "+_.subtitle}]};M(ae)}function Ee(_){fe(),M({role:"user",parts:[{type:"text",text:_}]})}function Ae(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:d,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:c,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:u,children:"System Message"})]})]})}function Ie(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const ve=(U==null?void 0:U.length)===0&&(F==null?void 0:F.filter(_=>_.role==="user").length)===0,ye=e.jsxs("div",{"data-role":"editor-assistant",className:s.cn("flex h-full w-full flex-col justify-between px-6 py-4",m&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Ie(),T&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:T,children:(A==null?void 0:A.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Ae(),i&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:xe,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:m?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:be,children:m?e.jsx(s.Minimize2,{className:"size-4"}):e.jsx(s.Maximize2,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{E([]),C("editor"),G(),ne()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{L(!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:ce,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:X,className:"text-xs",children:["Load ",Math.min(5,se-Q.length)," ","more messages (",se-Q.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:Q,showTools:i,handleRun:ke,showSystemMessage:o,onQuickReply:je,disableQuickReplies:S}),!we&&e.jsx(s.AssistantStatus,{status:K,errorMessage:V})]})}),j&&!ie&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{ee({force:!0}),ue()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),de&&z>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:z>9?"9+":z})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[ve&&!A&&e.jsx(s.Placeholders,{onClick:Te,placeholders:Pn}),e.jsx("div",{children:ve&&A&&e.jsx(s.SeedQuestions,{seedQuestions:A.seedQuestions||[],handleSeedQuestionClick:Ee})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:$,stop:P,input:U,handleInputChange:J,handleSubmit:_=>{fe(),B(_),ee({force:!0})},isLoading:S,status:K,assistantType:"editor",onFocus:()=>{}})]}),H&&l&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",H.inputTokens," prompt tokens, ",H.outputTokens," ","completion tokens, ",H.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(y==null?void 0:y.selectedEntities)||[],open:x,onOpenChange:h,dataSource:y||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return m&&n?nt.createPortal(e.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:e.jsx("div",{className:"flex h-full w-full",children:ye})}),n):ye}function zn({selectedChart:t,onChartChange:a}){const[n,r]=D.useState(!1),l=s.useEditorStore(c=>c.card),d=()=>{var o;if(t==="custom")return((o=l==null?void 0:l.customCardPreferences)==null?void 0:o.componentName)||"Custom Visual";const c=s.chartTypes.find(u=>u.id===t);return(c==null?void 0:c.label)||"Select chart type"},i=()=>{var o;if(t==="custom"){const u=(o=l==null?void 0:l.customCardPreferences)==null?void 0:o.componentName;if(u){const x=s.getAutoDetectedChartIcon(u);return x||e.jsx(s.ChartIcon,{chartName:u,isCustom:!0,className:"h-4 w-4"})}return e.jsx(s.Shapes,{className:"h-4 w-4"})}const c=s.chartTypes.find(u=>u.id===t);if(c){const u=c.icon;return e.jsx(u,{className:"h-4 w-4"})}return e.jsx(s.Shapes,{className:"h-4 w-4"})};return e.jsx("div",{children:e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[i(),e.jsx("span",{children:d()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[360px] p-3",align:"start",onOpenAutoFocus:c=>c.preventDefault(),children:e.jsx(Ds,{onChartSelect:c=>a(c),onClose:()=>r(!1)})})]})})}let $n=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce((a,n)=>(n&=63,n<36?a+=n.toString(36):n<62?a+=(n-26).toString(36).toUpperCase():n>62?a+="-":a+="_",a),"");const Be=[{id:"sum",label:"Sum",symbol:"+",description:"Add two metrics together",template:()=>"({field_0} + {field_1})",requiresTwoInputs:!0},{id:"difference",label:"Difference",symbol:"−",description:"Subtract one metric from another",template:()=>"({field_0} - {field_1})",requiresTwoInputs:!0},{id:"product",label:"Product (Multiplication)",symbol:"×",description:"Multiply two metrics",template:()=>"({field_0} * {field_1})",requiresTwoInputs:!0},{id:"ratio",label:"Ratio",symbol:"÷",description:"Divide one metric by another",template:()=>"({field_0} / NULLIF({field_1}, 0))",requiresTwoInputs:!0},{id:"change",label:"Change",symbol:"Δ",description:"Calculate percentage change from A to B",template:()=>"(({field_1} - {field_0}) / NULLIF({field_0}, 0))",requiresTwoInputs:!0},{id:"percentage",label:"Percentage",symbol:"%",description:"Calculate (A / B) × 100",template:()=>"(({field_0} / NULLIF({field_1}, 0)) * 100)",requiresTwoInputs:!0},{id:"scale",label:"Scale (Multiply by Factor)",symbol:"×n",description:"Multiply a metric by a constant factor",template:()=>"({field_0} * {constant})",requiresTwoInputs:!1},{id:"custom",label:"Custom Expression",symbol:"{}",description:"Drag fields to create custom expression with tokens",requiresTwoInputs:!1,allowsCustomExpression:!0}];function Kn(t,a,n,r,l,d,i,c,o){const u=Be.find(f=>f.id===a);if(!u)throw new Error(`Unknown operation: ${a}`);let x,h=[],p;if(a==="custom"){if(!(c!=null&&c.trim()))throw new Error("Custom expression is required");x=c.trim()}else if(a==="scale"){if(!n)throw new Error("Metric A is required for scale operation");if(o===void 0||o===0)throw new Error("Constant factor is required for scale operation");x=u.template().replace("{constant}",String(o)),h=[n],p=o}else{if(!n||!r)throw new Error("Metrics A and B are required for standard operations");x=u.template(),h=[n,r]}const w={operation:a,inputFields:h,...p!==void 0&&{constant:p}};return{id:i||`calc_${$n(10)}`,name:t.toLowerCase().replace(/\s+/g,"_"),label:t,alias:t.toLowerCase().replace(/\s+/g,"_"),qualifiedFieldName:t.toLowerCase().replace(/\s+/g,"_"),dataType:"number",role:"metric",aggregate:"SUM",expression:x,calculatedFormula:w,entityId:d,entityName:s.CALCULATED_FIELD_ENTITY_MARKER,entityType:"table",description:`Calculated field: ${t}`}}function fs(t){var r,l;const a=Be.find(d=>d.id===t.operation);if(!a)return"Unknown operation";if(t.operation==="custom")return"Custom expression";if(t.operation==="scale"){const d=((r=t.inputFields[0])==null?void 0:r.label)||((l=t.inputFields[0])==null?void 0:l.name)||"A",i=t.constant??1;return`${d} × ${i}`}return t.inputFields.map(d=>d.label||d.name).join(` ${a.symbol} `)}const Qe=({dataType:t})=>s.getFieldIconComponent(t);function Gn({aliasTemplate:t,onAliasTemplateChange:a}){var o;const[n,r]=D.useState(t),[l,d]=D.useState(!1),i=(o=s.useEditorStore(u=>{var x;return(x=u.card.config)==null?void 0:x.pivotByColumns}))==null?void 0:o[0],c=i?`e.g. Min Sales in {{${i.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input,{placeholder:c,value:l?n:t,onChange:u=>{r(u.target.value),d(!0)},onFocus:()=>d(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&l&&n!==t?(a(n),d(!1)):u.key==="Escape"&&(r(t),d(!1))},"aria-label":"Edit alias template"}),l&&n!==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:()=>{a(n),d(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),d(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function qn({valueAliases:t,onValueAliasesChange:a}){const[n,r]=D.useState(null),[l,d]=D.useState(""),[i,c]=D.useState(""),o=()=>{a({...t,"":""})},u=h=>{const p={...t};delete p[h],a(p)},x=h=>{const p={...t};delete p[h],p[l]=i,a(p),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([h,p],w)=>e.jsx("div",{className:"flex items-center gap-2",children:n===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input,{placeholder:"Value key",value:l,onChange:m=>d(m.target.value),className:"h-8 w-24 text-xs",onPointerDown:m=>m.stopPropagation(),onKeyDown:m=>{m.key==="Enter"?x(h):m.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input,{placeholder:"Alias label",value:i,onChange:m=>c(m.target.value),className:"h-8 w-24 text-xs",onPointerDown:m=>m.stopPropagation(),onKeyDown:m=>{m.key==="Enter"?x(h):m.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>x(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),d(h),c(p)},"aria-label":"Edit value alias key"}),e.jsx(s.Input,{placeholder:"Alias label",value:p,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),d(h),c(p)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(h),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},h+w)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:o,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Un({column:t}){const a=s.useEditorStore(o=>o.card.type),n=s.useEditorStore(o=>{var u,x;return(x=(u=o.card)==null?void 0:u.config)==null?void 0:x.metricColumns}),r=(n==null?void 0:n.map(o=>o.label))||[],l=r==null?void 0:r.find(o=>o===t.label||o===t.name),d=l?r.indexOf(l):-1;function i(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(Bs,{idx:d,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function c(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Vs,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&i(),["pie","doughnut"].includes(a)&&c()]})}function Hn({field:t,searchQuery:a="",limit:n=500}){const{authToken:r,tokenProps:l}=s.useSemaphorContext(),d=s.useEditorStore(u=>u.card),i=d==null?void 0:d.dataSource,c=["attribute-values",t.entityName,t.name,a,n],o=s.useQuery({queryKey:c,queryFn:async()=>{if(!(i!=null&&i.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:a?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:a}],groups:[]}:void 0,rowLimit:n},x={connection_id:i.connectionId,cardConfig:u,cardDataSource:i,cache_config:s.getCacheConfig({card:d})};console.log("requestBody",x);const h=await s.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",x);if(h!=null&&h.error)return console.error("Error fetching attribute values:",h.error),[];const p=t.name;return((h==null?void 0:h.records)||[]).map(m=>{const f=m[p]||m[t.alias||p]||m[t.label];return{id:f||"",value:f||"",label:String(f||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(i!=null&&i.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:o.data||[],isLoading:o.isLoading,isFetching:o.isFetching,isError:o.isError,error:o.error,refetch:o.refetch}}function _s({open:t,onOpenChange:a,availableFields:n,existingFilters:r,editingCondition:l,onSave:d}){var O,R;const i=!!l,[c,o]=D.useState(i?"values":"fields"),[u,x]=D.useState(""),[h,p]=D.useState({id:(l==null?void 0:l.id)||s.v4(),field:(l==null?void 0:l.field)||null,selectedValues:l?Array.isArray(l.value)?l.value:[l.value]:[]}),w=n.filter(y=>{var g;return i?!1:!((g=r==null?void 0:r.conditions)==null?void 0:g.some(j=>j.field.id===y.id))&&y.label.toLowerCase().includes(u.toLowerCase())}),m=y=>{p({...h,field:y}),o("values")},f=()=>{if(h.field&&h.selectedValues.length>0){const y={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let k;if(i){const g=((r==null?void 0:r.conditions)||[]).map(j=>j.id===l.id?y:j);k={...r,conditions:g}}else{const g=(r==null?void 0:r.conditions)||[];k={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...g,y],groups:[]}}d(k),a(!1)}},b=()=>{if(!i||!l)return;const y=((r==null?void 0:r.conditions)||[]).filter(k=>k.id!==l.id);if(y.length>0){const k={...r,conditions:y};d(k)}else d(void 0);a(!1)},C=y=>{p({...h,selectedValues:y})},I=()=>{i&&l?(p({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),o("values")):(p({id:s.v4(),field:null,selectedValues:[]}),o("fields")),x("")};return D.useEffect(()=>{t&&I()},[t,i,l]),e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:i?`Edit Filter: ${(O=h.field)==null?void 0:O.label}`:c==="fields"?"Select Field to Filter":`Select Values for ${(R=h.field)==null?void 0:R.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!i&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&c==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(y=>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:[y.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(y.value)?`${y.value.length} values`:String(y.value)})]},y.id))})]}),c==="fields"&&!i?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search fields...",value:u,onChange:y=>x(y.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:w.map(y=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>m(y),children:[e.jsx(Qe,{dataType:s.getDataType(y.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:y.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[y.entityName,".",y.name]})]})]},y.id))}),w.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),w.length===0&&!u&&n.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(Jn,{field:h.field,selectedValues:h.selectedValues,onValuesChange:C,onBack:i?void 0:()=>o("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:i?e.jsx(s.Button,{variant:"destructive",onClick:b,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:I,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:f,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Jn({field:t,selectedValues:a,onValuesChange:n,onBack:r}){const[l,d]=D.useState(""),{values:i,isLoading:c,isFetching:o}=Hn({field:t,searchQuery:l,limit:500}),u=l?i.filter(p=>String(p.value).toLowerCase().includes(l.toLowerCase())):i,x=p=>{const w=a.includes(p);n(w?a.filter(m=>m!==p):[...a,p])},h=()=>{a.length===u.length&&u.length>0?n([]):n(u.map(p=>p.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search values...",value:l,onChange:p=>d(p.target.value),className:"pl-10"})]}),c||o?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(s.Checkbox,{checked:a.length===u.length&&u.length>0,onCheckedChange:h}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",u.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:u.map(p=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>x(p.value),children:[e.jsx(s.Checkbox,{checked:a.includes(p.value),onCheckedChange:()=>x(p.value)}),e.jsx(Je,{className:"text-sm",children:p.label})]},p.id))})]})]})}function Qs({open:t,onOpenChange:a,availableMetrics:n,existingField:r,onSave:l,cardId:d}){const[i,c]=D.useState(""),[o,u]=D.useState("ratio"),[x,h]=D.useState(null),[p,w]=D.useState(null),[m,f]=D.useState(1),[b,C]=D.useState(""),[I,O]=D.useState({format:"number",decimalPlaces:2}),[R,y]=D.useState({}),k=Be.find(v=>v.id===o),g=n.find(v=>v.id===x),j=n.find(v=>v.id===p);D.useEffect(()=>{if(r&&t)if(c(r.label),r.calculatedFormula)if(u(r.calculatedFormula.operation),r.calculatedFormula.operation==="custom")C(r.expression||"");else if(r.calculatedFormula.operation==="scale"){const v=r.calculatedFormula.inputFields;if(v.length>=1){const A=n.find(F=>F.qualifiedFieldName===v[0].qualifiedFieldName);h((A==null?void 0:A.id)||null)}r.calculatedFormula.constant!==void 0&&f(r.calculatedFormula.constant)}else{const v=r.calculatedFormula.inputFields;if(v.length>=2){const A=n.find(E=>E.qualifiedFieldName===v[0].qualifiedFieldName),F=n.find(E=>E.qualifiedFieldName===v[1].qualifiedFieldName);h((A==null?void 0:A.id)||null),w((F==null?void 0:F.id)||null)}}else u("custom"),C(r.expression||"")},[r,t,n]);const T=()=>{const v={};return i.trim()||(v.name="Name is required"),o==="custom"?b.trim()||(v.customExpression="Custom expression is required"):o==="scale"?(x||(v.inputA="Please select a metric for input A"),(isNaN(m)||m===0)&&(v.constantFactor="Please enter a valid non-zero number"),r&&x===r.id&&(v.circular="Cannot reference the field being edited")):(x||(v.inputA="Please select a metric for input A"),p||(v.inputB="Please select a metric for input B"),x===p&&(v.inputs="Inputs A and B must be different metrics"),r&&(x===r.id||p===r.id)&&(v.circular="Cannot reference the field being edited")),y(v),Object.keys(v).length===0},L=()=>{if(!T())return;const v=Kn(i,o,g||null,j||null,I,d,r==null?void 0:r.id,o==="custom"?b:void 0,o==="scale"?m:void 0);l(v),N()},N=()=>{c(""),u("ratio"),h(null),w(null),f(1),C(""),y({}),a(!1)};return e.jsxs(s.Dialog,{modal:!1,open:t,onOpenChange:a,children:[t&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-w-md max-h-[90vh] overflow-y-auto",onInteractOutside:v=>{v.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsxs(s.DialogTitle,{children:[r?"Edit":"Create"," Calculated Metric"]}),e.jsx(s.DialogDescription,{children:"Combine existing metrics to create a new calculated field"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"name",children:"Name"}),e.jsx(s.Input$1,{id:"name",value:i,onChange:v=>c(v.target.value),placeholder:"e.g., Profit Margin",className:R.name?"border-red-500":""}),R.name&&e.jsx("p",{className:"text-xs text-red-500",children:R.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"operation",children:"Outcome is"}),e.jsxs(s.Select,{value:o,onValueChange:v=>{u(v),v==="custom"?(h(null),w(null)):o==="custom"&&C("")},children:[e.jsx(s.SelectTrigger,{id:"operation",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"CALCULATED"}),Be.map(v=>e.jsx(s.SelectItem,{value:v.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm",children:v.symbol}),e.jsx("span",{children:v.label})]})},v.id))]})})]}),k&&e.jsx("p",{className:"text-xs text-muted-foreground",children:k.description})]}),o==="custom"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"customExpression",children:"SQL Expression"}),e.jsx(s.Textarea,{id:"customExpression",value:b,onChange:v=>C(v.target.value),placeholder:"e.g., CASE WHEN revenue > 1000 THEN revenue - cost ELSE 0 END",className:s.cn("font-mono text-sm",R.customExpression&&"border-red-500"),rows:4}),R.customExpression&&e.jsx("p",{className:"text-xs text-red-500",children:R.customExpression}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Write a SQL expression using column names from your data source"})]}):e.jsxs("div",{className:"rounded-md bg-muted p-3 font-mono text-sm",children:["= ",x&&g?g.label:"A"," ",k==null?void 0:k.symbol," ",p&&j?j.label:"B"]}),o!=="custom"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"inputA",children:"Where"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded bg-muted font-mono text-sm font-medium",children:"A"}),e.jsxs(s.Select,{value:x||"",onValueChange:h,children:[e.jsx(s.SelectTrigger,{id:"inputA",className:R.inputA?"border-red-500":"",children:e.jsx(s.SelectValue,{placeholder:"+ Choose metric"})}),e.jsx(s.SelectContent,{children:n.filter(v=>!s.isCalculatedMetric(v)||v.id!==(r==null?void 0:r.id)).map(v=>e.jsxs(s.SelectItem,{value:v.id,children:[v.label||v.name,v.aggregate&&` (${v.aggregate})`]},v.id))})]})]}),R.inputA&&e.jsx("p",{className:"text-xs text-red-500",children:R.inputA})]}),o!=="custom"&&o!=="scale"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded bg-muted font-mono text-sm font-medium",children:"B"}),e.jsxs(s.Select,{value:p||"",onValueChange:w,children:[e.jsx(s.SelectTrigger,{id:"inputB",className:R.inputB?"border-red-500":"",children:e.jsx(s.SelectValue,{placeholder:"+ Choose metric"})}),e.jsx(s.SelectContent,{children:n.filter(v=>!s.isCalculatedMetric(v)||v.id!==(r==null?void 0:r.id)).map(v=>e.jsxs(s.SelectItem,{value:v.id,children:[v.label||v.name,v.aggregate&&` (${v.aggregate})`]},v.id))})]})]}),R.inputB&&e.jsx("p",{className:"text-xs text-red-500",children:R.inputB})]}),o==="scale"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"constantFactor",children:"Multiplication Factor"}),e.jsx(s.Input$1,{id:"constantFactor",type:"number",step:"any",value:m,onChange:v=>f(parseFloat(v.target.value)||0),placeholder:"e.g., 0.15",className:R.constantFactor?"border-red-500":""}),R.constantFactor&&e.jsx("p",{className:"text-xs text-red-500",children:R.constantFactor}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Enter the constant value to multiply the metric by (e.g., 0.15 for 15%)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"format",children:"Format"}),e.jsxs(s.Select,{value:I.format,onValueChange:v=>O({...I,format:v}),children:[e.jsx(s.SelectTrigger,{id:"format",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsxs(s.SelectItem,{value:"number",children:["Decimal (",I.decimalPlaces,")"]}),e.jsx(s.SelectItem,{value:"currency",children:"Currency"}),e.jsx(s.SelectItem,{value:"percent",children:"Percentage"})]})]})]}),(R.inputs||R.circular)&&e.jsxs(s.Alert,{variant:"destructive",children:[e.jsx(s.CircleAlert,{className:"h-4 w-4"}),e.jsx(s.AlertDescription,{children:R.inputs||R.circular})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:N,children:"Cancel"}),e.jsxs(s.Button,{onClick:L,children:[r?"Update":"Create"," Metric"]})]})]})]})}function _n({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:d=!1,cardType:i}){var We,Xe,Ze,es,ss;const{attributes:c,listeners:o,setNodeRef:u,transform:x,transition:h,isDragging:p}=s.useSortable({id:t.id}),w=s.useEditorStore(q=>q.card),{updateLabel:m,handleAggregationChange:f,handleDateFormatChange:b,handleGranularityChange:C,handleAliasTemplateChange:I,handleValueAliasesChange:O,removeField:R,handleKpiComparisonTypeChange:y,handleKpiShowTrendlineChange:k,handleKpiTrendlineWindowChange:g,handleKpiTrendlineGranularityChange:j,handleKpiTargetValueChange:T}=s.useFieldManagement(w),[L,N]=D.useState(!1),[v,A]=D.useState(!1),[F,E]=D.useState(!1),[M,S]=D.useState(null),[P,K]=D.useState(t.dateFormat||"YYYY-MM-DD"),[H,V]=D.useState(t.customFormat||""),[G,U]=D.useState(!!t.customFormat),[$,J]=D.useState(t.granularity||"day"),[B,Q]=D.useState(t.aliasTemplate||""),[Y,se]=D.useState(t.valueAliases||{}),[X,ne]=D.useState((We=t.parameters)==null?void 0:We.filters),W=q=>{q==="custom"?U(!0):(U(!1),K(q),a==="groupBy"&&b(n,q,""))},ie=q=>{V(q),a==="groupBy"&&b(n,"custom",q)},de=q=>{var le;J(q);const Z=(le=s.getDateFormatOptionsForGranularity(q)[0])==null?void 0:le.value;Z&&!G&&(K(Z),a==="groupBy"&&b(n,Z,"")),a==="groupBy"&&C(n,q)},z=q=>{Q(q),a==="metrics"&&I(n,q)},ee=q=>{se(q),a==="metrics"&&O(n,q)},ce=q=>{m(a,n,q)},ue=q=>{var te;if(ne(q),a==="metrics"){const Z={...t,parameters:{...t.parameters,filters:q}},le=[...((te=w.config)==null?void 0:te.metricColumns)||[]];le[n]=Z,s.useEditorStore.getState().actions.updateCardConfig(w.id,{metricColumns:le})}A(!1)},we=()=>{R(a,n)},me={transform:s.CSS.Transform.toString(x),transition:h},je=s.getDataType(t.dataType),xe=je==="date",be=i==="kpi",ke=s.getDateFormatOptionsForGranularity($),fe=a!=="pivotBy",Te=xe&&a==="groupBy"&&(!be||((Xe=w.config)==null?void 0:Xe.comparisonType)==="start_vs_end"),Ee=!be&&xe&&a==="groupBy",Ae=i&&s.COMPARISON_SUPPORTED_CHART_TYPES.includes(i)&&xe&&a==="groupBy",Ie=i==="kpi"&&xe&&a==="groupBy",ve=i&&i!=="pivotTable"&&a==="metrics"&&((Ze=w.config)==null?void 0:Ze.comparisonType)==="target",ye=a==="metrics",_=()=>{const q=t,te=a==="metrics"&&s.isCalculatedMetric(q);return e.jsxs("div",{className:"space-y-1",children:[!te&&e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:Z=>{Z.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),te&&q.calculatedFormula&&e.jsxs("div",{title:fs(q.calculatedFormula),onPointerDown:Z=>{Z.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:["= ",fs(q.calculatedFormula)]})]})},ae=()=>fe?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(pe,{value:t.label??"",onSave:ce,placeholder:"Display label...",type:"text"})]}):null,re=()=>Te?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:$,onValueChange:de,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(q=>e.jsx(s.SelectItem,{className:"text-xs",value:q,children:s.toTitleCase(q)},q))})]})]}):null,Ne=()=>Ee?e.jsxs(e.Fragment,{children:[re(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(s.Select,{value:G?"custom":P,onValueChange:W,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:ke.map(q=>e.jsx(s.SelectItem,{className:"text-xs",value:q.value,children:q.label},q.value))})]}),G&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:H,onChange:q=>{q.stopPropagation(),ie(q.target.value)},onClick:q=>q.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,Ws=()=>{var Z,le,Ce,Me,ge;const q=Ae,te=Ie;return!q&&!te?null:e.jsxs(e.Fragment,{children:[q&&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:((Z=w.config)==null?void 0:Z.comparisonType)||"none",onValueChange:y,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"start_vs_end",children:"Start vs End"})]})]})]}),te&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((le=w.config)==null?void 0:le.showTrendline)||!1,onCheckedChange:k})]})}),((Ce=w.config)==null?void 0:Ce.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input,{type:"number",min:"1",max:"365",value:((Me=w.config)==null?void 0:Me.trendlineWindow)||30,onChange:Fe=>{const tt=parseInt(Fe.target.value)||30;g(tt)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(s.Select,{value:((ge=w.config)==null?void 0:ge.trendlineGranularity)||"day",onValueChange:j,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]})]})},Xs=()=>{var q,te;return ve?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(pe,{value:((q=w.config)==null?void 0:q.targetValue)!==void 0&&((te=w.config)==null?void 0:te.targetValue)!==null?String(w.config.targetValue):"",onSave:Z=>{!isNaN(Number(Z))&&Z!==null?T(Number(Z)):T(0)},placeholder:"Enter target value...",type:"text"})]}):null},Zs=()=>{if(!ye)return null;const q=t,te=s.isCalculatedMetric(q);return e.jsxs(e.Fragment,{children:[te&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Formula"}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>E(!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:Z=>{f(n,Z)},disabled:te,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(X==null?void 0:X.conditions)&&X.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:X.conditions.map(Z=>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:()=>{S(Z),A(!0)},children:[e.jsxs("span",{className:"font-medium",children:[Z.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(Z.value)?Z.value.length===1?String(Z.value[0]):Z.value.length<=2?Z.value.join(", "):`${Z.value.slice(0,2).join(", ")} +${Z.value.length-2}`:String(Z.value)})}),Array.isArray(Z.value)&&Z.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 (",Z.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:Z.value.map((le,Ce)=>e.jsx("div",{children:String(le)},Ce))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:le=>{var Me;le.stopPropagation();const Ce=X.conditions.filter(ge=>ge.id!==Z.id);if(Ce.length>0){const ge={...X,conditions:Ce};ue(ge)}else if(ne(void 0),a==="metrics"){const ge={...t,parameters:{...t.parameters,filters:void 0}},Fe=[...((Me=w.config)==null?void 0:Me.metricColumns)||[]];Fe[n]=ge,s.useEditorStore.getState().actions.updateCardConfig(w.id,{metricColumns:Fe})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},Z.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{S(null),A(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Un,{column:t}),d&&e.jsxs(e.Fragment,{children:[e.jsx(Gn,{aliasTemplate:B,onAliasTemplateChange:z}),e.jsx(qn,{valueAliases:Y,onValueAliasesChange:ee})]})]})},{columns:et=[]}=s.useColumns(),st=(X==null?void 0:X.conditions)&&X.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:me,...c,...o,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${p?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(Qe,{dataType:je}),e.jsx(Je,{className:s.cn("w-[140px] flex-1 text-sm",st&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),a==="metrics"&&((es=X==null?void 0:X.conditions)==null?void 0:es.length)&&!L&&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:X.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:X.conditions.map(q=>e.jsxs("div",{children:[q.field.label,":"," ",Array.isArray(q.value)?`${q.value.length} values`:String(q.value)]},q.id))})})]})}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:q=>{q.stopPropagation(),N(!L)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${L?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:q=>{q.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const te=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",te),l(te)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:q=>{q.stopPropagation(),we()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),L&&e.jsxs("div",{className:"space-y-3",children:[_(),ae(),i==="kpi"&&re(),Ne(),Ws(),Xs(),Zs()]})]}),v&&e.jsx(_s,{open:v,onOpenChange:q=>{A(q),q||S(null)},availableFields:et,existingFilters:X,editingCondition:M,onSave:q=>{var te;if(q)ue(q);else if(ne(void 0),a==="metrics"){const Z={...t,parameters:{...t.parameters,filters:void 0}},le=[...((te=w.config)==null?void 0:te.metricColumns)||[]];le[n]=Z,s.useEditorStore.getState().actions.updateCardConfig(w.id,{metricColumns:le})}S(null)}}),F&&a==="metrics"&&e.jsx(Qs,{open:F,onOpenChange:E,availableMetrics:((ss=w.config)==null?void 0:ss.metricColumns)||[],existingField:t,onSave:q=>{var Z;const te=[...((Z=w.config)==null?void 0:Z.metricColumns)||[]];te[n]=q,s.useEditorStore.getState().actions.updateCardConfig(w.id,{metricColumns:te})},cardId:w.id})]})}function Qn({concept:t}){const a=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Pivot Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metric Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function Re({zone:t,fields:a,label:n,placeholder:r,shouldShow:l,hasPivotColumns:d=!1,activeField:i=null}){const{isOver:c,setNodeRef:o}=s.useDroppable({id:t}),{updateSortByColumn:u}=s.useEditorActions(),x=s.useEditorStore(b=>b.card),h=s.useEditorStore(b=>b.card.type),p=a.length>0,w=D.useMemo(()=>!i||!c?!0:s.validateFieldForChartType(i,t,h).isValid,[i,c,t,h]),m=(b,C)=>{var O;!((O=x.config)!=null&&O.sortByColumns)||x.config.sortByColumns.findIndex(R=>R.id===b)===-1||u(x.id,b,{direction:C})};if(t==="sortBy"&&l===!1)return null;const f=t!=="sortBy"&&h!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:n}),f&&e.jsx(Qn,{concept:t})]}),e.jsx("div",{ref:o,className:s.cn("rounded-lg border-2 border-dotted p-0.5 transition-all",{"border-green-500 bg-green-50 dark:bg-green-950":c&&w,"border-red-500 bg-red-50 dark:bg-red-950":c&&!w,"border-muted-foreground/30 bg-muted/40":!c&&p,"min-h-[60px] border-muted-foreground/20 bg-background":!c&&!p}),children:a.length===0?e.jsx("div",{className:"flex min-h-[60px] items-center justify-center text-sm text-muted-foreground/60",children:r}):e.jsx(s.SortableContext,{items:a.map(b=>b.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:a.map((b,C)=>{const O=b.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(_n,{field:b,zone:t,index:C,sortDirection:O,onSortDirectionChange:R=>m(b.id,R),hasPivotColumns:d,cardType:h})})},b.id)})})})})]})}const gs={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%
195
+ 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 Yn(){var p,w,m,f,b,C,I,O,R,y,k;const t=s.useEditorStore(g=>g.card),{setCardPreferences:a}=s.useEditorActions(),n=((p=t.config)==null?void 0:p.metricColumns)||[],r=((w=t.config)==null?void 0:w.groupByColumns)||[],l=n.length===2&&r.length===0,d=n.length>=1&&r.length>0;if(!(t.type==="kpi"&&(l||d)))return null;const c=((f=(m=t.preferences)==null?void 0:m.kpiVisualOptions)==null?void 0:f.metricComparison)||{},o=g=>{var T;const j={...t.preferences,kpiVisualOptions:{...(T=t.preferences)==null?void 0:T.kpiVisualOptions,metricComparison:{...c,...g}}};a(j)},u=d||c.enabled,x=((b=t.config)==null?void 0:b.comparisonType)||"none",h=x==="previous_period"||x==="same_period_last_year"||x==="start_vs_end";return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xt,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[l&&n.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:c.enabled||!1,onCheckedChange:g=>o({enabled:g,...g&&!c.calculationType?{calculationType:"difference"}:{}})})]}),u&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const g=c.calculationType||"difference",j=gs[g];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:j==null?void 0:j.label}),e.jsx("p",{children:j==null?void 0:j.description}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-[10px]",children:j==null?void 0:j.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",j==null?void 0:j.example]})]})})()})]})]}),e.jsxs(s.Select,{value:c.calculationType||"difference",onValueChange:g=>o({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(gs).map(([g,j])=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:j.label},g))})]})]}),e.jsx(_e,{formatOptions:c.formatOptions||{},onFormatOptionsChange:g=>o({formatOptions:g}),showTitle:!0,title:"COMPARISON FORMAT"}),(h||l)&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),l&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:c.position||"right",onValueChange:g=>o({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:c.showArrow!==!1,onCheckedChange:g=>o({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:c.showColor!==!1,onCheckedChange:g=>o({showColor:g})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),c.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Le,{value:((C=c.colorConfig)==null?void 0:C.increase)||"green",onChange:g=>o({colorConfig:{...c.colorConfig,increase:g}}),label:"Primary > Secondary"}),e.jsx(Le,{value:((I=c.colorConfig)==null?void 0:I.decrease)||"red",onChange:g=>o({colorConfig:{...c.colorConfig,decrease:g}}),label:"Primary < Secondary"}),e.jsx(Le,{value:((O=c.colorConfig)==null?void 0:O.noChange)||"neutral",onChange:g=>o({colorConfig:{...c.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:c.conditionalLabel||!1,onCheckedChange:g=>o({conditionalLabel:g})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),c.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input$1,{id:"label-increase",type:"text",value:((R=c.conditionalLabels)==null?void 0:R.increase)??"Increase",onChange:g=>o({conditionalLabels:{...c.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$1,{id:"label-decrease",type:"text",value:((y=c.conditionalLabels)==null?void 0:y.decrease)??"Decrease",onChange:g=>o({conditionalLabels:{...c.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$1,{id:"label-no-change",type:"text",value:((k=c.conditionalLabels)==null?void 0:k.noChange)??"No change",onChange:g=>o({conditionalLabels:{...c.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$1,{id:"label-name",type:"text",value:c.labelName??"",onChange:g=>o({labelName:g.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function Wn(){var l,d;const t=s.useEditorStore(i=>i.card),{setCardPreferences:a}=s.useEditorActions();if(t.type!=="kpi")return null;const n=((d=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:d.formatOptions)||{},r=i=>{var o;const c={...t.preferences,kpiVisualOptions:{...(o=t.preferences)==null?void 0:o.kpiVisualOptions,formatOptions:i}};a(c)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Hash,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(_e,{formatOptions:n,onFormatOptionsChange:r,showTitle:!1})})]})}function Xn(){var d;const t=s.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.type}),a=s.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.preferences}),{setCardPreferences:n}=s.useEditorActions();if(t!=="treemap")return null;const r=((d=a==null?void 0:a.chartOptions)==null?void 0:d.treemapColorMode)??"branch",l=i=>{const c={...a||{},chartOptions:{...a==null?void 0:a.chartOptions,treemapColorMode:i}};n(c)};return e.jsxs(s.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(s.RadioGroup,{value:r,onValueChange:i=>l(i??"branch"),className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:"treemap-color-branch",value:"branch"}),e.jsxs(s.Label,{htmlFor:"treemap-color-branch",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Shade by value (default)"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Keeps parent hue and adjusts lightness based on the node's share within the branch."})]})]}),e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:"treemap-color-category",value:"category"}),e.jsxs(s.Label,{htmlFor:"treemap-color-category",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Single color per category"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Applies the top-level color to all descendants without lightening/darkening."})]})]})]})})]})}function Zn({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r,activeField:l}){const[d,i]=D.useState(!1),c=s.useEditorStore(O=>{var R;return((R=O.card.customCardPreferences)==null?void 0:R.url)&&O.card.type==="custom"}),o=s.useEditorStore(O=>O.card),u=s.useEditorStore(O=>O.actions.updateCardConfig),x=o==null?void 0:o.type,h=t.length>0||n.length>0,p=x!=="kpi"||n.length<=2,w=x!=="kpi",m=x!=="kpi"&&h,f=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(x),b=w&&!f,C=()=>x==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},I=()=>x==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Columns",placeholder:"Drop fields to measure"};return e.jsxs(e.Fragment,{children:[e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.List,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[p&&e.jsx(Re,{zone:"groupBy",fields:t,label:C().label,placeholder:C().placeholder,activeField:l}),b&&e.jsx(Re,{zone:"pivotBy",fields:a,label:"Pivot Columns",placeholder:"Drop fields to pivot data",activeField:l}),e.jsx(Re,{zone:"metrics",fields:n,label:I().label,placeholder:I().placeholder,hasPivotColumns:a.length>0,activeField:l}),n.length>=1&&e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:()=>i(!0),className:"mt-2 w-full justify-start text-xs text-muted-foreground hover:text-foreground",children:[e.jsx(s.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),m&&e.jsx(Re,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics",activeField:l})]})]}),!c&&e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings2,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(Wn,{}),e.jsx(Yn,{}),e.jsx(zs,{}),e.jsx(Xn,{}),e.jsx(Us,{}),x==="bullet"&&e.jsx(qs,{}),x==="funnel"&&e.jsx(Js,{}),(x==="bubble"||x==="scatter")&&e.jsx(Hs,{}),e.jsx($s,{}),e.jsx(Ks,{}),e.jsx(Gs,{})]})})]}),c&&e.jsxs(s.AccordionItem,{value:"plugin",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vs,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsx(Fs,{})})]})]}),e.jsx(Qs,{open:d,onOpenChange:i,availableMetrics:n,onSave:O=>{u(o.id,{metricColumns:[...n,O]})},cardId:o.id})]})}function ea({onEditJoins:t}){const a=s.useEditorStore(c=>c.card),{autoJoinMetadata:n}=s.useDashboardCardQuery(a);if(!(n!=null&&n.autoResolved))return null;const{resolvedJoinPlan:r}=n,l=(r==null?void 0:r.joins)||[];if(l.length===0)return null;const d=c=>!c||c.length===0?"No conditions":c.map(o=>{var p,w,m,f;const u=`${(p=o.source)==null?void 0:p.entityName}.${(w=o.source)==null?void 0:w.name}`,x=`${(m=o.target)==null?void 0:m.entityName}.${(f=o.target)==null?void 0:f.name}`,h=o.operator||"=";return`${u} ${h} ${x}`}).join(" AND "),i=c=>!c.joinKeyGroups||c.joinKeyGroups.length===0?"No conditions defined":c.joinKeyGroups.length===1?d(c.joinKeyGroups[0].keys):c.joinKeyGroups.map((o,u)=>({id:u,operator:o.operator,condition:d(o.keys)}));return e.jsx(s.Card,{className:"border-blue-500/30 bg-blue-50/30 dark:bg-blue-950/20",children:e.jsxs("div",{className:"flex items-center justify-between p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(At,{className:"size-4 text-blue-600 dark:text-blue-400"}),e.jsx("h3",{className:"text-sm font-medium text-blue-900 dark:text-blue-100",children:"Auto-Resolved Joins"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"secondary",className:"cursor-help bg-blue-100 text-xs text-blue-700 dark:bg-blue-900 dark:text-blue-300",children:l.length})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:l.map((c,o)=>{const u=i(c),x=Array.isArray(u);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children:c.source.name}),e.jsx(s.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:c.target.name})]}),e.jsx(s.Badge,{variant:"outline",className:"border-green-500/40 bg-green-50/30 text-xs text-green-700 dark:bg-green-950/30 dark:text-green-300",children:c.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:x?u.map(h=>e.jsxs("div",{className:"rounded bg-muted/30 px-2 py-1",children:[e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:h.condition}),h.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",h.operator,")"]})]},h.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:u})})})]},c.id||o)})})})]})})]}),t&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:t,className:"h-7 gap-1 p-2 text-xs text-blue-700 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-100",children:e.jsx(s.SquarePen,{className:"size-3.5"})})]})})}const js={getItem(t){if(typeof window>"u")return null;try{return localStorage.getItem(t)}catch(a){return console.warn(`Failed to read from localStorage (${t}):`,a),null}},setItem(t,a){if(!(typeof window>"u"))try{localStorage.setItem(t,a)}catch(n){console.warn(`Failed to write to localStorage (${t}):`,n)}}};function sa({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:d,activeField:i}){var g,j;const[c,o]=D.useState(()=>js.getItem("chart-selector-expanded")==="true"),[u,x]=D.useState(!1),h=s.useEditorStore(T=>T.card),p=s.useEditorStore(T=>T.actions.updateCardConfig),w=n.length>0||r.length>0||l.length>0,{data:m,autoJoinMetadata:f}=s.useDashboardCardQuery(h),b=((g=h==null?void 0:h.config)==null?void 0:g.joinPlan)||(f!=null&&f.autoResolved?f.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),C=((j=h==null?void 0:h.dataSource)==null?void 0:j.selectedEntities)||[],I=T=>{p(h.id,{...h==null?void 0:h.config,joinPlan:T}),x(!1)},O=()=>{p(h.id,{...h==null?void 0:h.config,joinPlan:void 0}),x(!1)},R=()=>{x(!1)},y=()=>{x(!0)};D.useEffect(()=>{js.setItem("chart-selector-expanded",String(c))},[c]);const k=()=>{o(T=>!T)};return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col border-x border-border",children:[e.jsxs("div",{className:s.cn("px-6 pt-4",{"space-y-4":c}),children:[e.jsx("div",{className:s.cn("overflow-hidden transition-all duration-300 ease-in-out",c?"max-h-[200px] opacity-100":"max-h-0 opacity-0"),children:c&&e.jsx(zn,{selectedChart:t,onChartChange:a})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:"flex items-center justify-center",children:e.jsx(s.ChartQuickSelector,{selectedChart:t,onChartChange:a,isDropdownExpanded:c,onToggleDropdown:k})})]}),e.jsx("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:e.jsx("div",{className:s.cn("invisible flex gap-2",{visible:w||m}),children:e.jsx(qe.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(ea,{onEditJoins:y}),e.jsx(Zn,{groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:d,activeField:i})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]}),e.jsx(ws,{open:u,onOpenChange:x,joinPlan:b,availableDataSources:C,onSave:I,onCancel:R,onRemove:O,children:e.jsx("div",{})})]})}function ta({initialFilters:t,availableFields:a}={}){const[n,r]=D.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(y=>y.card.dataSource);const{columns:l,isLoading:d}=s.useColumns(),c=a||l||[],o={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=y=>{const k=g=>{if(g.id===y){const j=c[0]||o,T=s.getDataType(j.dataType)==="date";return{...g,conditions:[...g.conditions,{id:`condition-${Date.now()}`,field:j,operator:T?"between":"=",value:T?[]:""}]}}return{...g,groups:g.groups.map(k)}};r(k(n))},x=y=>{const k=g=>{if(g.id===y){const j=c[0]||o,T=s.getDataType(j.dataType)==="date";return{...g,groups:[...g.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:j,operator:T?"between":"=",value:T?[]:""}],groups:[]}]}}return{...g,groups:g.groups.map(k)}};r(k(n))},h=(y,k)=>{const g=j=>j.id===y?{...j,conditions:j.conditions.filter(T=>T.id!==k)}:{...j,groups:j.groups.map(g)};r(g(n))},p=(y,k)=>{const g=j=>j.id===y?{...j,groups:j.groups.filter(T=>T.id!==k)}:{...j,groups:j.groups.map(g)};r(g(n))},w=(y,k,g,j)=>{if(g==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const T=L=>L.id===y?{...L,conditions:L.conditions.map(N=>N.id===k?{...N,[g]:j}:N)}:{...L,groups:L.groups.map(T)};r(T(n))},m=(y,k,g)=>{const j=T=>T.id===y?{...T,conditions:T.conditions.map(L=>L.id===k?{...L,...g}:L)}:{...T,groups:T.groups.map(j)};r(j(n))},f=(y,k)=>{const g=j=>j.id===y?{...j,logicalOperator:k}:{...j,groups:j.groups.map(g)};r(g(n))},b=(y,k)=>{const g=j=>j.id===y?{...j,negate:k}:{...j,groups:j.groups.map(g)};r(g(n))},C=(y,k,g)=>{const j=T=>T.id===y?{...T,conditions:s.arrayMove(T.conditions,k,g)}:{...T,groups:T.groups.map(j)};r(j(n))},I=(y,k,g)=>{const j=T=>T.id===y?{...T,groups:s.arrayMove(T.groups,k,g)}:{...T,groups:T.groups.map(j)};r(j(n))},O=y=>{if(!y||y.conditions.length===0&&y.groups.length===0)return"-- No filters defined";const k=j=>{let T="";typeof j.field=="object"?T=j.field.entityName?`${j.field.entityName}.${j.field.name}`:j.field.name:T=String(j.field);const L=j.operator;let N=j.value;if(j.field.dataType==="string"&&!["in","not in"].includes(j.operator))typeof N=="string"?N=`'${N}'`:Array.isArray(N)&&(N=`'${N.join(", ")}'`);else if(j.field.dataType==="date"||j.field.dataType==="datetime"||j.field.dataType==="timestamp")if(j.operator==="between"&&Array.isArray(N)&&N.length===2){const v=N[0]?`'${N[0]}'`:"NULL",A=N[1]?`'${N[1]}'`:"NULL";return`${T} BETWEEN ${v} AND ${A}`}else if((j.operator==="in"||j.operator==="not in")&&Array.isArray(N)){const v=N.map(A=>A?`'${A}'`:"NULL").join(", ");return`${T} ${L} (${v})`}else typeof N=="string"||N instanceof Date?N=`'${N}'`:Array.isArray(N)&&N.length>0&&(N=`'${N[0]}'`);else if(["in","not in"].includes(j.operator)){let v=[];Array.isArray(N)?v=N.map(A=>typeof A=="string"?`'${A}'`:String(A)):typeof N=="string"?v=N.split(",").map(A=>{const F=A.trim();return j.field.dataType==="string"?`'${F}'`:F}):typeof N=="number"&&(v=[String(N)]),N=`(${v.join(", ")})`}switch(L){case"contains":return typeof N=="string"?`${T} LIKE '%${N.replace(/'/g,"")}'`:`${T} LIKE '%${String(N)}'`;case"startsWith":return typeof N=="string"?`${T} LIKE '${N.replace(/'/g,"")}%'`:`${T} LIKE '${String(N)}%'`;case"endsWith":return typeof N=="string"?`${T} LIKE '%${N.replace(/'/g,"")}'`:`${T} LIKE '%${String(N)}'`;case"isNull":return`${T} IS NULL`;case"isNotNull":return`${T} IS NOT NULL`;default:return`${T} ${L} ${N}`}},g=j=>{const T=j.conditions.map(k),L=j.groups.map(F=>g(F)),N=[...T,...L].filter(Boolean);if(N.length===0)return"";const v=N.join(` ${j.logicalOperator} `),A=N.length>1?`(${v})`:v;return j.negate?`NOT ${A}`:A};return g(y)},R=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:c,isLoading:d,addCondition:u,addGroup:x,removeCondition:h,removeGroup:p,updateCondition:w,updateConditionFields:m,updateGroupOperator:f,updateGroupNegate:b,reorderConditions:C,reorderGroups:I,generateSQLPreview:O,hasAnyFilters:R}}function na({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const aa=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function ra({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:l="w-64"}){const[d,i]=D.useState(!1),c=D.useMemo(()=>{const o={};return n.forEach(u=>{const x=aa(u);o[x]||(o[x]={}),o[x][u.entityId]||(o[x][u.entityId]=[]),o[x][u.entityId].push(u)}),o},[n]);return e.jsxs(s.Popover,{modal:!0,open:d,onOpenChange:i,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":d,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(na,{children:[t.entityName,".",t.name]})}):r,e.jsx(it,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(c).map(([o,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),o]}),children:Object.entries(u).map(([x,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[s.getEntityIcon(h[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:h[0].entityName})]}),h.map((p,w)=>e.jsxs(s.CommandItem,{value:p.id,onSelect:()=>{a(p),i(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===p.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:p.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:p.description&&e.jsx("span",{children:p.description})})]})]},p.id+w))]},`${o}-${x}`))},o))})]})})]})}function Ye(t){var f;const a=s.useEditorStore(b=>b.card),{authToken:n,tokenProps:r}=s.useSemaphorContext(),l=s.useEditorStore(b=>b.card.config),d=l==null?void 0:l.joinPlan,i={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},o={...i,role:"sortby",direction:"asc"},u={joinPlan:d,groupByColumns:[i],metricColumns:[c],sortByColumns:[o]},x=((f=a.dataSource)==null?void 0:f.connectionId)||a.connectionId,{data:h,isPending:p,error:w}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(n==null?void 0:n.accessToken)||"",{connection_id:x,cardConfig:u,cardDataSource:a.dataSource})}catch(b){console.log(t),console.error("error",b)}},enabled:!!x,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(b=>({label:b.value||"BLANK",value:b.value||"BLANK",count:(b==null?void 0:b.count)||0})),isPending:p,error:w}}function la({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:l}){const[d,i]=Ke.useState(!1),{filterValues:c}=Ye(t),o=x=>{n(a.filter(h=>h!==x))},u=x=>{a.includes(x)?n(a.filter(h=>h!==x)):n([...a,x])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:d,onOpenChange:i,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":d,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(x=>{const h=c.find(p=>p.value===x);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:p=>{p.key==="Enter"&&o(x)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.stopPropagation(),o(x)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},x)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:c.map((x,h)=>e.jsxs(s.CommandItem,{onSelect:()=>u(x.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(x.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:x.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x.count})]})]},x.value+h))})]})]})})]})})}function oa({field:t,value:a,onChange:n,placeholder:r="Select value...",className:l}){const{filterValues:d,isPending:i,error:c}=Ye(t);return i?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):c?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:d.map((o,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:o.value,children:o.label},o.value+u))})]})}function ia({value:t,operator:a,onChange:n,className:r}){var o;const{tokenProps:l}=s.useSemaphorContext(),d=(o=l==null?void 0:l.params)==null?void 0:o.timezone,i=D.useMemo(()=>{if(t){if(a==="between"||a==="not between"){if(Array.isArray(t)&&t.length===2){const u=t[0]?new Date(t[0]):void 0,x=t[1]?new Date(t[1]):void 0;if(u&&x)return{from:u,to:x}}}else if(a==="="||a==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(a===">"||a===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(a==="<"||a==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((a==="in"||a==="not in")&&Array.isArray(t)&&t.length>0){const u=new Date(t[0]),x=t.length>1?new Date(t[t.length-1]):u;if(!isNaN(u.getTime()))return{from:u,to:x}}}},[t,a]),c=u=>{if(!u){n(void 0);return}if(u.from&&u.to)n([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const x=new Date(u.from);x.setHours(23,59,59,999),n([u.from.toISOString(),x.toISOString()])}else if(u.to){const x=new Date(u.to);x.setHours(0,0,0,0),n([x.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:i,onChange:c,timezone:d,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const ca=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],da=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],ua=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],ma=["=","!=","isNull","isNotNull"],xa=["between","isNull","isNotNull"],ha={"=":"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 bs(t){return ha[t]||s.titleCase(t)}function pa(t){switch(t){case"string":return da;case"number":return ua;case"boolean":return ma;case"date":return xa;default:return ca}}function Ys({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:d,onUpdateGroupOperator:i,availableFields:c,updateConditionFields:o}){const{attributes:u,listeners:x,setNodeRef:h,transform:p,transition:w,isDragging:m}=s.useSortable({id:t.id}),{isPending:f,error:b}=Ye(t.field),C={transform:s.CSS.Transform.toString(p),transition:w};return e.jsxs("div",{ref:h,style:C,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${m?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...x,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:I=>i(n,I),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"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(ra,{value:t.field,onValueChange:I=>{const O=I,R=s.getDataType(O.dataType)==="date";o(n,t.id,{field:O,value:"",operator:R?"between":"="})},availableFields:c,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:I=>{I==="in"||I==="not in"?o(n,t.id,{operator:I,value:[]}):I==="isNull"||I==="isNotNull"?o(n,t.id,{operator:I,value:null}):o(n,t.id,{operator:I,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?bs(t.operator):""})}),e.jsx(s.SelectContent,{children:pa(s.getDataType(t.field.dataType)).map(I=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:I,children:bs(I)},I))})]}),t.operator==="isNull"||t.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?f?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):b?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(la,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(I=>typeof I=="string")?t.value:[],onChange:I=>o(n,t.id,{value:I}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input,{value:typeof t.value=="string"?t.value:"",onChange:I=>o(n,t.id,{value:I.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(oa,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:I=>o(n,t.id,{value:I}),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:I=>o(n,t.id,{value:I==="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(ia,{value:t.value,operator:t.operator,onChange:I=>o(n,t.id,{value:I}),className:"flex-1"}):e.jsx(s.Input,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:I=>l(n,t.id,"value",I.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>d(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function fa({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:d,onUpdateCondition:i,onUpdateField:c,onRemoveCondition:o,onReorderConditions:u,onReorderGroups:x,onAddCondition:h,onAddGroup:p,availableFields:w,renderFilterGroup:m,updateConditionFields:f}){const{attributes:b,listeners:C,setNodeRef:I,transform:O,transition:R,isDragging:y}=s.useSortable({id:t.id}),k={transform:s.CSS.Transform.toString(O),transition:R},g=T=>{const{active:L,over:N}=T;if(N&&L.id!==N.id){const v=t.conditions.findIndex(F=>F.id===L.id),A=t.conditions.findIndex(F=>F.id===N.id);v!==-1&&A!==-1&&u(t.id,v,A)}},j=T=>{const{active:L,over:N}=T;if(N&&L.id!==N.id&&n){const v=t.groups.findIndex(F=>F.id===L.id),A=t.groups.findIndex(F=>F.id===N.id);v!==-1&&A!==-1&&x(n,v,A)}};return e.jsxs("div",{ref:I,style:k,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${y?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...b,...C,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>l(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:T=>r(t.id,T),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:()=>n&&d(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>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:g,children:e.jsx(s.SortableContext,{items:t.conditions.map(T=>T.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((T,L)=>e.jsx(Ys,{condition:T,index:L,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:i,onUpdateField:c,onRemoveCondition:o,onUpdateGroupOperator:r,availableFields:w,updateConditionFields:f},T.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:j,children:e.jsx(s.SortableContext,{items:t.groups.map(T=>T.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(T=>m(T,a+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>p(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function ga({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:l}){const{currentFilters:d,availableFields:i,isLoading:c,addCondition:o,addGroup:u,removeCondition:x,removeGroup:h,updateCondition:p,updateConditionFields:w,updateGroupOperator:m,updateGroupNegate:f,reorderConditions:b,reorderGroups:C,generateSQLPreview:I,hasAnyFilters:O,setCurrentFilters:R}=ta({initialFilters:t,availableFields:a}),y=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[k,g]=D.useState(!1),j=(N,v,A)=>{const F=E=>E.id===N?{...E,conditions:E.conditions.map(M=>M.id===v?{...M,field:A,dataType:A.dataType}:M)}:{...E,groups:E.groups.map(F)};R(F(d))},T=(N,v=0,A)=>v===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:y,collisionDetection:s.closestCenter,onDragEnd:F=>{const{active:E,over:M}=F;if(M&&E.id!==M.id){const S=N.conditions.findIndex(K=>K.id===E.id),P=N.conditions.findIndex(K=>K.id===M.id);S!==-1&&P!==-1&&b(N.id,S,P)}},children:e.jsx(s.SortableContext,{items:N.conditions.map(F=>F.id),strategy:s.verticalListSortingStrategy,children:N.conditions.map((F,E)=>e.jsx(Ys,{condition:F,index:E,groupId:N.id,groupLogicalOperator:N.logicalOperator,onUpdateCondition:p,onUpdateField:j,onRemoveCondition:x,onUpdateGroupOperator:m,availableFields:i,updateConditionFields:w},F.id))})}),e.jsx(s.DndContext,{sensors:y,collisionDetection:s.closestCenter,onDragEnd:F=>{const{active:E,over:M}=F;if(M&&E.id!==M.id){const S=N.groups.findIndex(K=>K.id===E.id),P=N.groups.findIndex(K=>K.id===M.id);S!==-1&&P!==-1&&C(N.id,S,P)}},children:e.jsx(s.SortableContext,{items:N.groups.map(F=>F.id),strategy:s.verticalListSortingStrategy,children:N.groups.map(F=>T(F,v+1,N.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(N.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),k&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(N.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},N.id):e.jsx(fa,{group:N,depth:v,parentGroupId:A,onUpdateGroupOperator:m,onUpdateGroupNegate:f,onRemoveGroup:h,onUpdateCondition:p,onUpdateField:j,onRemoveCondition:x,onReorderConditions:b,onReorderGroups:C,onAddCondition:o,onAddGroup:u,availableFields:i,renderFilterGroup:T,updateConditionFields:w},N.id),L=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[c?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):T(d),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{id:"advanced-mode",checked:k,onCheckedChange:N=>g(N)}),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)"})]})}),O&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:I(d)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),L>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(O?d:null),children:"Apply Filters"})]})]})}function ja({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:l,isOpen:d,onOpenChange:i}){const c=u=>{n(t,u),i(!1)},o=()=>{r(t),i(!1)};return e.jsxs(s.Dialog,{modal:!1,open:d,onOpenChange:i,children:[d&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(ga,{filters:a,availableFields:l,onSave:c,onCancel:()=>i(!1),onClearAll:o})]})]})}function ba({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var b,C;const[l,d]=D.useState(null),i=s.useEditorStore(I=>I.card),c=s.useEditorStore(I=>I.actions.updateCardConfig),o=(b=i==null?void 0:i.config)==null?void 0:b.joinPlan,u=(C=i==null?void 0:i.dataSource)==null?void 0:C.semanticDomainId,{data:x}=s.useJoinabilityMap(u),h=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],p=D.useCallback(I=>I.startsWith("card-")?null:I.startsWith("source-")||a.find(O=>O.id===I)?"source":n("groupBy").find(O=>O.id===I)?"groupBy":n("metrics").find(O=>O.id===I)?"metrics":n("pivotBy").find(O=>O.id===I)?"pivotBy":n("sortBy").find(O=>O.id===I)?"sortBy":null,[a,n]),w=D.useCallback(I=>{d(I.active.id)},[]),m=D.useCallback(I=>{var T;const{active:O,over:R}=I;if(!R||!t){d(null);return}const y=O.id,k=R.id,g=p(y),j=p(k)||k;if(j==="sortBy"){if(g==="source"){const L=a.find(v=>v.id===y);if(!L){d(null);return}if(!(n("groupBy").some(v=>v.name===L.name&&v.qualifiedEntityName===L.qualifiedEntityName)||n("metrics").some(v=>v.name===L.name&&v.qualifiedEntityName===L.qualifiedEntityName))){d(null);return}}else if(g==="pivotBy"){d(null);return}else if(g!=="groupBy"&&g!=="metrics"&&g!=="sortBy"){d(null);return}}if(g==="source"&&j==="sortBy"){const L=[...a].find(F=>F.id===y);if(!L){d(null);return}const N=n("sortBy");if(s.fieldAlreadyExists(L,N)){d(null);return}const v=s.validateFieldForChartType(L,"sortBy",i.type);if(!v.isValid){s.ue.error("Invalid Field Type",{description:v.reason,position:"top-center",duration:3e3}),d(null);return}const A=s.getNewField(L,"sortBy",N);d(null),r("sortBy",[...N,A]);return}if(g==="source"&&j!=="source"&&j!=="sortBy"){const L=[...a].find(M=>M.id===y);if(!L){d(null);return}const N=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(N.length>0){const M=N[0].qualifiedEntityName;if(!M){d(null);return}if(M!==L.qualifiedEntityName&&L.qualifiedEntityName)if(u&&(x!=null&&x.joinabilityMap)){if(s.calculateFieldState(L,{joinabilityMap:x.joinabilityMap,selectedFields:N,baseEntityName:(T=o==null?void 0:o.baseEntity)==null?void 0:T.name}).state==="unreachable"){s.showJoinRequiredNotification(),d(null);return}}else{if(!o){s.showJoinRequiredNotification(),d(null);return}if(!s.areEntitiesJoined(M,L.qualifiedEntityName,o)){s.showJoinRequiredNotification(),d(null);return}}}const v=n(j);if(s.fieldAlreadyExists(L,v)){d(null);return}const A=s.validateFieldForChartType(L,j,i.type);if(!A.isValid){s.ue.error("Invalid Field Type",{description:A.reason,position:"top-center",duration:3e3}),d(null);return}const F=s.getNewField(L,j,v),E=[...v,F];d(null),r(j,E),j==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(i.type,i.config,c,t,E);return}if(g&&j&&g!=="source"&&j!=="source"&&g!==j){const L=n(g),N=n(j),v=L.find(S=>S.id===y);if(!v){d(null);return}const A=s.validateFieldForChartType(v,j,i.type);if(!A.isValid){s.ue.error("Invalid Field Type",{description:A.reason,position:"top-center",duration:3e3}),d(null);return}const F=s.getNewField(v,j,N);if(d(null),j==="sortBy"){s.fieldAlreadyExists(v,N)||r(j,[...N,F]);return}const E=L.filter(S=>S.id!==y),M=[...N,F];r(g,E),r(j,M),j==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(i.type,i.config,c,t,M);return}if(g&&j&&g===j&&g!=="source"){const L=n(g),N=L.findIndex(A=>A.id===y),v=L.findIndex(A=>A.id===k);if(N!==v){const A=s.arrayMove(L,N,v);r(g,A)}}d(null)},[t,a,n,r,p,o,u,x,i.type,c,i.config]),f=l?h.find(I=>I.id===l):null;return{activeId:l,activeField:f,handleDragStart:w,handleDragEnd:m}}function va({activeView:t,onViewChange:a,splitViewEnabled:n}){const r=s.useEditorStore(o=>o.card),{config:l}=D.useContext(s.SemaphorContext).tokenProps,d=(l==null?void 0:l.showInfoTab)!==!1,{errorMessage:i}=s.useDashboardCardQuery(r),c=()=>n?!1:!["table","pivotTable","aggregateTable"].includes(r.type);return e.jsx(s.Tabs,{value:t,onValueChange:o=>a(o),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),c()&&e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),r.type!=="kpi"&&d&&e.jsx(s.TabsTrigger,{value:"info",className:s.cn("rounded-md transition data-[state=active]:bg-muted",i&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:i?"Error":"Info"})]})})}const ya=[{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 Na(){var o,u;const t=s.useEditorStore(x=>x.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=D.useState(!1),[l,d]=D.useState(""),i=x=>{if(x==="custom"){r(!0);return}r(!1),a(t.id,parseInt(x))},c=x=>{const h=x.target.value;d(h),h&&!isNaN(parseInt(h))&&a(t.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input$1,{type:"number",value:l,onChange:c,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(o=t.config)==null?void 0:o.rowLimit)==null?void 0:u.toString())||"100",onValueChange:i,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:ya.map(x=>e.jsx(s.SelectItem,{value:x.value,children:x.label},x.value))})]})})}function Ca({card:t,queryData:a,isLoading:n,isFetching:r,pagination:l,onPaginationChange:d,onSortChange:i,sortState:c,splitViewEnabled:o}){const u=D.useMemo(()=>(a==null?void 0:a.records)||[],[a==null?void 0:a.records]);return!o||["table","pivotTable","aggregateTable"].includes(t.type)?e.jsx(Ge,{}):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(Ge,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:(a==null?void 0:a.records)&&e.jsx(s.TableVisual,{card:t,data:u,paginationMetadata:l,onPaginationChange:d,isLoading:n||r,onSortChange:i,sortState:c})})})]})}const Sa="semaphor-split-view-enabled";function wa(){return ks(Sa,!0)}function ka({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onFiltersClick:l,activeCard:d,columns:i,columnsLoading:c,columnsError:o}){var se,X,ne;const u=s.useEditorStore(W=>W.card),x=s.useDashboardStore(W=>W.filterValues),h=s.useDashboardStore(W=>W.selectedSheetId),p=s.useDashboardStore(W=>W.inlineFilterValuesMap[(d==null?void 0:d.id)||""]),{updateCardConfig:w,setCard:m,updateCardInFrame:f,setShowAIDialog:b}=s.useEditorActions(),C=s.useEditorStore(W=>W.showAIDialog),I=s.useDashboardStore(W=>W.isVisualEditing),[O,R]=D.useState(!1),[y,k]=D.useState(!1),[g,j]=D.useState(null),{config:T}=D.useContext(s.SemaphorContext).tokenProps,L=(T==null?void 0:T.showInfoTab)!==!1,[N,v]=wa();s.useEditorStore(W=>{var ie;return((ie=W.card.customCardPreferences)==null?void 0:ie.url)&&W.card.type==="custom"});const{data:A,errorMessage:F,isLoading:E,isFetching:M,errorSql:S,pagination:P,refetch:K,comparisonMetadata:H}=s.useDashboardCardQuery(d),V=D.useMemo(()=>(A==null?void 0:A.records)||[],[A==null?void 0:A.records]),[G,U]=D.useState(!1);D.useEffect(()=>{M||U(!1)},[M]);const $=()=>{const W=!N;W&&t==="table"&&a("chart"),v(W)},J=(W,ie)=>{const de={...d,paginationConfig:{page:W+1,pageSize:ie}};m(de),f(de)};function B(){return e.jsxs("div",{className:"relative border-b border-border bg-background p-4",children:[e.jsx("button",{onClick:r,className:"absolute right-4 top-4 rounded-md p-1 hover:bg-muted","aria-label":"Close Debug Panel",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsxs("div",{className:"space-y-4 pr-8",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(u.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(x||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(d.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",i.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:c?"Loading...":o?"Error loading columns":JSON.stringify(i.slice(0,5),null,2)})]})]})]})}const Q=W=>{if(!u.config)return;const ie=s.sortStateToSortByColumns(W,u.config.metricColumns,u.config.groupByColumns);w(u.id,{...u.config,sortByColumns:ie})},Y=D.useMemo(()=>{var W;return s.sortByColumnsToSortState((W=u.config)==null?void 0:W.sortByColumns)},[(se=u.config)==null?void 0:se.sortByColumns]);return e.jsxs("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":C&&I}),children:[n&&B(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&C&&e.jsx(Ms,{variant:"outline"}),e.jsx(va,{activeView:t,onViewChange:a,splitViewEnabled:N}),e.jsx(s.FilterInfo,{cardId:d.id,cardFilters:(X=d.config)==null?void 0:X.filters,cardFilterCount:s.getFilterCount(((ne=d.config)==null?void 0:ne.filters)||null),onFiltersClick:l,inlineFilters:d.inlineFilters,inlineFilterValues:p,sheetId:h||""}),H&&e.jsx(s.ComparisonMetadataBadge,{metadata:H,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Na,{})}),C&&e.jsx(qe.EditorClearButton,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:E||M,onClick:()=>{U(!0),K()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":G})})}),t==="chart"&&e.jsx(s.IconButton,{tooltip:N?"Hide Results Table":"Show Results Table",onClick:$,children:N?e.jsx(mt,{className:"size-4"}):e.jsx(kt,{className:"size-4"})}),t==="chart"&&e.jsx(e.Fragment,{children:e.jsx(Ls,{})}),!C&&e.jsx(s.IconButton,{onClick:()=>b(!C),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":N&&!["table","pivotTable","aggregateTable"].includes(d.type)}),children:e.jsx(Ca,{card:d,queryData:A,isLoading:E,isFetching:M,pagination:P,onPaginationChange:J,onSortChange:Q,sortState:Y,splitViewEnabled:N})}),t==="table"&&(A==null?void 0:A.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:d,data:V,paginationMetadata:P,onPaginationChange:J,isLoading:E||M,onSortChange:Q,sortState:Y})}),t==="info"&&L&&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:F?e.jsx(He,{error:F,errorSql:S,onSendFeedback:()=>{const W=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:u.config,dataSource:d.dataSource,dashboardFilters:x,errorMessage:F,errorSql:S,generatedSql:A==null?void 0:A.sql});j(W),k(!0)},onOpenInEditor:()=>{b(!0),setTimeout(()=>{const W=s.useEditorStore.getState().actions;W.setIsDevMode(!0),W.setCardSql(S||""),setTimeout(()=>{W.setRunSql(!0)},100)},100)}}):e.jsx(Es,{sql:A==null?void 0:A.sql,error:F,errorSql:S})})})]}),g&&e.jsx(s.FeedbackDialog,{open:y,onOpenChange:k,feedbackData:g})]})]})}function Ta({activeField:t}){const[a,n]=D.useState(!0);return D.useEffect(()=>{t&&n(!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 ${a?"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(Qe,{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 Ea=()=>{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 a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Aa({column:t,isSelected:a,onSelect:n,availableFields:r,width:l,onWidthChange:d}){var K,H,V;const i=s.useEditorStore(G=>G.card),{updateCardConfig:c,removeGroupByColumn:o,removeMetricColumn:u,updateFilters:x}=s.useEditorActions(),[h,p]=D.useState(!1),[w,m]=D.useState(!1),f=D.useRef(null),b=D.useCallback(G=>{G.preventDefault(),G.stopPropagation(),m(!0),f.current={startX:G.clientX,startWidth:l||150};const U=J=>{if(!f.current)return;const B=J.clientX-f.current.startX,Q=Math.max(80,f.current.startWidth+B);d==null||d(t.id,Q)},$=()=>{m(!1),f.current=null,document.removeEventListener("mousemove",U),document.removeEventListener("mouseup",$)};document.addEventListener("mousemove",U),document.addEventListener("mouseup",$)},[l,t.id,d]),C=(K=i==null?void 0:i.config)==null?void 0:K.filters,I=(H=C==null?void 0:C.conditions)==null?void 0:H.some(G=>G.field.name===t.name&&G.field.qualifiedEntityName===t.qualifiedEntityName),O=G=>{G?x(i.id,G):c(i.id,{filters:void 0})},{attributes:R,listeners:y,setNodeRef:k,transform:g,transition:j,isDragging:T}=s.useSortable({id:t.id}),L={transform:s.CSS.Transform.toString(g),transition:j},N=s.getDataType(t.dataType),v=Ia(N),A=()=>{var $;const G=(($=i==null?void 0:i.config)==null?void 0:$.sortByColumns)||[],U=G.findIndex(J=>J.name===t.name);if(U!==-1){const J=[...G];J[U]={...J[U],direction:"asc"},c(i.id,{sortByColumns:J})}else c(i.id,{sortByColumns:[...G,{...t,id:`sort-${t.id}`,role:"sortby",direction:"asc"}]})},F=()=>{var $;const G=(($=i==null?void 0:i.config)==null?void 0:$.sortByColumns)||[],U=G.findIndex(J=>J.name===t.name);if(U!==-1){const J=[...G];J[U]={...J[U],direction:"desc"},c(i.id,{sortByColumns:J})}else c(i.id,{sortByColumns:[...G,{...t,id:`sort-${t.id}`,role:"sortby",direction:"desc"}]})},E=()=>{var $;const G=(($=i==null?void 0:i.config)==null?void 0:$.groupByColumns)||[];if(!G.some(J=>J.name===t.name)){const J={...t,id:`groupby-${t.id}-${Date.now()}`,role:"groupby"};c(i.id,{groupByColumns:[...G,J]})}},M=G=>{var J;const U=((J=i==null?void 0:i.config)==null?void 0:J.metricColumns)||[];if(!U.some(B=>B.name===t.name&&B.aggregate===G)){const B={...t,id:`metric-${t.id}-${G}-${Date.now()}`,label:`${G} of ${t.label||t.name}`,role:"metric",aggregate:G};c(i.id,{metricColumns:[...U,B]})}},S=()=>{t.role==="groupby"?o(i.id,t.id):t.role==="metric"&&u(i.id,t.id)},P={...L,width:l?`${l}px`:void 0,minWidth:l?`${l}px`:"120px"};return e.jsxs("th",{ref:k,style:P,className:s.cn("group relative border-r border-border bg-background px-1 py-0",T&&"opacity-50",a&&"bg-primary/10",w&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...R,...y,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:n,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",a&&"bg-primary/10"),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(v,{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,")"]}),I&&e.jsx(s.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(s.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(s.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(s.DropdownMenuItem,{onClick:()=>p(!0),children:[e.jsx(s.Filter,{className:s.cn("mr-2 h-4 w-4",I&&"text-primary")}),I?"Edit Filter":"Filter"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:A,children:[e.jsx(lt,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(s.DropdownMenuItem,{onClick:F,children:[e.jsx(rt,{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:()=>M("SUM"),children:"Sum"}),e.jsx(s.DropdownMenuItem,{onClick:()=>M("AVG"),children:"Average"}),e.jsx(s.DropdownMenuItem,{onClick:()=>M("COUNT"),children:"Count"}),e.jsx(s.DropdownMenuItem,{onClick:()=>M("DISTINCT"),children:"Count Distinct"}),e.jsx(s.DropdownMenuItem,{onClick:()=>M("MIN"),children:"Min"}),e.jsx(s.DropdownMenuItem,{onClick:()=>M("MAX"),children:"Max"})]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:E,children:[e.jsx(Ue,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(s.DropdownMenuItem,{disabled:!0,children:[e.jsx(Ns,{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:b,className:s.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",w&&"bg-primary")}),e.jsx(_s,{open:h,onOpenChange:p,availableFields:r.length>0?r:[t],existingFilters:C,editingCondition:I?(V=C==null?void 0:C.conditions)==null?void 0:V.find(G=>G.field.name===t.name&&G.field.qualifiedEntityName===t.qualifiedEntityName):void 0,onSave:O})]})}function Ia(t){switch(t){case"number":return s.Hash;case"date":return s.Calendar;case"string":default:return s.Type}}function Da({selectedColumn:t,onColumnSelect:a,isLoading:n=!1,sourceFields:r=[]}){var j,T,L,N;const l=s.useEditorStore(v=>v.card),{updateCardConfig:d}=s.useEditorActions(),[i,c]=D.useState(null),[o,u]=D.useState({}),[x,h]=D.useState(!1),p=D.useMemo(()=>{var F,E;const v=((F=l==null?void 0:l.config)==null?void 0:F.groupByColumns)||[],A=((E=l==null?void 0:l.config)==null?void 0:E.metricColumns)||[];return[...v,...A]},[(j=l==null?void 0:l.config)==null?void 0:j.groupByColumns,(T=l==null?void 0:l.config)==null?void 0:T.metricColumns]),w=D.useMemo(()=>{const v=new Set(p.map(A=>`${A.qualifiedEntityName}.${A.name}`));return r.filter(A=>!v.has(`${A.qualifiedEntityName}.${A.name}`))},[r,p]),{data:m,isLoading:f}=s.useDashboardCardQuery(l),b=(m==null?void 0:m.records)||[],C=D.useCallback((v,A)=>{u(F=>({...F,[v]:A}))},[]),I=D.useCallback(v=>{var M,S;const A=s.getDataType(v.dataType),F=((M=l==null?void 0:l.config)==null?void 0:M.groupByColumns)||[],E=((S=l==null?void 0:l.config)==null?void 0:S.metricColumns)||[];if(A==="number"){const P={...v,id:`metric-${v.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};d(l.id,{metricColumns:[...E,P]})}else{const P={...v,id:`groupby-${v.id}-${Date.now()}`,role:"groupby"};d(l.id,{groupByColumns:[...F,P]})}h(!1)},[(L=l==null?void 0:l.config)==null?void 0:L.groupByColumns,(N=l==null?void 0:l.config)==null?void 0:N.metricColumns,l.id,d]),O=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),R=v=>{c(v.active.id)},y=v=>{const{active:A,over:F}=v;if(c(null),!F||A.id===F.id)return;const E=p.findIndex(S=>S.id===A.id),M=p.findIndex(S=>S.id===F.id);if(E!==-1&&M!==-1){const S=s.arrayMove(p,E,M),P=S.filter(H=>H.role==="groupby"),K=S.filter(H=>H.role==="metric");d(l.id,{groupByColumns:P,metricColumns:K})}},k=i?p.find(v=>v.id===i):null,g=v=>{let A="";for(;v>=0;)A=String.fromCharCode(v%26+65)+A,v=Math.floor(v/26)-1;return A};return n?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):p.length===0?e.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-4 p-8 text-center",children:e.jsxs("div",{className:"rounded-lg border-2 border-dashed border-muted-foreground/25 p-12",children:[e.jsx("h3",{className:"text-lg font-medium text-muted-foreground",children:"No columns selected"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground/75",children:"Select columns from the panel on the right to build your table"})]})}):e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(s.DndContext,{sensors:O,collisionDetection:s.closestCenter,onDragStart:R,onDragEnd:y,children:[e.jsxs("table",{className:"w-full border-collapse",children:[e.jsxs("thead",{children:[e.jsxs("tr",{className:"border-b border-border bg-muted/30",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-1 text-center text-xs font-medium text-muted-foreground"}),e.jsx(s.SortableContext,{items:p.map(v=>v.id),strategy:s.horizontalListSortingStrategy,children:p.map((v,A)=>e.jsx("th",{style:{width:o[v.id]?`${o[v.id]}px`:void 0,minWidth:o[v.id]?`${o[v.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:g(A)},`letter-${v.id}`))}),e.jsx("th",{className:"w-10 border-r border-border bg-muted/30 px-2 py-1"})]}),e.jsxs("tr",{className:"border-b-2 border-border bg-background",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-2 text-center text-xs font-medium text-muted-foreground",children:"#"}),e.jsx(s.SortableContext,{items:p.map(v=>v.id),strategy:s.horizontalListSortingStrategy,children:p.map(v=>e.jsx(Aa,{column:v,isSelected:(t==null?void 0:t.id)===v.id,onSelect:()=>a(v),availableFields:r,width:o[v.id],onWidthChange:C},v.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(s.Popover,{open:x,onOpenChange:h,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Add column",children:e.jsx(s.Plus,{className:"h-4 w-4"})})}),e.jsx(s.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search columns..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No columns available."}),e.jsx(s.CommandGroup,{heading:"Available Columns",children:w.map(v=>{const A=s.getDataType(v.dataType),F=A==="number"?s.Hash:A==="date"?s.Calendar:s.Type;return e.jsxs(s.CommandItem,{value:v.label||v.name,onSelect:()=>I(v),children:[e.jsx(F,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm",children:v.label||v.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:v.entityName})]})]},v.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:f?e.jsx("tr",{children:e.jsx("td",{colSpan:p.length+2,className:"h-32 text-center",children:e.jsx(s.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):b.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:p.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):b.slice(0,100).map((v,A)=>e.jsxs("tr",{className:s.cn("border-b border-border transition-colors hover:bg-muted/50",A%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:A+1}),p.map(F=>{const E=v[F.name]??v[F.label??""];return e.jsx("td",{style:{width:o[F.id]?`${o[F.id]}px`:void 0,minWidth:o[F.id]?`${o[F.id]}px`:"120px"},className:s.cn("border-r border-border px-3 py-2 text-sm",(t==null?void 0:t.id)===F.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:Ma(E,F)})},`${A}-${F.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},A))})]}),e.jsx(s.DragOverlay,{children:k&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:k.label||k.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(b.length,100)," of ",b.length," rows"]}),e.jsxs("span",{children:[p.length," columns"]})]})]})}function Ma(t,a){if(t==null)return"—";if(typeof t=="number")return a.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 n=new Date(t);if(!isNaN(n.getTime()))return n.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(t)}function La({entityGroups:t,isLoading:a=!1}){var O,R;const n=s.useEditorStore(y=>y.card),{updateCardConfig:r,removeGroupByColumn:l,removeMetricColumn:d}=s.useEditorActions(),[i,c]=D.useState(!0),[o,u]=D.useState(""),[x,h]=D.useState(new Set),p=((O=n==null?void 0:n.config)==null?void 0:O.groupByColumns)||[],w=((R=n==null?void 0:n.config)==null?void 0:R.metricColumns)||[],m=y=>{const k=new Set(x);k.has(y)?k.delete(y):k.add(y),h(k)},f=y=>p.some(k=>k.name===y.name&&k.qualifiedEntityName===y.qualifiedEntityName)||w.some(k=>k.name===y.name&&k.qualifiedEntityName===y.qualifiedEntityName),b=(y,k)=>{if(k)if(s.getDataType(y.dataType)==="number"){const j={...y,id:`metric-${y.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(n.id,{metricColumns:[...w,j]})}else{const j={...y,id:`groupby-${y.id}-${Date.now()}`,role:"groupby"};r(n.id,{groupByColumns:[...p,j]})}else{const g=p.findIndex(T=>T.name===y.name&&T.qualifiedEntityName===y.qualifiedEntityName),j=w.findIndex(T=>T.name===y.name&&T.qualifiedEntityName===y.qualifiedEntityName);g!==-1&&l(n.id,p[g].id),j!==-1&&d(n.id,w[j].id)}},C=y=>{if(!o)return y;const k=o.toLowerCase();return y.filter(g=>g.name.toLowerCase().includes(k)||g.label&&g.label.toLowerCase().includes(k))},I=y=>{switch(s.getDataType(y)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.Type}};return i?e.jsxs("div",{className:"flex h-full w-72 flex-col border-l border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Columns"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>c(!1),title:"Close panel",children:e.jsx(Ct,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search columns...",value:o,onChange:y=>u(y.target.value),className:"h-8 pl-8 text-sm"})]})}),(p.length>0||w.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[p.length>0&&e.jsxs(s.Collapsible,{defaultOpen:!0,children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(Ue,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsx("span",{children:"Groupings"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:p.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:p.map(y=>{const k=I(y.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(k,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:y.label||y.name}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>l(n.id,y.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},y.id)})})})]}),w.length>0&&e.jsxs(s.Collapsible,{defaultOpen:!0,children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(s.Calculator,{className:"h-3.5 w-3.5 text-green-500"}),e.jsx("span",{children:"Metrics"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:w.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:w.map(y=>{const k=I(y.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(k,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:y.label||y.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:y.aggregate}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>d(n.id,y.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},y.id)})})})]})]}),e.jsx(s.ScrollArea,{className:"flex-1",children:e.jsx("div",{className:"p-2",children:a?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(y=>{const k=C(y.columns);if(k.length===0)return null;const g=x.has(y.entityId)||o.length>0;return e.jsxs(s.Collapsible,{open:g,onOpenChange:()=>m(y.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",g&&"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:y.label||y.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:k.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:k.map(j=>{const T=I(j.dataType),L=f(j);return e.jsxs("label",{className:s.cn("flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-sm transition-colors hover:bg-muted/50",L&&"bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:L,onCheckedChange:N=>b(j,N),className:"h-3.5 w-3.5"}),e.jsx(T,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:j.label||j.name})]},j.id)})})})]},y.entityId)})})})]}):e.jsx("div",{className:"flex h-full items-start border-l border-border bg-muted/30 p-2",children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(!0),title:"Open panel",children:e.jsx(St,{className:"h-4 w-4"})})})}const Fa=[{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 Oa({value:t,onChange:a,onSubmit:n,onCancel:r,selectedColumn:l,availableColumns:d}){const[i,c]=D.useState(!1),[o,u]=D.useState("column"),x=D.useRef(null);D.useEffect(()=>{const m=f=>{f.key==="Escape"&&t?r():f.key==="Enter"&&t&&!i&&n(t)};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[t,r,n,i]);const h=m=>{const f=`[${m.label||m.name}]`,b=x.current;if(b){const C=b.selectionStart||0,I=b.selectionEnd||0,O=t.slice(0,C)+f+t.slice(I);a(O),setTimeout(()=>{b.setSelectionRange(C+f.length,C+f.length),b.focus()},0)}else a(t+f);c(!1)},p=m=>{const f=x.current;if(f){const b=f.selectionStart||0,C=f.selectionEnd||0,I=t.slice(0,b)+m.syntax+t.slice(C);a(I),setTimeout(()=>{f.setSelectionRange(b+m.name.length+1,b+m.syntax.length-1),f.focus()},0)}else a(t+m.syntax);c(!1)},w=m=>{switch(s.getDataType(m)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.Type}};return e.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-1.5",children:[e.jsx("div",{className:"flex min-w-[100px] items-center justify-center rounded border border-border bg-background px-2 py-1 text-xs font-medium text-muted-foreground",children:l?e.jsx("span",{className:"truncate",children:l.label||l.name}):e.jsx("span",{children:"—"})}),e.jsxs(s.Popover,{open:i&&o==="function",onOpenChange:m=>{c(m),m&&u("function")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Insert function",children:e.jsx(wt,{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:Fa.map(m=>e.jsx(s.CommandItem,{value:m.name,onSelect:()=>p(m),children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm font-medium",children:m.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:m.syntax})]})},m.name))})]})]})})]}),e.jsxs(s.Popover,{open:i&&o==="column",onOpenChange:m=>{c(m),m&&u("column")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",className:"h-7 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground",title:"Insert column reference",children:[e.jsx("span",{children:"Columns"}),e.jsx(s.ChevronDown,{className:"h-3 w-3"})]})}),e.jsx(s.PopoverContent,{className:"w-[250px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search columns..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No columns found."}),e.jsx(s.CommandGroup,{heading:"Available Columns",children:d.map(m=>{const f=w(m.dataType);return e.jsxs(s.CommandItem,{value:m.label||m.name,onSelect:()=>h(m),children:[e.jsx(f,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:m.label||m.name})]},m.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(s.Input$1,{ref:x,value:t,onChange:m=>a(m.target.value),placeholder:"Enter a formula or select a column...",className:"h-7 border-border bg-background font-mono text-sm"})}),t&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-destructive hover:bg-destructive/10 hover:text-destructive",onClick:r,title:"Cancel (Esc)",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-green-600 hover:bg-green-600/10 hover:text-green-600",onClick:()=>n(t),title:"Apply (Enter)",children:e.jsx(s.Check,{className:"h-4 w-4"})})]})]})}function Ra({className:t}){var p,w,m,f;const a=s.useEditorStore(b=>b.card),[n,r]=D.useState(null),[l,d]=D.useState(""),{columns:i=[],columnGroups:c=[],isLoading:o}=s.useColumns();(p=a==null?void 0:a.config)!=null&&p.groupByColumns,(w=a==null?void 0:a.config)!=null&&w.metricColumns,(m=a==null?void 0:a.config)!=null&&m.groupByColumns,(f=a==null?void 0:a.config)!=null&&f.pivotByColumns;const u=b=>{r(b),d(b?`[${b.label||b.name}]`:"")},x=b=>{console.log("Formula submitted:",b),d(""),r(null)},h=()=>{d(""),r(null)};return e.jsxs("div",{className:s.cn("flex h-full w-full flex-col",t),children:[e.jsx(Oa,{value:l,onChange:d,onSubmit:x,onCancel:h,selectedColumn:n,availableColumns:i}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(Da,{selectedColumn:n,onColumnSelect:u,isLoading:o,sourceFields:i})}),e.jsx(La,{entityGroups:c,isLoading:o})]})]})}function Ba(){var K,H;const[t,a]=D.useState("chart"),[n,r]=D.useState(!1),[l,d]=D.useState(!1),[i,c]=D.useState(!0),o=s.useEditorStore(V=>V.showAIDialog),u=s.useDashboardStore(V=>V.isVisualEditing),{setCardType:x}=s.useEditorActions(),h=s.useEditorStore(V=>V.card.type);D.useEffect(()=>Ea(),[]);const p=V=>{x(V)},w=s.useEditorStore(V=>V.frame),m=s.useEditorStore(V=>V.card);s.useEditorStore(V=>V.activeTabCardId),s.useEditorStore(V=>V.actions.getAvailableFields);const{addCard:f,removeCard:b,updateCard:C,setActiveCard:I,updateFilters:O}=s.useEditorActions(),{columns:R=[],isLoading:y,error:k}=s.useColumns(),g=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),j=m,{getFieldsForContainer:T,setFieldsForContainer:L}=s.useFieldManagement(j),{activeField:N,handleDragStart:v,handleDragEnd:A}=ba({activeCardId:w.activeCardId,sourceFields:R,getFieldsForContainer:T,setFieldsForContainer:L}),F=(V,G)=>{G&&O(V,G)},E=V=>{var G;C(V,{config:{...(G=w.cards.find(U=>U.id===V))==null?void 0:G.config,filters:void 0}})},M=R,S=V=>{if(!V)return 0;let G=V.conditions.length;return V.groups.forEach(U=>{G+=S(U)}),G},P=S(((K=j==null?void 0:j.config)==null?void 0:K.filters)||null);return e.jsxs(s.DndContext,{sensors:g,collisionDetection:s.closestCenter,onDragStart:v,onDragEnd:A,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Ts,{isVisible:i,onToggleVisibility:()=>c(!i)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:h==="tableBuilder"?e.jsx(Ra,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!o&&e.jsx(sa,{selectedChart:h,onChartChange:p,groupByFields:T("groupBy"),pivotByFields:T("pivotBy"),metricsFields:T("metrics"),sortByFields:T("sortBy"),activeField:N}),e.jsx(ka,{selectedChart:h,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onFiltersClick:()=>d(!0),filterCount:P,activeCard:j,dataSourceState:m.dataSource||s.EMPTY_DATA_SOURCE,columns:R,columnsLoading:y,columnsError:k,getFieldsForContainer:T,cards:w.cards,activeCardId:w.activeCardId,addCard:f,setActiveCard:I})]})}),!i&&u&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>c(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),j&&e.jsx(ja,{cardId:j.id,filters:((H=j.config)==null?void 0:H.filters)||null,onFiltersChange:F,onClearFilters:E,availableFields:M,isOpen:l,onOpenChange:d}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Ta,{activeField:N||null})})]})}function Va({authToken:t,onSave:a,onClose:n}){const r=D.useRef(null),l=s.useEditorStore(k=>k.showAIDialog),d=s.useEditorStore(k=>k.isDevMode),i=s.useAssistantLayoutStore(k=>k.setFullscreen),c=s.useAssistantLayoutStore(k=>k.setPanelOpen),o=s.useAssistantLayoutStore(k=>k.setContainer),u=s.useAssistantPanel("editor"),x=s.useFullscreenAssistant(),h=s.useAssistantContainer("editor"),p=x==="editor",w=D.useCallback(k=>{o("editor",k)},[o]),{setAuthToken:m}=s.useDashboardActions(),{setShowAIDialog:f,setOnSave:b,setOnClose:C}=s.useEditorActions(),{setActiveAssistantType:I}=s.useAIActions();D.useEffect(()=>{a&&b(a),n&&C(n)},[a,b,n,C]),D.useEffect(()=>{t&&t.accessToken&&m(t)},[t,m]),D.useEffect(()=>{var k,g;l?((k=r.current)==null||k.resize(40),c("editor",!0),I("editor")):((g=r.current)==null||g.resize(0),c("editor",!1),x==="editor"&&i(null),I(null))},[l,c,I,i,x]);function O(k){k<1?(f(!1),c("editor",!1),x==="editor"&&i(null),I(null)):(l||(f(!0),I("editor")),u.isOpen||c("editor",!0))}function R(){return e.jsxs(e.Fragment,{children:[e.jsx(Ts,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow border-l",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:s.cn("grow transition-opacity",p&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Bn,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:O,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(ps,{isFullscreen:p,onFullscreenChange:k=>i(k?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:w,className:s.cn("absolute inset-0",!p&&"pointer-events-none")})]})]})}function y(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:s.cn("flex grow transition-opacity",p&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Ba,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:O,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(ps,{isFullscreen:p,onFullscreenChange:k=>i(k?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:w,className:s.cn("absolute inset-0",!p&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:d?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:R()}):y()})}function Pa(){s.useDashboardStore(i=>i.selectedCardId);const t=s.useDashboardStore(i=>i.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(i=>i.actions),n=s.useDashboardStore(i=>i.isVisualEditing),r=s.useDashboardStore(i=>i.actions.updateFrame);function l(i){t&&(r(t,i),a(!1))}function d(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(Va,{onSave:l,onClose:d})})}exports.default=Pa;