react-semaphor 0.1.200 → 0.1.201

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/chunks/{dashboard-controls-CR7lL9Et.js → dashboard-controls-BacLhDZ5.js} +5 -5
  2. package/dist/chunks/{dashboard-controls-DgtdC01F.js → dashboard-controls-dHxXj3lu.js} +1 -1
  3. package/dist/chunks/{dashboard-json-FBuHMfmM.js → dashboard-json-B9GQb5g8.js} +1 -1
  4. package/dist/chunks/{dashboard-json-Bmbz02KL.js → dashboard-json-D_ssqHMn.js} +1 -1
  5. package/dist/chunks/{dashboard-summary-settings-dialog-DV5YCuwR.js → dashboard-summary-settings-dialog-CrK0Y8eU.js} +1 -1
  6. package/dist/chunks/{dashboard-summary-settings-dialog-DYTNK2ms.js → dashboard-summary-settings-dialog-PTZFYaCj.js} +1 -1
  7. package/dist/chunks/{edit-dashboard-visual-BIYh-RkG.js → edit-dashboard-visual-4m9e0fE3.js} +1 -1
  8. package/dist/chunks/{edit-dashboard-visual-Nxbr8BSI.js → edit-dashboard-visual-B09o_T1B.js} +2 -2
  9. package/dist/chunks/{editor-action-buttons-CG41Ltln.js → editor-action-buttons-BTfSScCK.js} +1 -1
  10. package/dist/chunks/{editor-action-buttons-DbcFVAEa.js → editor-action-buttons-DqVXlwGQ.js} +2 -2
  11. package/dist/chunks/{index-BpOENSQP.js → index-Bbio7O6b.js} +1 -1
  12. package/dist/chunks/{index-DVYihXOb.js → index-dzyROcGu.js} +5 -4
  13. package/dist/chunks/{notification-bell-elxLrm2b.js → notification-bell-DUgBTV22.js} +1 -1
  14. package/dist/chunks/{notification-bell-CJIzPr5F.js → notification-bell-zly06Xaf.js} +3 -3
  15. package/dist/chunks/{resource-management-panel-DIFmTV1p.js → resource-management-panel-Bcm1QBik.js} +1 -1
  16. package/dist/chunks/{resource-management-panel-BTPmfdMd.js → resource-management-panel-CGjcKL2u.js} +3 -3
  17. package/dist/chunks/{use-role-aware-display-preferences-CwhsIdSD.js → use-role-aware-display-preferences-CTtWN05-.js} +1 -1
  18. package/dist/chunks/{use-role-aware-display-preferences-Ld4jvyhY.js → use-role-aware-display-preferences-DVP5ZxZJ.js} +1 -1
  19. package/dist/chunks/{use-visual-utils-B6X9311f.js → use-visual-utils-D5Tp7ZlC.js} +1 -1
  20. package/dist/chunks/{use-visual-utils-B9Bw0478.js → use-visual-utils-agqKw1Gz.js} +1 -1
  21. package/dist/dashboard/index.cjs +1 -1
  22. package/dist/dashboard/index.js +1 -1
  23. package/dist/index.cjs +1 -1
  24. package/dist/index.js +5 -5
  25. package/dist/surfboard/index.cjs +1 -1
  26. package/dist/surfboard/index.js +2 -2
  27. package/dist/types/dashboard.d.ts +1 -1
  28. package/dist/types/main.d.ts +1 -1
  29. package/dist/types/surfboard.d.ts +1 -1
  30. package/dist/types/types.d.ts +1 -1
  31. package/package.json +1 -1
@@ -1074,7 +1074,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
1074
1074
 
1075
1075
  `)},flush(e){e.enqueue(`data: [DONE]
1076
1076
 
1077
- `)}})}});var aQe=eXe(()=>fte(Ci([ir({type:Vt("text-start"),id:ft(),providerMetadata:jr.optional()}),ir({type:Vt("text-delta"),id:ft(),delta:ft(),providerMetadata:jr.optional()}),ir({type:Vt("text-end"),id:ft(),providerMetadata:jr.optional()}),ir({type:Vt("error"),errorText:ft()}),ir({type:Vt("tool-input-start"),toolCallId:ft(),toolName:ft(),providerExecuted:ho().optional(),dynamic:ho().optional()}),ir({type:Vt("tool-input-delta"),toolCallId:ft(),inputTextDelta:ft()}),ir({type:Vt("tool-input-available"),toolCallId:ft(),toolName:ft(),input:wa(),providerExecuted:ho().optional(),providerMetadata:jr.optional(),dynamic:ho().optional()}),ir({type:Vt("tool-input-error"),toolCallId:ft(),toolName:ft(),input:wa(),providerExecuted:ho().optional(),providerMetadata:jr.optional(),dynamic:ho().optional(),errorText:ft()}),ir({type:Vt("tool-output-available"),toolCallId:ft(),output:wa(),providerExecuted:ho().optional(),dynamic:ho().optional(),preliminary:ho().optional()}),ir({type:Vt("tool-output-error"),toolCallId:ft(),errorText:ft(),providerExecuted:ho().optional(),dynamic:ho().optional()}),ir({type:Vt("reasoning-start"),id:ft(),providerMetadata:jr.optional()}),ir({type:Vt("reasoning-delta"),id:ft(),delta:ft(),providerMetadata:jr.optional()}),ir({type:Vt("reasoning-end"),id:ft(),providerMetadata:jr.optional()}),ir({type:Vt("source-url"),sourceId:ft(),url:ft(),title:ft().optional(),providerMetadata:jr.optional()}),ir({type:Vt("source-document"),sourceId:ft(),mediaType:ft(),title:ft(),filename:ft().optional(),providerMetadata:jr.optional()}),ir({type:Vt("file"),url:ft(),mediaType:ft(),providerMetadata:jr.optional()}),ir({type:ate(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:ft().optional(),data:wa(),transient:ho().optional()}),ir({type:Vt("start-step")}),ir({type:Vt("finish-step")}),ir({type:Vt("start"),messageId:ft().optional(),messageMetadata:wa().optional()}),ir({type:Vt("finish"),finishReason:ste(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:wa().optional()}),ir({type:Vt("abort")}),ir({type:Vt("message-metadata"),messageMetadata:wa()})])));function lQe(e){return e.type.startsWith("data-")}function vte(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const s=t[r];if(s===void 0)continue;const o=r in e?e[r]:void 0,i=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),a=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);i&&a?n[r]=vte(o,s):n[r]=s}return n}function cQe(e){const t=["ROOT"];let n=-1,r=null;function s(l,u,d){switch(l){case'"':{n=u,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,r=u,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function o(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":s(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=l,t.pop();break}default:{n=l,s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l)):n=l;break}}}let a=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?a+="true".slice(d.length):"false".startsWith(d)?a+="false".slice(d.length):"null".startsWith(d)&&(a+="null".slice(d.length))}}return a}async function wte(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await z1({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await z1({text:cQe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Yv(e){return e.type.startsWith("tool-")}function uQe(e){return e.type==="dynamic-tool"}function CT(e){return Yv(e)||uQe(e)}function q6(e){return e.type.split("-").slice(1).join("-")}function dQe({lastMessage:e,messageId:t}){return{message:(e==null?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function fQe({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await r(async({state:u,write:d})=>{var f,h,m,p;function g(C){const S=u.message.parts.filter(Yv).find(j=>j.toolCallId===C);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function b(C){const S=u.message.parts.filter(j=>j.type==="dynamic-tool").find(j=>j.toolCallId===C);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function x(C){var N;const S=u.message.parts.find(_=>Yv(_)&&_.toolCallId===C.toolCallId),j=C,k=S;S!=null?(S.state=C.state,k.input=j.input,k.output=j.output,k.errorText=j.errorText,k.rawInput=j.rawInput,k.preliminary=j.preliminary,k.providerExecuted=(N=j.providerExecuted)!=null?N:S.providerExecuted,j.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:`tool-${C.toolName}`,toolCallId:C.toolCallId,state:C.state,input:j.input,output:j.output,rawInput:j.rawInput,errorText:j.errorText,providerExecuted:j.providerExecuted,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}function y(C){var N,S;const j=u.message.parts.find(E=>E.type==="dynamic-tool"&&E.toolCallId===C.toolCallId),k=C,_=j;j!=null?(j.state=C.state,_.toolName=C.toolName,_.input=k.input,_.output=k.output,_.errorText=k.errorText,_.rawInput=(N=k.rawInput)!=null?N:_.rawInput,_.preliminary=k.preliminary,_.providerExecuted=(S=k.providerExecuted)!=null?S:j.providerExecuted,k.providerMetadata!=null&&j.state==="input-available"&&(j.callProviderMetadata=k.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:C.toolName,toolCallId:C.toolCallId,state:C.state,input:k.input,output:k.output,errorText:k.errorText,preliminary:k.preliminary,providerExecuted:k.providerExecuted,...k.providerMetadata!=null?{callProviderMetadata:k.providerMetadata}:{}})}async function v(C){if(C!=null){const N=u.message.metadata!=null?vte(u.message.metadata,C):C;t!=null&&await B6({value:N,schema:t}),u.message.metadata=N}}switch(a.type){case"text-start":{const C={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=C,u.message.parts.push(C),d();break}case"text-delta":{const C=u.activeTextParts[a.id];C.text+=a.delta,C.providerMetadata=(f=a.providerMetadata)!=null?f:C.providerMetadata,d();break}case"text-end":{const C=u.activeTextParts[a.id];C.state="done",C.providerMetadata=(h=a.providerMetadata)!=null?h:C.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const C={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=C,u.message.parts.push(C),d();break}case"reasoning-delta":{const C=u.activeReasoningParts[a.id];C.text+=a.delta,C.providerMetadata=(m=a.providerMetadata)!=null?m:C.providerMetadata,d();break}case"reasoning-end":{const C=u.activeReasoningParts[a.id];C.providerMetadata=(p=a.providerMetadata)!=null?p:C.providerMetadata,C.state="done",delete u.activeReasoningParts[a.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),d();break}case"tool-input-start":{const C=u.message.parts.filter(Yv);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:C.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const C=u.partialToolCalls[a.toolCallId];C.text+=a.inputTextDelta;const{value:N}=await wte(C.text);C.dynamic?y({toolCallId:a.toolCallId,toolName:C.toolName,state:"input-streaming",input:N}):x({toolCallId:a.toolCallId,toolName:C.toolName,state:"input-streaming",input:N}),d();break}case"tool-input-available":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d();break}case"tool-output-available":{if(a.dynamic){const C=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:C.toolName,state:"output-available",input:C.input,output:a.output,preliminary:a.preliminary})}else{const C=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:q6(C),state:"output-available",input:C.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const C=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:C.toolName,state:"output-error",input:C.input,errorText:a.errorText,providerExecuted:a.providerExecuted})}else{const C=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:q6(C),state:"output-error",input:C.input,rawInput:C.rawInput,errorText:a.errorText,providerExecuted:a.providerExecuted})}d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{a.messageId!=null&&(u.message.id=a.messageId),await v(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&d();break}case"finish":{a.finishReason!=null&&(u.finishReason=a.finishReason),await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"message-metadata":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"error":{s==null||s(new Error(a.errorText));break}default:if(lQe(a)){(n==null?void 0:n[a.type])!=null&&await B6({value:a.data,schema:n[a.type]});const C=a;if(C.transient){i==null||i(C);break}const N=C.id!=null?u.message.parts.find(S=>C.type===S.type&&C.id===S.id):void 0;N!=null?N.data=C.data:u.message.parts.push(C),i==null||i(C),d()}}l.enqueue(a)})}}))}async function hQe({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:r}=await n.read();if(r)break}}catch(r){t==null||t(r)}finally{n.releaseLock()}}Vy({prefix:"aitxt",size:24});Vy({prefix:"aiobj",size:24});var mQe=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{await e(),t()}catch(r){n(r)}}),this.processQueue()})}};Vy({prefix:"aiobj",size:24});var pQe={};XXe(pQe,{object:()=>bQe,text:()=>gQe});var gQe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),bQe=({schema:e})=>{const t=KXe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await wte(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const s=r.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:n},r){const s=await z1({text:n});if(!s.success)throw new U6({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const o=await aP({value:s.value,schema:t});if(!o.success)throw new U6({message:"No object generated: response did not match schema.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return o.value}}};async function xQe(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async t=>{const{name:n,type:r}=t,s=await new Promise((o,i)=>{const a=new FileReader;a.onload=l=>{var u;o((u=l.target)==null?void 0:u.result)},a.onerror=l=>i(l),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var yQe=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:s,prepareSendMessagesRequest:o,prepareReconnectToStreamRequest:i}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=s,this.prepareSendMessagesRequest=o,this.prepareReconnectToStreamRequest=i}async sendMessages({abortSignal:e,...t}){var n,r,s,o,i;const a=await oh(this.body),l=await oh(this.headers),u=await oh(this.credentials),d={...ed(l),...ed(t.headers)},f=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:d,credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),h=(r=f==null?void 0:f.api)!=null?r:this.api,m=(f==null?void 0:f.headers)!==void 0?ed(f.headers):d,p=(f==null?void 0:f.body)!==void 0?f.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},g=(s=f==null?void 0:f.credentials)!=null?s:u,x=await((o=this.fetch)!=null?o:globalThis.fetch)(h,{method:"POST",headers:L6({"Content-Type":"application/json",...m},`ai-sdk/${W6}`,$6()),body:JSON.stringify(p),credentials:g,signal:e});if(!x.ok)throw new Error((i=await x.text())!=null?i:"Failed to fetch the chat response.");if(!x.body)throw new Error("The response body is empty.");return this.processResponseStream(x.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await oh(this.body),a=await oh(this.headers),l=await oh(this.credentials),u={...ed(a),...ed(e.headers)},d=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:u,credentials:l,requestMetadata:e.metadata})),f=(n=d==null?void 0:d.api)!=null?n:`${this.api}/${e.chatId}/stream`,h=(d==null?void 0:d.headers)!==void 0?ed(d.headers):u,m=(r=d==null?void 0:d.credentials)!=null?r:l,g=await((s=this.fetch)!=null?s:globalThis.fetch)(f,{method:"GET",headers:L6(h,`ai-sdk/${W6}`,$6()),credentials:m});if(g.status===204)return null;if(!g.ok)throw new Error((o=await g.text())!=null?o:"Failed to fetch the chat response.");if(!g.body)throw new Error("The response body is empty.");return this.processResponseStream(g.body)}},cP=class extends yQe{constructor(e={}){super(e)}processResponseStream(e){return rXe({stream:e,schema:aQe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},vQe=class{constructor({generateId:e=YZe,id:t=e(),transport:n=new cP,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new mQe,this.sendMessage=async(f,h)=>{var m,p,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(m=this.lastMessage)==null?void 0:m.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await xQe(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:x=f,f.messageId!=null){const y=this.state.messages.findIndex(v=>v.id===f.messageId);if(y===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[y].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,y+1),this.state.replaceMessage(y,{...x,id:f.messageId,role:(p=x.role)!=null?p:"user",metadata:f.metadata})}else this.state.pushMessage({...x,id:(g=x.id)!=null?g:this.generateId(),role:(b=x.role)!=null?b:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const m=f==null?this.state.messages.length-1:this.state.messages.findIndex(p=>p.id===f);if(m===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[m].role==="assistant"?m:m+1),await this.makeRequest({trigger:"regenerate-message",messageId:f,...h})},this.resumeStream=async(f={})=>{await this.makeRequest({trigger:"resume-stream",...f})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolOutput=async({state:f="output-available",tool:h,toolCallId:m,output:p,errorText:g})=>this.jobExecutor.run(async()=>{var b,x;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(C=>CT(C)&&C.toolCallId===m?{...C,state:f,output:p,errorText:g}:C)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(C=>CT(C)&&C.toolCallId===m?{...C,state:f,output:p,errorText:g}:C)),this.status!=="streaming"&&this.status!=="submitted"&&((b=this.sendAutomaticallyWhen)!=null&&b.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(x=this.lastMessage)==null?void 0:x.id})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=l,this.onData=u,this.sendAutomaticallyWhen=d}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:s}){var o,i,a,l;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;let d=!1,f=!1,h=!1;try{const m={state:dQe({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};m.abortController.signal.addEventListener("abort",()=>{d=!0}),this.activeResponse=m;let p;if(e==="resume-stream"){const b=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(b==null){this.setStatus({status:"ready"});return}p=b}else p=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:m.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const g=b=>this.jobExecutor.run(()=>b({state:m.state,write:()=>{var x;this.setStatus({status:"streaming"}),m.state.message.id===((x=this.lastMessage)==null?void 0:x.id)?this.state.replaceMessage(this.state.messages.length-1,m.state.message):this.state.pushMessage(m.state.message)}}));await hQe({stream:fQe({stream:p,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:g,onError:b=>{throw b}}),onError:b=>{throw b}}),this.setStatus({status:"ready"})}catch(m){if(d||m.name==="AbortError")return d=!0,this.setStatus({status:"ready"}),null;h=!0,m instanceof TypeError&&(m.message.toLowerCase().includes("fetch")||m.message.toLowerCase().includes("network"))&&(f=!0),this.onError&&m instanceof Error&&this.onError(m),this.setStatus({status:"error",error:m})}finally{try{(i=this.onFinish)==null||i.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:d,isDisconnect:f,isError:h,finishReason:(o=this.activeResponse)==null?void 0:o.state.finishReason})}catch(m){console.error(m)}this.activeResponse=void 0}(a=this.sendAutomaticallyWhen)!=null&&a.call(this,{messages:this.state.messages})&&!h&&await this.makeRequest({trigger:"submit-message",messageId:(l=this.lastMessage)==null?void 0:l.id,metadata:t,headers:n,body:r})}};function wQe({messages:e}){const t=e[e.length-1];if(!t||t.role!=="assistant")return!1;const n=t.parts.reduce((s,o,i)=>o.type==="step-start"?i:s,-1),r=t.parts.slice(n+1).filter(CT).filter(s=>!s.providerExecuted);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function CQe(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...o){clearTimeout(n);const i=Date.now(),a=i-r,l=t-a;l<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},l)}}var SQe=CQe;const NQe=hf(SQe);var Cte=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Kn=(e,t,n)=>(Cte(e,t,"read from private field"),n?n.call(e):t.get(e)),ga=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},Cc=(e,t,n,r)=>(Cte(e,t,"write to private field"),t.set(e,n),n);function jQe(e,t){return t!=null?NQe(e,t):e}var Jo,Gv,Kv,Ig,Rg,Ag,dh,ST,NT,kQe=class{constructor(e=[]){ga(this,Jo,void 0),ga(this,Gv,"ready"),ga(this,Kv,void 0),ga(this,Ig,new Set),ga(this,Rg,new Set),ga(this,Ag,new Set),this.pushMessage=t=>{Cc(this,Jo,Kn(this,Jo).concat(t)),Kn(this,dh).call(this)},this.popMessage=()=>{Cc(this,Jo,Kn(this,Jo).slice(0,-1)),Kn(this,dh).call(this)},this.replaceMessage=(t,n)=>{Cc(this,Jo,[...Kn(this,Jo).slice(0,t),this.snapshot(n),...Kn(this,Jo).slice(t+1)]),Kn(this,dh).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?jQe(t,n):t;return Kn(this,Ig).add(r),()=>{Kn(this,Ig).delete(r)}},this["~registerStatusCallback"]=t=>(Kn(this,Rg).add(t),()=>{Kn(this,Rg).delete(t)}),this["~registerErrorCallback"]=t=>(Kn(this,Ag).add(t),()=>{Kn(this,Ag).delete(t)}),ga(this,dh,()=>{Kn(this,Ig).forEach(t=>t())}),ga(this,ST,()=>{Kn(this,Rg).forEach(t=>t())}),ga(this,NT,()=>{Kn(this,Ag).forEach(t=>t())}),Cc(this,Jo,e)}get status(){return Kn(this,Gv)}set status(e){Cc(this,Gv,e),Kn(this,ST).call(this)}get error(){return Kn(this,Kv)}set error(e){Cc(this,Kv,e),Kn(this,NT).call(this)}get messages(){return Kn(this,Jo)}set messages(e){Cc(this,Jo,[...e]),Kn(this,dh).call(this)}};Jo=new WeakMap;Gv=new WeakMap;Kv=new WeakMap;Ig=new WeakMap;Rg=new WeakMap;Ag=new WeakMap;dh=new WeakMap;ST=new WeakMap;NT=new WeakMap;var fh,Y6=class extends vQe{constructor({messages:e,...t}){const n=new kQe(e);super({...t,state:n}),ga(this,fh,void 0),this["~registerMessagesCallback"]=(r,s)=>Kn(this,fh)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>Kn(this,fh)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>Kn(this,fh)["~registerErrorCallback"](r),Cc(this,fh,n)}};fh=new WeakMap;function Ste({experimental_throttle:e,resume:t=!1,...n}={}){const r=w.useRef("chat"in n?n.chat:new Y6(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new Y6(n));const o="id"in n?n.id:null,i=w.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=w.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),l=w.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=w.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=w.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return w.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:a,setMessages:d,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:u,resumeStream:r.current.resumeStream,status:l,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput}}function EQe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function _Qe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function TQe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function MQe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function Nte(e){return e.map(r=>{const s=r.connectionType==="API"||r.connectionType==="S3"||r.connectionType==="S3Tables"?"DuckDb":r.connectionType;return r.datamodelName?{...r,databaseName:"",schemaName:"",tableName:"",connectionType:s,tableReferenceFormat:"dm.{table_name}"}:{...r,connectionType:s,tableReferenceFormat:MQe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function jte(e){var n,r;if(!e)return"";let t="";try{const s=JSON.parse((e==null?void 0:e.message)||"{}");t=((r=(n=s==null?void 0:s.error)==null?void 0:n.lastError)==null?void 0:r.message)||(s==null?void 0:s.error)||e.message}catch{t=e.message}return t}function DQe(){var b;const{authToken:e,tokenProps:t}=Xe(),n=J(x=>x.dashboard.aiScopeTables),r=(b=tC().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=Ste({transport:new cP({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=ua.getState();return{assistantId:"dashboard-assistant",assistantProfileId:r,aiContext:x.currentAIContext,reasoningEffort:x.reasoningEffort,showReasoning:x.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:x,body:y})=>({body:{...y,messages:lY(x)}})}),onToolCall:m,sendAutomaticallyWhen:wQe,onFinish({isAbort:x,isDisconnect:y,isError:v}){console.log(x?"[Dashboard Assistant] Stream aborted by user":y?"[Dashboard Assistant] Stream disconnected (network error)":v?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully")},onError(x){var y;if(x.name==="AbortError"||(y=x.message)!=null&&y.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)");return}console.error("[Dashboard Assistant] Stream error:",x)}});async function m({toolCall:x}){if(x.toolName==="getCurrentTableScope"&&u({tool:x.toolName,toolCallId:x.toolCallId,output:{tables:Nte(n||[])}}),x.toolName==="getDashboardContext"){const y=J.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const p=!["ready","error"].includes(l),g=jte(d);return{sendMessage:s,regenerate:a,isLoading:p,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function kte(){var u;const{authToken:e,tokenProps:t}=Xe(),n=(u=tC().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=mn({queryKey:["assistant-profile",n],queryFn:()=>rr(`${t.apiServiceUrl}/v1/assistant/${n}`,(e==null?void 0:e.accessToken)||""),enabled:r()});return{assistantProfile:s==null?void 0:s.assistantProfile,isLoading:o,isFetching:i,isError:a}}function Ete({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:c.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[c.jsxs("div",{className:"mb-3 flex items-center",children:[c.jsx(B8,{className:"mr-2 h-4 w-4 text-muted-foreground"}),c.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),c.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>c.jsx(oe,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function B1(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(NM,{className:r});case"view":return c.jsx(ru,{className:r});case"materialized view":return c.jsx($ie,{className:r});case"model":return c.jsx(iC,{className:r});case"file":return c.jsx(bi,{className:r});case"dataset":return c.jsx($l,{className:r});case"upload":return c.jsx(_M,{className:r});case"url":return c.jsx(Y8,{className:r});default:return c.jsx(Ix,{className:r})}}const _te=D.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(Zo,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(Bs.Input,{ref:n,className:X("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));_te.displayName=Bs.Input.displayName;const yv=e=>e.label||(e==null?void 0:e.name),G6=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function IQe({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:u}){const{tokenProps:d}=Xe(),f=(d==null?void 0:d.type)==="dashboard",[h,m]=w.useState(""),[p,g]=w.useState(""),b=s.filter(S=>{if(!h)return!0;const j=yv(S).toLowerCase(),k=G6(S).toLowerCase(),_=h.toLowerCase();return j.includes(_)||k.includes(_)});w.useEffect(()=>{e||(m(""),g(""))},[e]),w.useEffect(()=>{b.length>0&&!p&&g(yv(b[0]))},[b,p]);const x=()=>{if(!p)return;const S=b.find(j=>yv(j)===p);S&&(o.some(k=>"id"in S&&"id"in k?S.id===k.id:S.name===k.name&&S.connectionId===k.connectionId)||t(S),i(S),r())},y=S=>{(S.key==="Tab"||S.key==="Enter")&&(S.preventDefault(),x())};if(!e)return null;const v=S=>o.some(j=>"id"in S&&"id"in j?S.id===j.id:S.name===j.name&&S.connectionId===j.connectionId),C=o.length===s.length,N=o.length>0;return c.jsx(c.Fragment,{children:c.jsxs(cp,{shouldFilter:!1,value:p,onValueChange:g,onKeyDown:y,children:[s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[c.jsx(_te,{placeholder:"Search entities...",value:h,onValueChange:m,className:"flex-1 border-0",autoFocus:!0}),!f&&c.jsxs(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u==null||u()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[c.jsx(Mr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[c.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),a==null||a()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},disabled:C,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),N&&c.jsxs(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),l==null||l()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[c.jsx(St,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),c.jsxs(up,{className:"min-h-60",children:[c.jsx(dp,{children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[c.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&c.jsxs(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u==null||u()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[c.jsx(Mr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx(fp,{children:b.map((S,j)=>{const k=v(S),_="id"in S?S.id:`${S.connectionId}-${S.name}`,E=yv(S);return c.jsxs(hp,{value:E,onSelect:()=>{k?n==null||n(S):t(S)},onMouseDown:M=>{M.preventDefault(),M.stopPropagation()},className:X("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[c.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:B1(S.type)}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate font-medium",children:E}),c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:G6(S)})]}),k&&c.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:c.jsx(Ar,{className:"h-3 w-3 text-background"})})]},_)})})]})]})})}const jT=e=>e.name||e.name,RQe=e=>{const t=jT(e),n="description"in e?e.description:"",r=e.database||"",s=e.schema||"";return c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"font-medium",children:t}),n&&c.jsx("div",{className:"text-sm text-muted-foreground",children:n}),c.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,s&&` • Schema: ${s}`]})]})};function AQe({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r}){const[s,o]=w.useState(!1),i=e.length>0;e.length,t.length,e.length<t.length;const a=e.length>=3?e.slice(0,2):e,l=e.length>=3?e.slice(2):[],u=l.length>0;return c.jsx(Ln,{children:c.jsx("div",{className:"space-y-2",children:i&&c.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.map((d,f)=>{const h="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs(ln,{children:[c.jsx(cn,{asChild:!0,children:c.jsxs(qe,{variant:"secondary",className:"group relative cursor-pointer gap-2 transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[B1(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:jT(d)}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(d),children:c.jsx(St,{className:"h-3 w-3"})})]})}),c.jsx(dn,{side:"top",className:"max-w-xs",children:RQe(d)})]},h)}),u&&c.jsxs(ln,{open:s,onOpenChange:o,children:[c.jsx(cn,{asChild:!0,children:c.jsxs(qe,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>o(!0),children:[c.jsx(U8,{className:"h-3 w-3"}),c.jsxs("span",{className:"text-xs",children:[l.length," more"]}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(l),children:c.jsx(St,{className:"h-3 w-3"})})]})}),c.jsx(dn,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),c.jsx("div",{className:"space-y-2",children:l.map(d=>{const f="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:B1(d.type,{size:"h-3 w-3"})}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate text-sm font-medium",children:jT(d)}),c.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(d),l.length===1&&o(!1)},children:c.jsx(St,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function Tte(e){return e.type==="dataset"&&e.label||e.name}function PQe(e){const t=[];return t.push({label:"Type",value:e.type}),t.push({label:"Name",value:e.name}),e.connectionType&&t.push({label:"Connection",value:e.connectionType}),e.database&&t.push({label:"Database",value:e.database}),e.schema&&t.push({label:"Schema",value:e.schema}),e.type==="dataset"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="dataset"&&e.description&&t.push({label:"Description",value:e.description}),e.type==="model"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="model"&&e.description&&t.push({label:"Description",value:e.description}),t}function FQe({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:c.jsxs("div",{className:"mb-4 space-y-2",children:[c.jsxs(fe,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),c.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:c.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>c.jsxs(qe,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[c.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),Tte(n),c.jsx("button",{onClick:s=>{s.stopPropagation(),t(n)},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-0 transition-opacity hover:bg-red-100 group-hover:opacity-100",children:c.jsx(St,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function OQe(e){const{tokenProps:t}=Xe(),n=J(l=>l.authToken)||e;Le(l=>l.selectedConnectionId),Le(l=>{var u,d;return(d=(u=l==null?void 0:l.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=mn({queryKey:["semantic-domains"],queryFn:()=>rr(`${t.apiServiceUrl}/v1/domains`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)});return{isPending:s,error:a,semanticDomainsData:o,semanticDomains:(o==null?void 0:o.domains)||[],isSemanticDomainsLoading:i,isSemanticDomainsError:a,refetchSemanticDomains:r}}function $Qe(e,t){const{tokenProps:n}=Xe(),r=J(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:l}=mn({queryKey:["datasets",e],queryFn:()=>rr(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:o,error:l,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:l,refetchDatasets:s}}function LQe(e){var g,b;const{tokenProps:t}=Xe(),n=J(x=>x.authToken)||e,{connections:r}=Ni(e),s=Le(x=>{var y,v;return(v=(y=x==null?void 0:x.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(x=>x.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(x){var y;return!s||!x?!1:!!((y=o==null?void 0:o.capabilities)!=null&&y.path.includes("database"))}const{data:d,isPending:f,error:h,refetch:m}=mn({queryKey:["databases",s],queryFn:()=>rr(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),p=(b=d==null?void 0:d.databases)==null?void 0:b.map(x=>({id:x.database_name,name:x.database_name}));return{isPending:f,error:h,databases:p||[],refetch:m,label:l}}function zQe(e){var g;const{tokenProps:t}=Xe(),n=J(b=>b.authToken)||e,{connections:r}=Ni(e),s=Le(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=Le(b=>{var x,y,v;return(v=(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(b=>b.id===s),a=i==null?void 0:i.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){var b;return!(!s||!((b=i==null?void 0:i.capabilities)!=null&&b.path.includes("schema"))||!o)}const{data:d,isPending:f,error:h,refetch:m}=mn({queryKey:["schemas",s,o],queryFn:()=>rr(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),p=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:p||[],refetch:m,label:l}}function Mte(e){const{tokenProps:t}=Xe(),n=J(h=>h.authToken)||e,{connections:r}=Ni(e),s=Le(h=>{var m,p;return(p=(m=h==null?void 0:h.card)==null?void 0:m.dataSource)==null?void 0:p.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:l,error:u,refetch:d}=mn({queryKey:["dataModels",s],queryFn:()=>rr(`${t.apiServiceUrl}/v1/datamodels`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:i()}),f=a==null?void 0:a.datamodels.map(h=>({id:h.id,name:h.name,label:h.label,description:h.description,connectionId:s,dialect:h.dialect,connectionType:o==null?void 0:o.type,type:"model",database:h.database,schema:h.schema}));return{isPending:l,error:u,dataModels:f||[],refetch:d}}function BQe(){var N,S,j;const e=Le(k=>k.card.dataSource);Le(k=>k.actions.updateDirectSource);const t=Le(k=>k.actions.updateDataSource),[n,r]=w.useState(""),{selectedConnection:s,error:o}=Ni(),{databases:i,isPending:a,error:l,label:u}=LQe(),{schemas:d,isPending:f,error:h,label:m}=zQe(),{error:p}=Mte(),g=s==null?void 0:s.capabilities.path.includes("schema"),b=s==null?void 0:s.capabilities.path.includes("database"),x=u==null?void 0:u.toLowerCase(),y=m==null?void 0:m.toLowerCase(),v=k=>{e&&t({...e,dbSelection:{database:k,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},C=k=>{var E;if(!((E=e==null?void 0:e.dbSelection)!=null&&E.database))return;const _=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{..._,schema:k},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return c.jsxs(c.Fragment,{children:[(o||l||h||p)&&c.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[c.jsx("div",{className:"flex items-center",children:c.jsxs("div",{className:"text-sm text-red-800",children:[c.jsx("strong",{children:"Error loading data:"}),c.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&c.jsxs("li",{children:["Connections: ",o]}),l&&c.jsxs("li",{children:[u,": ",l.message]}),h&&c.jsxs("li",{children:[m,": ",h.message]}),p&&c.jsxs("li",{children:["Data Models: ",p.message]})]})]})}),c.jsx(oe,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),c.jsxs("div",{className:"space-y-4",children:[b&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{className:"text-sm font-medium",children:u}),c.jsxs(it,{value:((N=e==null?void 0:e.dbSelection)==null?void 0:N.database)||"",onValueChange:v,disabled:a,children:[c.jsx(rt,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[a&&c.jsx(yn,{className:"h-4 w-4 animate-spin"}),c.jsx(at,{placeholder:l?`Error loading ${x}`:a?`Loading ${x}...`:`Select ${x}...`})]})}),c.jsx(st,{children:i.map(k=>c.jsx(we,{className:"hover:bg-muted",value:k.id,children:k.name},k.id))})]})]}),((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)&&g&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{className:"text-sm font-medium",children:m}),c.jsxs(it,{value:((j=e==null?void 0:e.dbSelection)==null?void 0:j.schema)||"",onValueChange:C,disabled:f,children:[c.jsx(rt,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[f&&c.jsx(yn,{className:"h-4 w-4 animate-spin"}),c.jsx(at,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),c.jsx(st,{children:d.map(k=>c.jsx(we,{className:"hover:bg-muted",value:k.id,children:k.name},k.id))})]})]})]})]})}function VQe(){const e=Le(l=>l.card.dataSource),t=Le(l=>l.actions.updateDataSource),[n,r]=w.useState(!1),s=l=>{if(!l||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(l).map(f=>({id:`file-${Date.now()}-${Math.random()}`,name:f.name,type:"upload",connectionId:"default",connectionType:"none",label:f.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:f.name,file:f})),d=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...d,...u]})},o=l=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==l);t({...e,selectedEntities:u})},i=l=>{if(l===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(l)/Math.log(u));return Number.parseFloat((l/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{className:"text-sm font-medium",children:"Upload Files"}),c.jsxs("div",{className:`rounded-lg border-2 border-dashed p-6 text-center transition-colors ${n?"border-blue-400 bg-blue-50":"border-gray-300 hover:border-gray-400"}`,onDragOver:l=>{l.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:l=>{l.preventDefault(),r(!1),s(l.dataTransfer.files)},children:[c.jsx(_M,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),c.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),c.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:l=>s(l.target.files),accept:".csv,.json,.xlsx,.xls"}),c.jsx(oe,{variant:"outline",size:"sm",onClick:()=>{var l;return(l=document.getElementById("file-upload"))==null?void 0:l.click()},children:"Select Files"}),c.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(fe,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(l=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(bi,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:l.originalName}),c.jsx("p",{className:"text-xs text-gray-500",children:l.file?i(l.file.size):""})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(l.id),children:c.jsx(St,{className:"h-3 w-3"})})]},l.id))})]})]})}function HQe(){const e=Le(f=>f.card.dataSource),t=Le(f=>f.actions.updateDataSource),[n,r]=w.useState(""),[s,o]=w.useState(""),[i,a]=w.useState("api"),l=()=>{if(!n.trim()||!s.trim()||!e)return;const f={id:`url-${Date.now()}-${Math.random()}`,name:n.trim(),type:"url",connectionId:"default",connectionType:"none",label:n.trim(),description:`URL source of type ${i}`,url:s.trim(),sourceType:i,originalName:n.trim()},h=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...h,f]}),r(""),o(""),a("api")},u=f=>{if(!e)return;const h=(e.selectedEntities||[]).filter(m=>m.id!==f);t({...e,selectedEntities:h})},d=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),c.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{className:"text-xs text-gray-600",children:"Source Name"}),c.jsx(pn,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{className:"text-xs text-gray-600",children:"URL"}),c.jsx(pn,{placeholder:"https://api.example.com/data",value:s,onChange:f=>o(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{className:"text-xs text-gray-600",children:"Type"}),c.jsxs("select",{value:i,onChange:f=>a(f.target.value),className:"h-8 w-full rounded-md border border-gray-300 px-2 text-sm",children:[c.jsx("option",{value:"api",children:"API Endpoint"}),c.jsx("option",{value:"csv",children:"CSV File"}),c.jsx("option",{value:"json",children:"JSON File"})]})]}),c.jsxs(oe,{onClick:l,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[c.jsx(Mr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(fe,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(Ix,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),c.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:c.jsx(St,{className:"h-3 w-3"})})]},f.id))})]})]})}function UQe(e,t){var y,v;const{tokenProps:n}=Xe(),r=J(C=>C.authToken)||t,{connections:s}=Ni(t),o=Le(C=>{var N,S;return(S=(N=C==null?void 0:C.card)==null?void 0:N.dataSource)==null?void 0:S.connectionId}),i=Le(C=>{var N,S,j;return(j=(S=(N=C==null?void 0:C.card)==null?void 0:N.dataSource)==null?void 0:S.dbSelection)==null?void 0:j.database}),a=Le(C=>{var N,S,j;return(j=(S=(N=C==null?void 0:C.card)==null?void 0:N.dataSource)==null?void 0:S.dbSelection)==null?void 0:j.schema}),l=s==null?void 0:s.find(C=>C.id===o),u=l==null?void 0:l.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){if(!o)return!1;const C=(u==null?void 0:u.path)||[];return!(C.includes("database")&&!i||C.includes("schema")&&!a)}const{data:h,isPending:m,isLoading:p,error:g,refetch:b}=mn({queryKey:[e,o,i,a],queryFn:()=>rr(`${n.apiServiceUrl}/v1/${e}s`,(r==null?void 0:r.accessToken)||"",{connection_id:o,database_name:i,schema_name:a}),enabled:f()}),x=(v=h==null?void 0:h[`${e}s`])==null?void 0:v.map(C=>{var N;return{connectionId:l==null?void 0:l.id,connectionType:l==null?void 0:l.type,dialect:l==null?void 0:l.dialect,type:e,dbObjectType:(N=C==null?void 0:C.table_type)==null?void 0:N.toLowerCase(),id:C[`${e}_name`],database:i,schema:a,name:C[`${e}_name`]}});return{isPending:m,isLoading:p,error:g,entities:x||[],refetch:b,label:d}}function V1({title:e,message:t}){return c.jsx("div",{className:"rounded-xl border border-destructive/40 bg-destructive/10 p-4 text-destructive shadow-sm",children:c.jsxs("div",{className:"flex items-start gap-4",children:[c.jsx(Yl,{className:"h-6 w-6 flex-shrink-0"}),c.jsxs("div",{className:"flex-1",children:[c.jsx("h4",{className:"text-base font-semibold",children:e}),t&&c.jsx("p",{className:"mt-1 text-sm text-destructive/90",children:t})]})]})})}function WQe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=Ni(),[i,a]=w.useState(""),[l,u]=w.useState(""),[d,f]=w.useState("tables"),{updateDataSource:h,setSelectedConnectionId:m}=Cr(),{entities:p,isLoading:g,error:b}=UQe("table"),{dataModels:x,isPending:y,error:v}=Mte(),C=E=>{const M=s.find(P=>P.id===E);if(!M)return;const T=M.type==="upload"?"upload":M.type==="url"?"url":"database";h({...e,connectionId:E,connectionType:M.type,mode:T,dbSelection:{database:"",schema:"",entityType:"table"}}),m(E)},N=E=>{var F,A;const M=n||[],T=M.some($=>$.name===E.name&&$.type===E.type);let P;if(T)P=M.filter($=>!($.name===E.name&&$.type===E.type));else{const $={connectionId:e.connectionId,connectionType:e.connectionType,type:E.type,dbObjectType:E.dbObjectType,database:((F=e.dbSelection)==null?void 0:F.database)||"",schema:((A=e.dbSelection)==null?void 0:A.schema)||"",name:E.name,dialect:E.dialect};P=[...M,$]}t==null||t(P)},S=E=>{const M=n||[],T=M.some(F=>F.type==="model"&&F.name===E.name);let P;T?P=M.filter(F=>!(F.type==="model"&&F.name===E.name)):P=[...M,E],t==null||t(P)},j=p.filter(E=>E.name.toLowerCase().includes(i.toLowerCase())),k=x.filter(E=>E.name.toLowerCase().includes(l.toLowerCase())),_=w.useCallback(()=>{if(!t)return;const E=n||[];let M=[...E];if(d==="tables"){const P=j.filter(F=>!E.some(A=>A.name===F.name&&A.type==="table")).map(F=>{var A,$;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:F.dbObjectType,database:((A=e.dbSelection)==null?void 0:A.database)||"",schema:(($=e.dbSelection)==null?void 0:$.schema)||"",name:F.name,dialect:F.dialect}});M=[...E,...P]}else if(d==="datamodels"){const T=k.filter(P=>!E.some(F=>F.name===P.name&&F.type==="model"));M=[...E,...T]}t(M)},[d,j,k,n,e,t]);return w.useEffect(()=>{r&&r(_)},[r,_]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{className:"font-medium= text-sm",children:"Connection"}),c.jsxs(it,{value:(e==null?void 0:e.connectionId)||"",onValueChange:C,disabled:o,children:[c.jsx(rt,{className:"w-full",children:c.jsx(at,{placeholder:o?"Loading connections...":"Select connection..."})}),c.jsx(st,{children:s.map(E=>c.jsx(we,{className:"hover:bg-muted",value:E.id,children:c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx($l,{className:"h-4 w-4 flex-shrink-0"}),c.jsx("span",{className:"truncate",children:E.name}),c.jsx(qe,{variant:"secondary",className:"flex-shrink-0 text-xs",children:E.type})]})},E.id))})]})]}),(e==null?void 0:e.connectionId)&&c.jsxs(c.Fragment,{children:[e.connectionType==="upload"&&c.jsx(VQe,{}),e.connectionType==="url"&&c.jsx(HQe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(BQe,{}),c.jsx("div",{className:"space-y-4",children:c.jsx("div",{className:"space-y-2",children:c.jsxs(Ls,{defaultValue:"tables",value:d,onValueChange:E=>f(E),className:"w-full",children:[c.jsxs(Cs,{className:"grid w-full grid-cols-2",children:[c.jsxs(rn,{value:"tables",children:["Tables & Views (",j.length,")"]}),c.jsxs(rn,{value:"datamodels",children:["Data Models (",k.length,")"]})]}),c.jsxs(pr,{value:"tables",className:"space-y-2",children:[c.jsx(jn,{placeholder:"Search tables and views...",value:i,onChange:E=>a(E.target.value),className:"h-8 text-sm",disabled:g}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):b?c.jsx(V1,{title:"Error loading tables",message:b.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):j.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):j.map(E=>{const M=n.some(T=>T.name===E.name&&T.type==="table");return c.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>N(E),children:[c.jsx(un,{id:`table-${E.name}`,checked:M,onCheckedChange:()=>N(E),onClick:T=>T.stopPropagation(),disabled:g}),c.jsxs(fe,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[E.name,E.dbObjectType==="view"&&c.jsx(qe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),E.dbObjectType==="materialized view"&&c.jsx(qe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},E.name)})})]}),c.jsxs(pr,{value:"datamodels",className:"space-y-2",children:[c.jsx(jn,{placeholder:"Search data models...",value:l,onChange:E=>u(E.target.value),className:"h-8 text-sm",disabled:y}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?c.jsx(V1,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):k.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):k.map(E=>{const M=n.some(T=>T.name===E.name&&T.type==="model");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(E),children:[c.jsx(un,{id:`dataModel-${E.name}`,checked:M,onCheckedChange:()=>S(E),onClick:T=>T.stopPropagation(),disabled:y}),c.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[c.jsx(fe,{className:"cursor-pointer",children:E.name}),c.jsx("span",{className:"text-xs text-muted-foreground",children:E.description})]})]},E.name)})})]})]})})})]})]})]})}function qQe({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:s=[],isRestricted:o=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var N;const[l,u]=w.useState(""),d=w.useCallback(S=>{const j={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:S};t({...j})},[e,t]);w.useEffect(()=>{i&&!(e!=null&&e.semanticDomainId)&&d(i)},[i,e==null?void 0:e.semanticDomainId,d]);const{semanticDomains:f,isPending:h,error:m}=OQe(),p=o?f.filter(S=>s.includes(S.id)):f,{datasets:g,isPending:b,error:x}=$Qe(e==null?void 0:e.semanticDomainId),y=S=>{const j=r||[],k=j.some(E=>E.id===S.id&&E.type==="dataset");let _;if(k)_=j.filter(E=>!(E.id===S.id&&E.type==="dataset"));else{const E={id:S.id,datasetType:S.type,name:S.name||S.table,label:S.label,domainId:S.domainId,description:S.description,database:S.database,schema:S.schema,type:"dataset",connectionId:S.connectionId,connectionType:S.connectionType,dialect:S.dialect,datamodelId:S.datamodelId,sql:S.sql};_=[...j,E]}n==null||n(_)},v=g.filter(S=>S.name.toLowerCase().includes(l.toLowerCase())),C=w.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const S=r||[],k=v.filter(E=>!S.some(M=>M.id===E.id&&M.type==="dataset")).map(E=>({id:E.id,datasetType:E.type,name:E.name||E.table,label:E.label,domainId:E.domainId,description:E.description,database:E.database,schema:E.schema,type:"dataset",connectionId:E.connectionId,connectionType:E.connectionType,dialect:E.dialect,datamodelId:E.datamodelId,sql:E.sql})),_=[...S,...k];n(_)},[v,r,e==null?void 0:e.semanticDomainId,n]);return w.useEffect(()=>{a&&a(C)},[a,C]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{className:"text-sm font-medium",children:"Semantic Domain"}),c.jsxs(it,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:d,disabled:h||o&&!!i,children:[c.jsx(rt,{className:"w-full",children:c.jsx(at,{placeholder:h?"Loading semantic domains...":o&&i?"Loading domain...":"Select semantic domain...",children:((N=p.find(S=>S.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:N.label)||"Select semantic domain"})}),c.jsx(st,{children:p.map(S=>c.jsx(we,{className:"hover:bg-muted",value:S.id,children:c.jsxs("div",{className:"flex flex-col items-start",children:[c.jsx("span",{className:"font-medium",children:S.label}),c.jsx("span",{className:"text-xs",children:S.description})]})},S.id))})]}),m&&c.jsx(V1,{title:"Error loading semantic models",message:m.message})]}),(e==null?void 0:e.semanticDomainId)&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(jn,{placeholder:"Search datasets...",value:l,onChange:S=>u(S.target.value),className:"h-8 text-sm",disabled:b}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:b?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):x?c.jsx(V1,{title:"Error loading datasets",message:x.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):v.length===0?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:l?"No datasets match your search":"No datasets available"}):v.map(S=>{const j=r.some(k=>k.id===S.id&&k.type==="dataset");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>y(S),children:[c.jsx(un,{id:`dataset-${S.id}`,checked:j,onCheckedChange:()=>y(S),onClick:k=>k.stopPropagation(),disabled:b}),c.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[c.jsx(fe,{className:"cursor-pointer font-medium",children:S.label||S.name}),c.jsx("span",{className:"text-xs text-gray-500",children:S.description})]})]},S.label||S.name)})})]})]})]})}function uP({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s}){const{tokenProps:o}=Xe(),{allowedSemanticDomains:i}=o,[a,l]=w.useState([]),{updateDataSource:u}=Cr(),d=J(M=>M.isVisualEditing),f=J(M=>M.dashboard.aiContext),{setAiContext:h}=Bt(),m=w.useRef(null),[p,g]=w.useState(!1),b=i&&i.length>0,x=!b,y=b&&i.length===1?i[0]:void 0,v=w.useCallback(M=>{const T=M;u({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:T,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...T!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,u]),C=w.useCallback(M=>{u({...n,...M})},[n,u]);w.useEffect(()=>{b&&n.mode!=="semanticDomain"&&v("semanticDomain")},[b,n.mode,v]),w.useEffect(()=>{y&&!n.semanticDomainId&&C({semanticDomainId:y})},[y,n.semanticDomainId,C]),w.useEffect(()=>{e?l(s||[]):(m.current=null,g(!1))},[e,n==null?void 0:n.selectedEntities,r,u,s,n]);const N=M=>{const T=a.filter(P=>!(P.name===M.name&&P.type===M.type));l(T)},S=()=>{l([])},j=w.useCallback(M=>{l(M)},[]),k=w.useCallback(()=>{m.current&&m.current()},[]),_=w.useCallback(M=>{m.current=M,g(!0)},[]);function E(){var M,T;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const P=(M=a==null?void 0:a[0])==null?void 0:M.connectionId,F=(T=a==null?void 0:a[0])==null?void 0:T.connectionType;u({...n,connectionId:P,connectionType:F,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return c.jsx(Kr,{open:e,onOpenChange:t,children:c.jsx(zr,{className:"flex max-w-2xl flex-col",children:c.jsxs("div",{children:[c.jsxs(Br,{className:"flex-shrink-0",children:[c.jsx(Vr,{children:r==="aiContext"?"Data Context":"Select Data Source"}),c.jsx(as,{children:r==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),c.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:c.jsxs("div",{className:"space-y-4",children:[x&&c.jsx("div",{className:"space-y-2",children:c.jsx(Ls,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:v,className:"w-full",children:c.jsxs(Cs,{className:"grid w-full grid-cols-2",children:[c.jsx(rn,{value:"database",children:"Direct Source"}),c.jsx(rn,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&c.jsx(qQe,{dataSource:n,onDataSourceUpdate:C,selectedEntities:a,onSelectionChange:j,allowedDomainIds:i||[],isRestricted:b,autoSelectedDomainId:y,onRegisterSelectAll:_}),(n==null?void 0:n.mode)==="database"&&x&&c.jsx(WQe,{dataSource:n,onDataSourceUpdate:C,selectedEntities:a,onSelectionChange:j,onRegisterSelectAll:_})]})}),c.jsx(FQe,{selectedEntities:a,onDeselectEntity:N}),c.jsx(is,{className:"flex-shrink-0",children:c.jsx("div",{className:"flex w-full justify-between",children:c.jsxs("div",{className:"flex grow justify-end gap-2",children:[c.jsx(oe,{variant:"outline",onClick:k,disabled:!p,children:"Select All"}),c.jsx(oe,{variant:"outline",onClick:S,disabled:a.length===0,children:"Clear All"}),c.jsxs(oe,{variant:"outline",onClick:()=>t(!1),children:[c.jsx(St,{className:"mr-2 h-4 w-4"}),"Close"]}),c.jsxs(oe,{onClick:E,children:[c.jsx(Ar,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function YQe({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=w.useRef(null),o=async a=>{const l=Array.from(a.target.files||[]);if(l.length===0)return;const u=gl-n;if(l.length>u){We.error(`You can only attach ${gl} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=mee(l);if(f.forEach(({file:h,error:m})=>{We.error(`${h.name}: ${m}`)}),d.length>0)try{const h=await Promise.all(d.map(m=>JA(m)));e(h)}catch(h){console.error("Failed to process files:",h),We.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:s,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:o,className:"hidden",disabled:t||n>=gl}),c.jsx(oe,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=gl,title:n>=gl?`Maximum ${gl} files allowed`:"Attach files",children:c.jsx(vM,{className:"h-4 w-4 text-muted-foreground"})})]})}function GQe({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=w.useState(!1),a=w.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),l=w.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),m=f.clientX,p=f.clientY;(m<h.left||m>=h.right||p<h.top||p>=h.bottom)&&i(!1)},[]),u=w.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=w.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const m=gl-r;if(h.length>m){We.error(`You can only attach ${gl} files per message. You have ${m} slot(s) remaining.`);return}const{valid:p,errors:g}=mee(h);if(g.forEach(({file:b,error:x})=>{We.error(`${b.name}: ${x}`)}),p.length>0)try{const b=await Promise.all(p.map(x=>JA(x)));t(b),We.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),We.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:X("relative",s),onDragEnter:a,onDragLeave:l,onDragOver:u,onDrop:d,children:[e,o&&!n&&c.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-lg border-2 border-dashed border-primary bg-primary/5 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-2",children:[c.jsx(_M,{className:"h-8 w-8 text-primary"}),c.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:[gl-r," slot(s) available"]})]})})]})}const dP=w.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:l},u)=>{const[d,f]=w.useState(!1),[h,m]=w.useState(!1),[p,g]=w.useState(!1),b=w.useRef(null),x=pp();lje(),aje();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:C,setShowReasoning:N}=cS(),{queueMessage:S}=gp(),{addFileAttachment:j,removeFileAttachment:k,clearFileAttachments:_,getFileAttachments:E}=SI(),M=CI(l),T=Le(B=>B.card.dataSource),P=J(B=>B.dashboard.aiContext),F=J(B=>{var G;return(G=B.dashboard.aiContext)==null?void 0:G.selectedEntities});w.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const A=w.useCallback(()=>{const B=b.current;if(B){if(!e||e.length===0){B.style.height="10px";return}B.style.height="auto";const G=Math.min(Math.max(B.scrollHeight,10),200);B.style.height=`${G}px`}},[e]);w.useEffect(()=>{A()},[A]),w.useEffect(()=>{const B=setTimeout(()=>{A()},0);return()=>clearTimeout(B)},[A]);const $=()=>{const B=e.trim();!B&&M.length===0||(a!=="ready"?(S(l,B,M),t(""),_(l)):r({preventDefault:()=>{}}))},q=B=>{B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),$()),B.key==="@"&&(U(),f(!0))},W=w.useCallback(B=>{const G=xqe(B.nativeEvent);G.length>0&&(B.preventDefault(),G.forEach(async Z=>{const Q=await JA(Z);j(l,Q)}))},[j,l]),z=w.useCallback(B=>{B.forEach(G=>{j(l,G)})},[j,l]),I=w.useCallback(B=>{B.forEach(G=>{j(l,G)})},[j,l]),L=w.useCallback(B=>{k(l,B)},[k,l]),O=B=>{if(x.selectedEntities.some(Z=>Z.id&&Z.id===B.id||Z.name===B.name)){const Z=x.selectedEntities.filter(Q=>!(Q.id&&Q.id===B.id||Q.name===B.name));y({selectedEntities:Z})}else{const Z=[...x.selectedEntities,B];y({selectedEntities:Z})}},R=B=>{O(B)},H=B=>{var Q;if(!x.selectedEntities.some(K=>K.id&&K.id===B.id||K.name===B.name)){const K=[...x.selectedEntities,B];y({selectedEntities:K})}const Z="label"in B?B.label:B.name;t(e+`@${Z} `),f(!1),(Q=b.current)==null||Q.focus()},V=B=>{const G=x.selectedEntities.filter(K=>!(K.id&&K.id===B.id||K.name===B.name));y({selectedEntities:G});const Q=`@${"label"in B?B.label:B.name}`;e.includes(Q)&&t(e.replace(Q,"").trim())},Y=B=>{const G=new Set(B.map(K=>K.id||K.name)),Z=x.selectedEntities.filter(K=>!G.has(K.id||K.name));y({selectedEntities:Z});let Q=e;B.forEach(K=>{const ie=`@${"label"in K?K.label:K.name}`;Q=Q.replace(ie,"").trim()}),t(Q)},U=w.useCallback(()=>{x.selectedEntities.length===0&&y({selectedEntities:(P==null?void 0:P.selectedEntities)||[]})},[x.selectedEntities.length,P==null?void 0:P.selectedEntities,y]);return c.jsxs(GQe,{onFilesDropped:z,currentFileCount:M.length,disabled:s,className:"space-y-4",children:[c.jsx(AQe,{entities:x.selectedEntities,availableEntities:F||[],onRemoveEntity:V,onRemoveEntities:Y}),M.length>0&&c.jsx(yqe,{files:M,onRemove:L,showRemove:!s,className:"mb-2"}),c.jsxs("div",{className:"rounded-lg border border-border bg-background shadow-sm focus-within:ring-1 focus-within:ring-foreground/40",children:[c.jsx("textarea",{ref:b,value:e,onChange:n,onKeyDown:q,onPaste:W,onFocus:()=>{A(),i==null||i()},placeholder:"Ask a question...",className:"max-h-[200px] min-h-[40px] w-full resize-none overflow-y-auto border-0 bg-transparent px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),c.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[l==="dashboard"&&c.jsxs(gs,{open:d,onOpenChange:B=>{B&&U(),f(B)},children:[c.jsx(bs,{asChild:!0,children:c.jsx(oe,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:c.jsx(Rie,{className:"h-4 w-4 text-muted-foreground"})})}),c.jsx(xs,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:B=>B.preventDefault(),children:c.jsx(IQe,{isOpen:!0,onSelect:O,onDeselect:R,onClose:()=>{var B;f(!1),(B=b.current)==null||B.focus()},availableEntities:F||[],selectedEntities:x.selectedEntities,onTabComplete:H,onSelectAll:()=>{F&&y({selectedEntities:F})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),m(!0)}})})]}),c.jsx(YQe,{onFilesSelected:I,disabled:s,currentFileCount:M.length})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[s&&c.jsx(oe,{className:"rounded-full",size:"sm",onClick:o,children:c.jsx(Gie,{className:"size-3.5 bg-background"})}),!s&&c.jsx(oe,{disabled:!e.trim()&&M.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:$,title:a!=="ready"?"Message will be queued":void 0,children:c.jsx(J8,{className:"size-4"})})]})]})]}),c.jsx(uP,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:m,dataSource:T||cN,dialogMode:"aiContext"})]})});dP.displayName="ChatInputWithContext";function Dte({assistantType:e,className:t}){const n=cY(e),{removeFromQueue:r}=gp();return n.length===0?null:c.jsxs("div",{className:X("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(Gl,{className:"h-3 w-3"}),c.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),c.jsx("div",{className:"space-y-2",children:n.map(s=>c.jsx("div",{className:"group relative rounded-lg border border-dashed border-muted-foreground/30 bg-muted/30 px-3 py-2 text-sm animate-in fade-in-0 slide-in-from-bottom-1",children:c.jsxs("div",{className:"flex items-start justify-between gap-2",children:[c.jsx("div",{className:"flex-1 space-y-1",children:c.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:c.jsx(St,{className:"h-3 w-3"})})]})},s.id))})]})}function Ite({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=cY(e),{dequeueMessage:o}=gp();w.useEffect(()=>{if(t!=="ready"||n||!(s&&s.length>0))return;const a=o(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,s,o,r,e])}function Rte(e,t={}){const{threshold:n=50,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=w.useRef(null),[a,l]=w.useState(!0),[u,d]=w.useState(!0),[f,h]=w.useState(!1),[m,p]=w.useState(0),g=w.useRef(0),b=w.useRef(!1),x=w.useRef(0),y=w.useRef(a),v=w.useRef(void 0),C=w.useRef({key:null,count:0,length:0}),N=w.useCallback(()=>{const _=i.current;return _?_.scrollHeight-_.scrollTop-_.clientHeight:0},[]),S=w.useCallback((_={})=>{if(!i.current)return;const{force:M=!1,instant:T=!1}=_;if(!M&&!y.current||!a&&!M)return;const P=T||r==="auto"||r==="instant"?"auto":r;v.current&&cancelAnimationFrame(v.current),b.current=!0,v.current=requestAnimationFrame(()=>{if(!M&&!y.current){b.current=!1,v.current=void 0;return}const F=i.current;if(!F){b.current=!1,v.current=void 0;return}const A=F.scrollHeight;P==="smooth"&&"scrollTo"in F?F.scrollTo({top:A,behavior:P}):F.scrollTop=A,g.current=F.scrollTop,d(!0),l(!0),y.current=!0,h(!1),p(0),b.current=!1,v.current=void 0})},[r,a]),j=w.useCallback(()=>{const _=i.current;if(!_)return;const E=g.current,M=_.scrollTop,T=M-E;if(g.current=M,T<-1){v.current&&(cancelAnimationFrame(v.current),v.current=void 0),b.current=!1,y.current=!1,l(!1),d(!1);return}if(b.current)return;const P=N()<=n;d(P),l(P),y.current=P,P&&(h(!1),p(0))},[N,n]),k=w.useCallback(()=>{p(0),h(!1)},[]);return w.useEffect(()=>{y.current=a},[a]),w.useEffect(()=>{const _=i.current;if(!_||!e||e.length===0){h(!1),p(0),C.current={key:null,count:0,length:0},g.current=_?_.scrollTop:0,x.current=_?_.scrollHeight:0;return}g.current=_.scrollTop,x.current=_.scrollHeight;const E=C.current,M=e[e.length-1],T=(M==null?void 0:M.id)??(M==null?void 0:M.messageId)??(M==null?void 0:M.createdAt)??(M==null?void 0:M.timestamp)??e.length,P=Array.isArray(M==null?void 0:M.parts)?M.parts.reduce((z,I)=>I?typeof I=="string"?z+I.length:typeof I.text=="string"?z+I.text.length:typeof I.content=="string"?z+I.content.length:typeof I.value=="string"?z+I.value.length:z:z,0):typeof(M==null?void 0:M.content)=="string"?M.content.length:typeof(M==null?void 0:M.text)=="string"?M.text.length:0,F=e.length>E.count,A=T!==E.key,$=P>E.length,q=s&&(M==null?void 0:M.role)==="assistant"&&!F&&(A||$),W=o||q;if(C.current={key:T,count:e.length,length:P},a&&(F||A||$||W)){S({force:!1,instant:W});return}if(!a&&F){const z=e.length-E.count;z>0&&(h(!0),p(I=>I+z))}else!a&&$&&(h(!0),p(z=>z>0?z:1))},[e,S,a,s,o]),w.useEffect(()=>{S({instant:!0})},[S]),w.useEffect(()=>{if(typeof ResizeObserver>"u")return;const _=i.current;if(!_)return;x.current=_.scrollHeight;const E=new ResizeObserver(()=>{const M=i.current;if(!M)return;const T=x.current,P=M.scrollHeight;x.current=P,!b.current&&y.current&&P>T&&S({force:!1,instant:!0})});return E.observe(_),()=>{E.disconnect()}},[S]),w.useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:u,hasNewMessages:f,newMessageCount:m,scrollToBottom:S,handleScroll:j,resetNewMessageCount:k}}function Ate(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=w.useState(r),a=w.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),l=e.length>o,u=o>=e.length,d=w.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=w.useCallback(()=>{i(r)},[r]);return w.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:l,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}function Pte(e){var n;if(!e||e.length===0)return{hasActiveTools:!1};const t=e[e.length-1];if(!(t!=null&&t.parts))return{hasActiveTools:!1};for(const r of t.parts){if(r.type==="reasoning"&&"state"in r&&r.state==="streaming")return{hasActiveTools:!0,activeToolText:r.text||"Reasoning...",toolType:"reasoning"};if(((n=r.type)!=null&&n.startsWith("tool-")||r.type==="dynamic-tool")&&"state"in r&&["input-streaming","input-available"].includes(r.state)){const s=r,o=s.state;return{hasActiveTools:!0,activeToolText:pee(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const KQe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function ZQe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=w.useState(!1),[a,l]=w.useState(LT),[u,d]=w.useState(!1),[f,h]=w.useState(!1),[m,p]=w.useState(!1),g=n??m,{isLocalDev:b,isConsoleMode:x}=Km(),y=w.useRef(null);J(Ge=>Ge.dashboard.aiScopeTables),J(Ge=>Ge.isDashboardEditing);const v=J(Ge=>Ge.selectedSheetId),{setDataSource:C}=Cr(),{addFrame:N,setSelectedFrameId:S,setIsDashboardEditing:j}=Bt(),k=pp(),{setCurrentAIContext:_,updateSelectedEntities:E,setReasoningEffort:M,setShowReasoning:T}=cS(),{clearQueue:P}=gp(),{clearFileAttachments:F,getFileAttachments:A}=SI(),$=CI("dashboard"),q=J(Ge=>Ge.dashboard.aiContext),W=Le(Ge=>Ge.card.dataSource),{assistantProfile:z}=kte(),I=J(Ge=>Ge.handleOpenAssistantProfile),{sendMessage:L,isLoading:O,messages:R,setMessages:H,status:V,stop:Y,errorMessage:U,clearError:B}=DQe(),G=w.useCallback(Ge=>{r==null||r(Ge),n===void 0&&p(Ge)},[n,r]),Z=w.useCallback(()=>{G(!g)},[g,G]);w.useEffect(()=>{if(!g)return;function Ge(Nt){Nt.key==="Escape"&&G(!1)}return window.addEventListener("keydown",Ge),()=>{window.removeEventListener("keydown",Ge)}},[g,G]);const[Q,K]=w.useState(""),te=Ge=>{K(Ge.target.value)};function ie({sql:Ge,cardTitle:Nt,connectionId:ce,cardType:Ae,python:Te,cardConfig:Ie,dataSource:Ue,customVisualPreferences:ke}){if(!v)return;const ye={id:kr(),title:Nt||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Ae==="horizontalBar"?"y":"x"}},type:Ae,sql:Ge,python:Te,dataSource:Ue,config:Ie,connectionId:ce,customCardPreferences:ke?{url:ke.url,componentName:ke.componentName,pluginChartType:ke.pluginChartType,settings:ke.settings,type:"component"}:void 0},ne={id:kr(),cards:[ye],activeCardId:ye.id};j(!0),N(v,ne,"end"),S(ne.id)}const ue=Ge=>{Ge.preventDefault();const Nt=Q.trim();if(!Nt&&$.length===0)return;const ce=[];Nt&&ce.push({type:"text",text:Nt}),$.forEach(Ae=>{Ae.data&&ce.push({type:"file",mediaType:Ae.type,filename:Ae.name,url:`data:${Ae.type};base64,${Ae.data}`})}),L({role:"user",parts:ce}),K(""),F("dashboard"),se({force:!0})};w.useEffect(()=>{var Ge;e&&((Ge=y.current)==null||Ge.focus())},[e]),Ite({assistantType:"dashboard",status:V,isLoading:O,sendMessage:L});const{hasActiveTools:he}=Pte(R),{visibleMessages:je,hasMoreMessages:be,totalMessageCount:Me,loadMoreMessages:le,resetMessageWindow:ae}=Ate(R,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:xe,isAtBottom:de,hasNewMessages:Se,newMessageCount:ge,scrollToBottom:se,handleScroll:me,resetNewMessageCount:Oe}=Rte(je,{threshold:50,behavior:"smooth",isStreaming:O});function Pe(Ge){tt();const Nt={role:"user",parts:[{type:"text",text:Ge.title+" "+Ge.subtitle}]};L(Nt)}function Re(Ge){tt(),L({role:"user",parts:[{type:"text",text:Ge}]})}function He(Ge){tt(),L({role:"user",parts:[{type:"text",text:Ge}]}),se({force:!0})}const Ke=w.useCallback(async()=>{const Ge=JSON.stringify(R??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Ge),We.success("Conversation copied")}catch(Nt){console.error("Failed to copy conversation",Nt),We.error("Unable to copy conversation")}},[R]);function tt(){k.selectedEntities.length===0&&_({selectedEntities:(q==null?void 0:q.selectedEntities)||[]})}const mt=(Q==null?void 0:Q.length)===0&&(R==null?void 0:R.filter(Ge=>Ge.role==="user").length)===0;function gt(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function dt(){return c.jsxs(wf,{children:[c.jsx(Cf,{asChild:!0,children:c.jsx(Yc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(zm,{className:"size-3.5"})})}),c.jsxs(yu,{align:"end",children:[c.jsx(Mh,{children:"Options"}),c.jsx(Kd,{}),c.jsx(Fg,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(Fg,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(Fg,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const Ht=c.jsxs("div",{"data-role":"dashboard-assistant",className:X("flex h-full grow flex-col justify-between break-words px-6 py-4",g&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[c.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[gt(),I&&c.jsx(oe,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:I,children:(z==null?void 0:z.name)||"Default Profile"}),c.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[x&&dt(),a&&c.jsx(oe,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Ke,children:"Copy Conversation"}),c.jsx(Yc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:Z,children:g?c.jsx(yM,{className:"size-4"}):c.jsx(aC,{className:"size-4"})}),c.jsx(Yc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{H([]),P("dashboard"),B(),ae()},children:c.jsx(cC,{className:"size-4"})}),c.jsx(Yc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(St,{className:"size-4"})})]})]}),c.jsxs(nl,{"data-role":"dashboard-assistant-scroll-area",ref:xe,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:me,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[be&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(oe,{variant:"outline",size:"sm",onClick:le,className:"text-xs",children:["Load ",Math.min(5,Me-je.length)," ","more messages (",Me-je.length," ","hidden)"]})}),c.jsx(bee,{showTools:a,showSystemMessage:u,messages:je,onAddToDashboard:ie,onQuickReply:He,disableQuickReplies:O}),!he&&c.jsx(gee,{status:V,errorMessage:U})]}),c.jsx(yi,{orientation:"horizontal"})]}),e&&!de&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(oe,{onClick:()=>{se({force:!0}),Oe()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(cr,{className:"h-4 w-4"}),Se&&ge>0&&c.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:ge>9?"9+":ge})]})}),c.jsxs("div",{className:"space-y-3",children:[!z&&mt&&c.jsx(xee,{onClick:Pe,placeholders:KQe}),c.jsx("div",{children:mt&&z&&c.jsx(Ete,{seedQuestions:z.seedQuestions||[],handleSeedQuestionClick:Re})}),c.jsx(Dte,{assistantType:"dashboard",className:"mb-3"}),c.jsx(dP,{ref:y,setInput:K,stop:Y,input:Q,handleInputChange:te,handleSubmit:Ge=>{tt(),ue(Ge),se({force:!0})},isLoading:O,status:V,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx(uP,{incomingSelectedEntities:(q==null?void 0:q.selectedEntities)||[],open:f,onOpenChange:h,dataSource:W||cN,dialogMode:"aiContext"})]});return g&&s?Xn.createPortal(c.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:c.jsx("div",{className:"flex h-full w-full",children:Ht})}),s):Ht}function XQe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Bt(),o=J(d=>d.dashboard.sheets),a=J(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),l=J(d=>d.isDashboardEditing),u=J(d=>d.isVisualEditing);w.useEffect(()=>{if(!l||u)return;async function d(m){const p=m.ctrlKey||m.metaKey;p&&m.key==="c"?(await f(),We.success("Card copied to clipboard"),m.preventDefault()):p&&m.key==="v"&&(await h(),m.preventDefault())}async function f(){try{const m=n();m&&await navigator.clipboard.writeText(JSON.stringify(m))}catch(m){console.error("Failed to copy text:",m)}}async function h(){if(!a)return null;try{const m=await navigator.clipboard.readText();try{const p=JSON.parse(m);if(p!=null&&p.id){const g=tA(p),b=g.cards.findIndex(x=>x.id===g.activeCardId);b!==-1&&(g.cards[b].title=`${g.cards[b].title} (Copy)`),r(a,g),s(g.id),We.success("Card pasted from clipboard")}}catch(p){console.error("Failed to parse clipboard contents: ",p)}return m}catch(m){return console.error("Failed to paste text:",m),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[r,n,s,a,l,u,t])}function QQe(e,t){switch(e.interactionMode){case"drillToDetail":JQe(e,t);break;case"drillThrough":eJe(e,t);break;case"drillToURL":tJe(e);break;case"inlineDrill":console.warn("Inline drill execution not yet implemented");break;case"clickFilter":case"drillDown":case"dynamicDrill":break;default:console.warn("Unknown interaction mode:",e.interactionMode)}}function JQe(e,t){var l;const{targetInsightId:n,contextMode:r,displayMode:s,filterGroups:o}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=o.flatMap(u=>u.filters);break;case"full":{const u=((l=t.getCurrentFilters)==null?void 0:l.call(t))||[],d=o.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}s==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function eJe(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:s,sourceCardId:o}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=s.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",l=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:l,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:l,filters:i,contextMode:r})}function tJe(e){const{url:t}=e;if(!t){console.warn("drillToURL event missing url");return}try{new URL(t)}catch(n){console.error("Invalid URL:",t,n);return}window.open(t,"_blank","noopener,noreferrer")}function nJe({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(Kr,{open:e,onOpenChange:t,children:c.jsxs(zr,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(Br,{children:[c.jsx(Vr,{children:i||"Insight Detail"}),c.jsx(as,{children:a||"View detailed insight data with applied filters"})]}),c.jsx($X,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(VX,{insightId:n,filters:r,contextMode:o}):c.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function rJe(){const e=Pt(C=>C.interactionStates),t=Pt(C=>C.setInteractionState),n=Pt(C=>C.clearLastInteractionEvent),r=Pt(C=>C.replaceCardWithInsight),s=Pt(C=>C.setPendingDrillThrough),o=Pt(C=>C.pendingDrillThrough),i=Pt(C=>C.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Bt(),{selectDashboard:u}=Dx(),d=J(C=>C.dashboard),f=J(C=>C.filterValues),{data:h,isLoading:m}=mB((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[p,g]=w.useState({open:!1,insightId:""}),b=HX(p.insightId,{enabled:p.open&&!!p.insightId}),x=w.useRef(new Set),y=w.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:C,filters:N,contextMode:S})=>{g({open:!0,insightId:C,filters:N,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:S})},replaceCardContent:({cardId:C,insightId:N,filters:S,contextMode:j})=>{r(C,N,S,j)},getCurrentFilters:()=>f||[],navigateWithDrill:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:C,contextMode:N,sourceDashboardId:S,sourceDashboardTitle:j,targetDashboardId:k})=>{const E={sourceCardId:Ra,interactionMode:"clickFilter",filterGroups:[{filters:C}]},M={...ai(),appliedClickFilters:[E],contextMode:N,sourceDashboardId:S,sourceDashboardTitle:j,targetDashboardId:k};t(Ra,M)}}),[a,r,f,l,d,s,t]);w.useEffect(()=>{Object.entries(e).forEach(([C,N])=>{if(N!=null&&N.lastInteractionEvent){const S=N.lastInteractionEvent,j=`${C}-${S.interactionMode}-${S.sourceCardId}-${Date.now()}`;if(x.current.has(j))return;x.current.add(j);try{QQe(S,y)}catch(k){console.error("Error executing interaction event:",k)}finally{n(C),setTimeout(()=>{x.current.delete(j)},5e3)}}})},[e,n,y]),w.useEffect(()=>{if(!(!o||!h||m))try{u(h),l(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(C){console.error("[DrillThrough] Error during automatic navigation:",C),i()}},[o,h,m,u,l,i]);const v=()=>{g({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(nJe,{open:p.open,onOpenChange:v,insightId:p.insightId,filters:p.filters,filterDefinitions:p.filterDefinitions,contextMode:p.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&m&&c.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border bg-background p-6 shadow-lg",children:[c.jsx(yn,{className:"h-8 w-8 animate-spin text-primary"}),c.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function sJe(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=oJe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function oJe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function iJe(e){return e?`Back to ${e}`:"Back"}function aJe(){var x,y,v,C,N;const e=Pt(S=>S.interactionStates[Ra]),t=J(S=>S.actions.goBackFromDrill),n=J(S=>S.actions.clearDrillContext),{selectDashboard:r}=Dx(),[s,o]=w.useState({x:16,y:16}),[i,a]=w.useState(!1),l=w.useRef({x:0,y:0});w.useEffect(()=>{if(!i)return;const S=k=>{o({x:k.clientX-l.current.x,y:k.clientY-l.current.y})},j=()=>{a(!1)};return document.addEventListener("mousemove",S),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",S),document.removeEventListener("mouseup",j)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((C=(v=(y=(x=e==null?void 0:e.appliedClickFilters)==null?void 0:x[0])==null?void 0:y.filterGroups)==null?void 0:v[0])==null?void 0:C.filters)||[],h=u?{id:u,title:d||"Previous Dashboard",description:"",isPrivate:!1,isPublic:!1,version:"",createdBy:null,createdByTenantUser:"",tenantId:"",projectId:"",createdAt:"",updatedAt:"",lastModified:"",lastModifiedBy:"",createdByUser:null,createdByTenantUserRel:{name:"",email:""},permissions:{canEdit:!0,canShare:!0,canDelete:!0},ownership:{status:"private",isOwner:!0,sharedCount:0,createdBy:{type:"user",userId:"",name:"",email:""}}}:null;if(!e||!((N=e.appliedClickFilters)!=null&&N.length))return null;const m=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(S){console.error("[DrillBack] Error during back navigation:",S)}},p=()=>{n()},g=S=>{S.target.closest("button")||(a(!0),l.current={x:S.clientX-s.x,y:S.clientY-s.y})};sJe(f);const b=iJe(d);return c.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:c.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:g,style:{cursor:i?"grabbing":"grab"},children:[c.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((S,j)=>{const k=S.field.label||S.field.name,_=String(S.value);return c.jsxs(qe,{variant:"secondary",className:"pointer-events-none text-xs",children:[k," = ",_]},j)})})]}),c.jsx(oe,{variant:"ghost",size:"sm",onClick:p,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(St,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(oe,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(R8,{className:"mr-2 h-4 w-4"}),b]})})]})})}function Fte(){var Me;const{showAssistant:e,tokenProps:t}=Xe(),{preferences:n,isConsoleMode:r}=Km(),s=((Me=n==null?void 0:n.cardDisplay)==null?void 0:Me.mode)==="print",o=w.useRef(null),i=w.useRef(null),[a,l]=w.useState(!1),{handleDragStart:u,isDraggingRef:d,getStyle:f,getPositionClasses:h}=f8e({initialPosition:"bottom-right"}),m=Fd(le=>le.setFullscreen),p=Fd(le=>le.setPanelOpen),g=Fd(le=>le.setContainer),b=oY("dashboard"),x=iY(),y=aY("dashboard"),v=b.isOpen,C=x==="dashboard",N=J(le=>le.isVisualEditing),S=J(le=>le.themeStyle),j=J(le=>{var ae;return(ae=le.dashboard)==null?void 0:ae.sheets}),k=J(le=>le.showFilters),_=J(le=>le.isDashboardEditing),E=J(le=>le.selectedSheetId),M=J(le=>{var ae,xe;return((xe=(ae=le.dashboard)==null?void 0:ae.summary)==null?void 0:xe.position)||"top"}),T=J(le=>{var ae;return(ae=le.dashboard)==null?void 0:ae.id}),P=J(le=>le.isDashboardPanelOpen),F=J(le=>le.actions.setIsDashboardPanelOpen),{getDefaultSheetId:A,setDefaultSheetId:$,clearDefaultSheetId:q}=_8(T),[W,z]=w.useState(null);CC(qt.DASHBOARD);const{setSelectedSheetId:I,setSheetTitle:L,addSheet:O,setSheets:R}=Bt();XQe(i);const{setActiveAssistantType:H}=cS();w.useEffect(()=>{if(T){const le=A();z(le)}},[T,A]),w.useEffect(()=>{v?H("dashboard"):x==="dashboard"&&m(null)},[v,H,x,m]),w.useEffect(()=>{var le;v||(le=o.current)==null||le.resize(0)},[v]);function V(le){var ae,xe;le?((ae=o.current)==null||ae.resize(40),p("dashboard",!0),H("dashboard")):(p("dashboard",!1),m(null),(xe=o.current)==null||xe.resize(0),H(null))}function Y(){const le={id:kr(),title:"New Sheet"};O(le),I(le.id)}function U(le,ae){if(!T)return;W===le?(q(),z(null),We.success("Default sheet cleared")):($(le),z(le),We.success(`"${ae}" set as default sheet`))}function B(le){var ae;le<1?(p("dashboard",!1),m(null),H(null),(ae=o.current)==null||ae.resize(0)):(v||p("dashboard",!0),H("dashboard"))}function G(){return(S==null?void 0:S.canvasTheme)==="muted"||!(S!=null&&S.canvasTheme)?"hsl(var(--semaphor-muted))":(S==null?void 0:S.canvasTheme)==="clear"?"":S==null?void 0:S.canvasTheme}const Z=(le,ae)=>{le.dataTransfer.setData("tabIndex",ae.toString())},Q=le=>{le.preventDefault()},K=(le,ae)=>{const xe=le.dataTransfer.getData("tabIndex");if(xe===ae.toString())return;const de=Array.from(j||[]),[Se]=de.splice(parseInt(xe),1);de.splice(ae,0,Se),R(de)},te=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail,ie=e===!0&&!s&&!v&&!N&&!k;function ue(){var le,ae;if(j&&j.length>1||_)return c.jsxs(Cs,{role:"tab-list",className:"flex h-12 w-0 min-w-full items-center justify-start gap-2 overflow-x-auto rounded-none border-b border-b-muted bg-transparent px-3",children:[r&&te&&c.jsx(oe,{style:{borderRadius:S==null?void 0:S.controlInputRadius},variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{F(!P)},className:"h-8 shrink-0 p-2",children:P?c.jsx($8,{className:"h-4 w-4"}):c.jsx(L8,{className:"h-4 w-4"})}),j==null?void 0:j.map((xe,de)=>{const Se=E===xe.id,ge=W===xe.id;return c.jsxs(rn,{draggable:!0,onDragStart:se=>Z(se,de),onDragOver:Q,onDrop:se=>K(se,de),style:{borderRadius:S==null?void 0:S.controlInputRadius},onClick:()=>I(xe.id),className:"flex shrink-0 items-center gap-1 border px-2 py-1",value:xe.id,children:[c.jsx(Zb,{enabled:_&&Se,text:xe.title,onSave:se=>L(xe.id,se),children:xe.title},xe.id),!_&&Se&&c.jsx("div",{title:ge?"Clear default sheet":"Set as default sheet",children:c.jsx(SM,{className:X("ml-1 size-3 cursor-pointer transition-all",ge?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:se=>{se.stopPropagation(),U(xe.id,xe.title||"Sheet")}})}),_&&Se&&j.length>1&&c.jsx(St,{className:"ml-1 size-3",onClick:()=>l(!0)})]},xe.id)}),_&&c.jsx("div",{style:{borderRadius:(ae=(le=S==null?void 0:S.chart)==null?void 0:le.options)==null?void 0:ae.borderRadius},className:"flex h-7 shrink-0 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:Y,children:c.jsx(Mr,{className:"size-3"})})]})}function he(){return c.jsx("div",{ref:i,style:{},className:"grow",children:j==null?void 0:j.map(le=>c.jsx(pr,{style:{backgroundColor:G()},className:X("mt-0",{}),value:le.id,children:c.jsx(Fze,{sheet:le})},le.id))})}function je(){var le;return c.jsxs(Ls,{"data-role":"dashboard-tabs-container",className:X("relative flex h-full flex-col",S==null?void 0:S.dashboardTabsContainer),onValueChange:ae=>{I(ae)},value:E||((le=j==null?void 0:j[0])==null?void 0:le.id),children:[ue(),M==="top"&&c.jsx(q_,{}),c.jsx(nl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:he()}),M==="bottom"&&c.jsx(q_,{}),c.jsx(h8e,{open:a,setOpen:l})]})}const be=w.useCallback(le=>{g("dashboard",le)},[g]);return j?c.jsxs(c.Fragment,{children:[c.jsx(rJe,{}),c.jsx(aJe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(QQ,{className:X("flex-1 basis-0 overflow-y-auto transition-opacity",C&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(tT,{children:je()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx(d8e,{open:v,onTabClick:V,withHandle:!0,disabled:!v}),c.jsx(tT,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:B,defaultSize:v?40:0,ref:o,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(ZQe,{open:v,setOpen:V,isFullscreen:C,onFullscreenChange:le=>m(le?"dashboard":null),fullscreenContainer:y})})})]})]}),c.jsx("div",{ref:be,className:X("absolute inset-0",!C&&"pointer-events-none")}),ie&&c.jsx("div",{className:X("absolute z-50 transition-all duration-300 ease-in-out",h().horizontal,h().vertical),style:f(),children:c.jsx(oe,{size:"sm",variant:"outline",className:"h-12 w-12 cursor-grab rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted active:cursor-grabbing",onClick:()=>{d.current||V(!0)},onMouseDown:u,onTouchStart:u,title:"Open Assistant (drag to move)",children:c.jsx(lC,{className:"h-5 w-5"})})})]})]}):null}function fP({children:e}){return c.jsx(la,{style:{height:"100%",width:"100%"},children:c.jsx(Yoe,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(Ln,{delayDuration:0,children:e})})})}function Ote({children:e,preferences:t}){const{currentUser:n}=$s(),r=w.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return c.jsx(W7.Provider,{value:r,children:c.jsx(hA,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function lJe(e=2e3,t=500){const n=Cie(),[r,s]=w.useState(!1),[o,i]=w.useState(!1),a=w.useRef(null);return w.useEffect(()=>{const l=setTimeout(()=>s(!0),e);return()=>clearTimeout(l)},[e]),w.useEffect(()=>{if(r){if(n>0){i(!1),a.current&&(clearTimeout(a.current),a.current=null);return}return a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i(!0)},t),()=>{a.current&&clearTimeout(a.current)}}},[r,n,t]),o}function hP({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=lJe(e,t);return w.useEffect(()=>(s&&(window.__SEMAPHOR_READY__={ready:!0,type:n,componentId:r||null,timestamp:Date.now()}),()=>{window.__SEMAPHOR_READY__={ready:!1,type:n,componentId:r||null,timestamp:Date.now()}}),[s,n,r]),c.jsx("div",{id:"idle-check","aria-hidden":"true",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s?"ready":""})}function $te(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(sa,{FallbackComponent:FS,children:c.jsxs(oM,{dashboardProps:e,children:[c.jsx(hP,{componentType:"dashboard",componentId:e.id}),c.jsx(fP,{children:c.jsx(Ote,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(NI,{...e,type:"dashboard",children:c.jsx(Fte,{})})})})})]})})}function K6(e,t){return e.map(n=>({...n,fieldScope:t}))}function cJe(e){const t=new Map;return e.forEach(n=>{const r=`${n.name}-${n.role||"unknown"}`;t.has(r)||t.set(r,n)}),Array.from(t.values())}function Z6(e){if(ic(e)||Qx(e))return e.expression}function mP(){const{columns:e,columnGroups:t,isLoading:n,hasError:r,error:s,refetch:o}=XD(),i=Le(g=>g.frame.calculatedFields),a=Le(g=>g.card.config),l=w.useMemo(()=>e.filter(g=>g.fieldScope==="domain"),[e]),u=w.useMemo(()=>e.filter(g=>g.fieldScope!=="domain"),[e]),d=w.useMemo(()=>i!=null&&i.length?K6(i,"dashboard"):[],[i]),f=w.useMemo(()=>{const g=new Map;return d.forEach(b=>{const x=`${b.name}-${b.role||"unknown"}`;g.set(x,b)}),g},[d]),h=w.useMemo(()=>{const g=((a==null?void 0:a.metricColumns)||[]).filter(ic),b=((a==null?void 0:a.groupByColumns)||[]).filter(Qx),y=cJe([...g,...b]).filter(v=>{const C=`${v.name}-${v.role||"unknown"}`,N=f.get(C);if(!N)return!0;const S=Z6(v),j=Z6(N);return S&&j?S!==j:!0});return K6(y,"card").map(v=>({...v,id:`card-source-${v.id}`}))},[a==null?void 0:a.groupByColumns,a==null?void 0:a.metricColumns,f]),m=w.useMemo(()=>[...l,...d,...h,...u],[h,u,d,l]),p=w.useMemo(()=>t.filter(g=>g.entityId!==Gz),[t]);return{columns:e,columnGroups:p,rawColumnGroups:t,columnFields:u,domainCalculatedFields:l,dashboardCalculatedFields:d,cardCalculatedFields:h,scopedFields:m,isLoading:n,hasError:r,error:s,refetch:o}}function pP(e){const{tokenProps:t,authToken:n}=Xe(),r=t==null?void 0:t.apiServiceUrl;return mn({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return rr(s,n.accessToken)},enabled:!!e&&!!(n!=null&&n.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:s=>Math.min(1e3*2**s,3e4)})}function Lte(e,t,n){if(t==="source")return{isValid:!0};const r=vr(e.dataType);if(n==="detailTable"&&t!=="detailColumns"&&t!=="sortBy")return{isValid:!1,reason:"Detail tables only accept columns"};if(n==="kpi"){if(t==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(t==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function zte(e,t,n,r,s){if(e!=="kpi"||s.length<3)return;const o=(t==null?void 0:t.groupByColumns)&&t.groupByColumns.length>0,i=s.some(a=>a.comparisonType&&a.comparisonType!=="none");!o&&!i||n(r,{groupByColumns:[],metricColumns:s.map(a=>({...a,comparisonType:"none",targetValue:void 0}))})}function uJe(e,t){return(e||[]).map(n=>({...n,id:t(n),label:n.label!==void 0?n.label:n.name}))}const Bte=e=>{var F;const t=(F=e==null?void 0:e.dataSource)==null?void 0:F.semanticDomainId,{data:n}=pP(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=Cr(),h=Le(A=>A.card.type),m=e==null?void 0:e.id,p=(A,$)=>{if(A.id)return A.id;const q=A.qualifiedEntityName||A.entityName||$;return`${$}-${q}-${A.name}`},g=w.useCallback(A=>{if(!(e!=null&&e.config))return[];switch(A){case"groupBy":return(e.config.groupByColumns||[]).map($=>({...$,id:p($,"groupBy"),label:$.label!==void 0?$.label:$.name}));case"metrics":return(e.config.metricColumns||[]).map($=>({...$,id:p($,"metrics"),label:$.label!==void 0?$.label:$.name}));case"pivotBy":return(e.config.pivotByColumns||[]).map($=>({id:p($,"pivotBy"),name:$.name,dataType:$.dataType,label:$.label!==void 0?$.label:$.name,qualifiedEntityName:$.qualifiedEntityName,entityId:$.entityId,entityName:$.entityName,entityType:$.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map($=>({id:p($,"sortBy"),name:$.name,dataType:$.dataType,label:$.label!==void 0?$.label:$.name,qualifiedEntityName:$.qualifiedEntityName,entityId:$.entityId,entityName:$.entityName,entityType:$.entityType,direction:$.direction}));case"detailColumns":return uJe(e.config.detailColumns,$=>p($,"detailColumns"));case"source":return[];default:return[]}},[e]),b=w.useCallback((A,$)=>{if(m)switch(A){case"groupBy":{r(m,{groupByColumns:$});break}case"metrics":{r(m,{metricColumns:$});break}case"pivotBy":{r(m,{pivotByColumns:$});break}case"sortBy":{r(m,{sortByColumns:$});break}case"detailColumns":{r(m,{detailColumns:$});break}}},[m,r]),x=w.useCallback((A,$,q)=>{if(!m)return;const W=g(A),z=W[$];if(z)switch(A){case"groupBy":s(m,z.id,{label:q});break;case"metrics":o(m,z.id,{label:q});break;case"pivotBy":i(m,z.id,{label:q});break;case"sortBy":a(m,z.id,{label:q});break;case"detailColumns":{const I=W.map((L,O)=>O===$?{...L,label:q}:L);r(m,{detailColumns:I});break}}},[m,g,s,o,i,a,r]),y=w.useCallback((A,$)=>{if(!m)return;const W=g("metrics")[A];W&&o(m,W.id,{aggregate:$,label:cW(W.name,$)})},[m,g,o]),v=w.useCallback((A,$,q,W="groupBy")=>{if(!m)return;const z=g(W),I=z[A];if(!I)return;const L={dateFormat:$,customFormat:$==="custom"&&q?q:void 0};if(W==="detailColumns"){const O=z.map((R,H)=>H===A?{...R,...L}:R);r(m,{detailColumns:O});return}s(m,I.id,L)},[m,g,r,s]),C=w.useCallback((A,$)=>{if(!m)return;const W=g("groupBy")[A];W&&s(m,W.id,{granularity:$})},[m,g,s]),N=w.useCallback((A,$)=>{if(!m)return;const W=g("metrics")[A];W&&o(m,W.id,{aliasTemplate:$})},[m,g,o]),S=w.useCallback((A,$)=>{if(console.log("handleValueAliasesChange",A,$),!m)return;console.log("handleValueAliasesChange",A,$);const W=g("metrics")[A];W&&(console.log("handleValueAliasesChange",$),o(m,W.id,{valueAliases:$}))},[m,g,o]),j=w.useCallback((A,$)=>{if(!m)return;const W=g("metrics")[A];W&&o(m,W.id,{comparisonType:$,...$!=="target"?{targetValue:void 0}:{}})},[m,g,o]),k=w.useCallback(A=>{m&&r(m,{showTrendline:A})},[m,r]),_=w.useCallback(A=>{m&&r(m,{trendlineWindow:A})},[m,r]),E=w.useCallback(A=>{m&&r(m,{trendlineGranularity:A})},[m,r]),M=w.useCallback((A,$)=>{if(!m)return;const W=g("metrics")[A];W&&o(m,W.id,{targetValue:$})},[m,g,o]),T=w.useCallback(async A=>{var R;if(!m)return;const $=[...g("groupBy"),...g("pivotBy"),...g("metrics"),...g("sortBy"),...g("detailColumns")],q=A,W=zCe(q,$,{joinPlan:(R=e==null?void 0:e.config)==null?void 0:R.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!W.isValid){W.showError&&iW();return}const z=HCe(q,$,h);if(!z){We.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const I=Lte(q,z,h);if(!I.isValid){We.error("Invalid Field Type",{description:I.reason,position:"top-center",duration:3e3});return}const L=g(z);if(aW(q,L))return;const O=uW(q,z,L);if(O){const H=[...L,O];b(z,H),z==="metrics"&&zte(h,e==null?void 0:e.config,r,m,H)}},[m,e==null?void 0:e.config,g,b,t,n,h,r]),P=w.useCallback((A,$)=>{if(!m)return;const W=g(A)[$];if(W){if(A!=="sortBy"){const z=g("sortBy"),I=z.filter(L=>!(L.name===W.name&&L.qualifiedEntityName===W.qualifiedEntityName));I.length!==z.length&&r(m,{sortByColumns:I})}switch(A){case"groupBy":l(m,W.id);break;case"metrics":u(m,W.id);break;case"pivotBy":d(m,W.id);break;case"sortBy":f(m,W.id);break;case"detailColumns":{r(m,{detailColumns:(g("detailColumns")||[]).filter((z,I)=>I!==$)});break}}}},[m,g,l,u,d,f,r]);return{getFieldsForContainer:g,setFieldsForContainer:b,updateLabel:x,handleAggregationChange:y,handleDateFormatChange:v,handleGranularityChange:C,handleAliasTemplateChange:N,handleValueAliasesChange:S,removeField:P,handleFieldClick:T,handleMetricComparisonChange:j,handleKpiShowTrendlineChange:k,handleKpiTrendlineWindowChange:_,handleKpiTrendlineGranularityChange:E,handleMetricTargetValueChange:M,cardType:h}};function hN(e,t){var Ke,tt,mt,gt,dt,Ht,Ge,Nt;const{tokenProps:n}=Xe(),r=ws(),s=Xe().authToken||e,o=Le(ce=>ce.selectedConnectionId),i=Le(ce=>ce.card),{queryKey:a}=ame(i),l=Le(ce=>ce.selectedDatamodelId),u=Le(ce=>ce.isDevMode),d=Le(ce=>ce.selectedDatabaseName),f=Le(ce=>ce.selectedSchemaName),h=Le(ce=>ce.selectedTableName),m=Le(ce=>ce.actions.setSelectedConnectionId),p=Le(ce=>ce.actions.setSelectedDatamodelId),g=Le(ce=>ce.actions.setSelectedDatabaseName),b=Le(ce=>ce.actions.setSelectedSchemaName),x=Le(ce=>ce.actions.setSelectedTableName);Le(ce=>ce.actions.setCardSql);const{setQueryConfig:y}=Cr();function v(ce){var ke;if(!o||!ce)return!1;const Ae=((ke=_==null?void 0:_.capabilities)==null?void 0:ke.path)||[],Te=Ae.includes("database"),Ie=Ae.includes("schema");return!(!Ae.includes("table")||Te&&(!d||d==="NA")||Ie&&!f)}function C(ce){var Ae;return!o||!ce?!1:!!((Ae=_==null?void 0:_.capabilities)!=null&&Ae.path.includes("database"))}const{refetchConnections:N,connectionsData:S,isConnectionsLoading:j,isConnectionsError:k,selectedConnection:_}=Ni(e),{refetch:E,data:M,isLoading:T,isError:P}=mn({queryKey:["models",o],queryFn:()=>rr(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),F=_==null?void 0:_.type,A=((Ke=_==null?void 0:_.capabilities)==null?void 0:Ke.path.includes("schema"))??!1,$=((tt=_==null?void 0:_.capabilities)==null?void 0:tt.path.length)===1&&((mt=_==null?void 0:_.capabilities)==null?void 0:mt.path[0])==="table",q=$,{data:W,isLoading:z,isFetching:I,isError:L,refetch:O}=mn({queryKey:["databases",o],queryFn:()=>rr(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:C(F)}),{data:R,isLoading:H,isFetching:V,isError:Y,refetch:U}=mn({queryKey:["schemas",o,d],queryFn:()=>rr(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&A&&d!=="NA"}),{data:B,isLoading:G,isFetching:Z,isError:Q,refetch:K}=mn({queryKey:["tables",o,d,f],queryFn:()=>rr(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(F)}),{columns:te,isColumnsLoading:ie,isColumnsFetching:ue,isColumnsError:he,refetchColumns:je}=dW(e);w.useEffect(()=>{$&&(g(""),b(""),p(""),F==="API"&&x("api"))},[F,x,g,b,p,$]);const be=(_==null?void 0:_.type)==="API"?(gt=_==null?void 0:_.type)==null?void 0:gt.toLowerCase():h||"",Me=A&&f||"";function le(ce){x(ce),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function ae(ce){b(ce),x("")}function xe(ce){g(ce==="none"?"":ce),b(""),x(""),ce!=="none"&&ce!==""&&p("")}function de(ce){m(ce)}function Se(ce){p(ce==="none"?"":ce),ce!=="none"&&ce!==""&&g("")}W&&((dt=W==null?void 0:W.databases)==null?void 0:dt.length)>0,R&&((Ht=R==null?void 0:R.schemas)==null?void 0:Ht.length)>0;const ge=S==null?void 0:S.connections.map(ce=>({id:ce.id,name:ce.name,type:ce.type})),se=(Ge=M==null?void 0:M.datamodels)==null?void 0:Ge.map(ce=>({id:ce.id,name:ce.name})),me=W==null?void 0:W.databases.map(ce=>({id:ce.database_name,name:ce.database_name})),Oe=R==null?void 0:R.schemas.map(ce=>({id:ce.schema_name,name:ce.schema_name})),Pe=B==null?void 0:B.tables.map(ce=>({id:ce.table_name,name:ce.table_name})),Re=(Nt=M==null?void 0:M.datamodels.find(ce=>ce.id===l))==null?void 0:Nt.name,He=_!=null&&_.capabilities?tw({schemaName:Me,tableName:be,modelName:Re,databaseName:d||"",capabilities:_.capabilities}):be;return{connectionItems:ge,selectedConnectionId:o,selectedConnection:_,isConnectionsLoading:j,isConnectionsError:k,modelItems:se,selectedDatamodelId:l,selectedDatamodelName:Re,isModelsLoading:T,isModelsError:P,selectedDatabaseName:d,databaseItems:me,isDatabasesLoadingOrFetching:z||I,isDatabaseError:L,schemaItems:Oe,selectedSchemaName:f,isSchemaLoadingOrFetching:H||V,isSchemaError:Y,tableItems:Pe,selectedTableName:h,isTableLoadingOrFetching:G||Z,isTableError:Q,columns:te,isColumnsLoadingOrFetching:ie||ue,isColumnsError:he,isNonDbConnection:q,connectionType:F,tableName:be,formattedTableName:He,schemaName:Me,refetchConnections:N,refetchModels:E,refetchDatabases:O,refetchSchemas:U,refetchTables:K,refetchColumns:je,handleConnectionChange:de,handleDatamodelChange:Se,handleDatabaseChange:xe,handleSchemaChange:ae,handleTableChange:le}}function vv(e){return`${e}-${kr()}`}function X6(e,t){const n=gi(e.replace(/_/g," "));switch(t){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function dJe(e,t){const n=gi(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function gP(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return{tableName:void 0,schemaName:void 0,databaseName:void 0,connectionId:e==null?void 0:e.connectionId,connectionType:e==null?void 0:e.connectionType};const t=e.selectedEntities[0];return{tableName:t==null?void 0:t.name,schemaName:t==null?void 0:t.schema,databaseName:t==null?void 0:t.database,connectionId:e.connectionId,connectionType:e.connectionType}}function Vte(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Hte(){const e=Le(j=>j.sqlGen),t=Le(j=>j.isDevMode),n=Le(j=>j.card.dataSource),r=Le(j=>{var k,_;return(_=(k=j.card)==null?void 0:k.queryConfig)==null?void 0:_.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=gP(n),a=Vte(n),l=Le(j=>j.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:m,setIsShowingVisual:p}=Cr(),{modelItems:g,selectedDatamodelName:b}=hN(),{selectedConnection:x}=Ni(),y=x==null?void 0:x.capabilities,v=j=>({column_name:j.name,data_type:j.dataType,label:j.label,description:j.description});return{handleDevModeFieldClick:j=>{var _;if(!t)return;const k=v(j);if(t&&a&&s&&y){const E=WT(k,e);m(E);const M=(_=g==null?void 0:g.find(P=>P.id===l))==null?void 0:_.name,T=UT(E,o||"",s,M||"",i||"",y,j.qualifiedEntityName);T&&(f(T),h(!0))}else if(!t){if(_x(k.data_type))if(r&&r.length>0){const E={...k,role:"groupby",id:vv(k.column_name),name:k.column_name,type:k.data_type};d(E)}else{const E={...k,role:"metric",id:vv(k.column_name),name:k.column_name,label:X6(k.column_name,"COUNT"),type:k.data_type,aggregate:"COUNT"};u(E)}if(Xi(k.data_type)){const E={...k,role:"groupby",id:vv(k.column_name),name:k.column_name,type:k.data_type,label:dJe(k.column_name,"month"),granularity:"month"};d(E)}if(Zi(k.data_type)){const E={...k,role:"metric",id:vv(k.column_name),name:k.column_name,label:X6(k.column_name,"SUM"),type:k.data_type,aggregate:"SUM"};u(E)}}},handleShowSample:()=>{if(!a||!s||!y){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const j=tw({schemaName:o||"",tableName:s,modelName:b,databaseName:i||"",capabilities:y});p(!1);const _=(x==null?void 0:x.type)==="MSSQL"?`SELECT top 10 * FROM ${j}`:`SELECT * FROM ${j} LIMIT 10`;f(_),h(!0)},handleShowCount:()=>{if(!a||!s||!y){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const j=tw({schemaName:o||"",tableName:s,modelName:b,databaseName:i||"",capabilities:y});f(`SELECT COUNT(*) as count FROM ${j}`),h(!0)},isNumberField:j=>Zi(j.dataType)}}function fJe(e){const t=e.qualifiedFieldName,r=(e.qualifiedEntityName||e.qualifiedFieldName.split(".").slice(0,-1).join(".")).split(".").map(o=>hb(o)).join("."),s=hb(e.name);return{qualifiedColumnName:t,qualifiedTableName:r,formattedColumnName:s}}function Ute(e){const t=e;return{name:e.name,qualifiedFieldName:e.qualifiedFieldName,qualifiedEntityName:e.qualifiedEntityName,entityName:e.entityName,entityId:e.entityId,entityType:e.entityType,dataType:e.dataType,expression:t.expression,calculatedFormula:t.calculatedFormula}}function Wte(e,t){if(!(!e&&!t))return{semanticDomainId:e==null?void 0:e.semanticDomainId,selectedEntities:(e==null?void 0:e.selectedEntities)||[],connectionId:(e==null?void 0:e.connectionId)||(t==null?void 0:t.connectionId),connectionType:(e==null?void 0:e.connectionType)||(t==null?void 0:t.connectionType)}}function qte(e){var t,n;return e?!!(e.entityName===ec||e.expression||(n=(t=e.calculatedFormula)==null?void 0:t.inputFields)!=null&&n.length):!1}function Yte(){const e=J(l=>l.dashboard.filters)||[],t=J(l=>l.selectedSheetId),n=J(l=>l.actions.addFilter),r=J(l=>l.actions.removeFilter),{removeFilterValues:s}=Bt(),o=Le(l=>l.card.dataSource),{selectedConnection:i}=Ni();function a(l,u="sheet"){const{qualifiedColumnName:d,qualifiedTableName:f,formattedColumnName:h}=fJe(l);let m;if(u==="sheet"&&t?m=Xke(e,d,f,t):m=e==null?void 0:e.find(p=>km(p.column)===km(d)),m)s(m.id),r(m.id);else{const p=kr(),g=Ute(l),b=Wte(o,{connectionId:i==null?void 0:i.id,connectionType:i==null?void 0:i.type}),x=qte(g),y=u==="sheet"&&t?[t]:void 0;return n({id:p,location:u,column:d,title:l.label||l.name,dataType:l.dataType,qualifiedTableName:f,connectionId:(i==null?void 0:i.id)||"",operation:"in",applyToSheetIds:y,sql:x?"":rZ(l.dataType,f,h),fieldMeta:g,semanticContext:b}),p}}return{assignFilter:a}}function hJe({column:e}){const[t,n]=w.useState(!1),r=Le(y=>y.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=gP(r),a=Le(y=>y.selectedDatamodelId),l=Le(y=>y.sqlGen),{modelItems:u,selectedConnection:d}=hN(),f=d==null?void 0:d.capabilities,h=Le(y=>y.actions.setSqlGen),m=Le(y=>y.actions.setCardSql),p=Le(y=>y.actions.setRunSql),g=Vte(r);function b(y,v){var k,_;if(!g||!s){console.warn("Cannot generate SQL: missing table metadata");return}const C=WT(y,l,v),N=(k=u==null?void 0:u.find(E=>E.id===a))==null?void 0:k.name;if(h(C),!f){console.warn("Cannot generate SQL: missing connection capabilities");return}const S=(_=y.qualifiedFieldName)==null?void 0:_.split(".").slice(0,-1).join("."),j=UT(C,o||"",s,N||"",i||"",f,S);j&&(m(j),p(!0)),n(!1)}function x(){return c.jsxs("ul",{className:"text-xs",children:[c.jsx("li",{onClick:()=>b(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),c.jsx("li",{onClick:()=>b(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),c.jsx("li",{onClick:()=>b(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),c.jsx("li",{onClick:()=>b(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),c.jsx("li",{onClick:()=>b(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return g?c.jsxs(Mf,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(Df,{asChild:!0,children:c.jsx(zm,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(If,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:x()})]}):null}function mJe({field:e,fieldState:t}){return c.jsxs("div",{className:"w-64 bg-background p-0",children:[c.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[c.jsx("h3",{className:"text-sm font-medium text-foreground",children:e.label||e.name}),c.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:e.dataType})]}),e.description&&c.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:e.description}),t&&t.tooltip&&c.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:c.jsx("p",{className:"text-xs text-muted-foreground",children:t.tooltip})}),c.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:c.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:e.name})})]})}function Q6({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s,actions:o}){const i=Le(K=>K.isDevMode),a=t==="filter"||t==="inline-filter",l=i||a||(n==null?void 0:n.state)==="unreachable"&&!a,u=J(K=>K.dashboard.filters),d=J(K=>K.selectedSheetId),f=J(K=>K.actions.removeFilter),{removeFilterValues:h}=Bt(),{assignFilter:m}=Yte(),p=t==="filter"?ac(u,d):u,g=t==="filter"?p==null?void 0:p.find(K=>{if(K.title===e.name)return!0;const te=km(K.column||""),ie=km(e.name);return te.endsWith(`.${ie}`)||te===ie}):void 0,b=!!g,x=t==="inline-filter"&&(s==null?void 0:s.some(K=>K.column===e.qualifiedFieldName||K.column===e.name)),y=b||x,v=g&&a?u==null?void 0:u.find(K=>K.id===g.id):void 0,C=v&&(v.applyToSheetIds&&v.applyToSheetIds.length>1||v.excludeSheetIds&&v.excludeSheetIds.length>0||!v.applyToSheetIds&&!v.excludeSheetIds&&!v.sheetId);a&&y&&console.log("[SourceField Debug]",{fieldName:e.name,hasActiveFilter:y,activeFilterOnSheet:g?{id:g.id,title:g.title,column:g.column,applyToSheetIds:g.applyToSheetIds,excludeSheetIds:g.excludeSheetIds}:null,activeFilterForField:v?{id:v.id,title:v.title,column:v.column,applyToSheetIds:v.applyToSheetIds,excludeSheetIds:v.excludeSheetIds}:null,isMultiSheetFilter:C,selectedSheetId:d});const[N,S]=w.useState(!1),[j,k]=w.useState(null),{attributes:_,listeners:E,setNodeRef:M,transform:T,transition:P,isDragging:F}=Py({id:e.id,disabled:l}),[A,$]=w.useState(!1),q=Le(K=>K.card),{handleFieldClick:W}=Bte(q),{handleDevModeFieldClick:z,isNumberField:I}=Hte(),L=()=>{v&&(console.log("[SourceField] Removing multi-sheet filter:",v.id),h(v.id),f(v.id)),k(null),S(!1)},O=()=>{if(t==="inline-filter"&&r){r(e);return}t==="filter"?y&&C?(k(e),S(!0)):m(e,"sheet"):i?z(e):W(e)},R={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},H={transform:wi.Transform.toString(T),transition:P},V=()=>{if(!n||a)return{};const te={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[n.state]||{};return n.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",...te},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...te},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...te}}[n.state]||te};function Y(K){return K==="domain"?{label:"Domain",Icon:Ix,className:"border-border bg-muted text-foreground"}:K==="dashboard"?{label:"Dashboard",Icon:gM,className:"border-border bg-muted/70 text-foreground"}:{label:"Card",Icon:e9,className:"border-border bg-muted/40 text-foreground"}}const U=V(),B=e.fieldScope,G=B?Y(B):null,Z=Ww(e),Q=Z&&ic(e);return c.jsxs("div",{ref:M,style:H,...l?{}:_,...l?{}:E,className:X("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",F&&"scale-95 opacity-50",!F&&"border",U.borderColor||"border-transparent",U.bgColor||"",U.hoverBorderColor,U.hoverBgColor||"hover:bg-muted",U.opacity,U.cursor,b&&"border-accent-foreground/20 bg-accent",x&&"border-primary/20 bg-primary/10",{"cursor-pointer":i||a,"cursor-grab active:cursor-grabbing":!l&&!i&&!a}),title:n==null?void 0:n.tooltip,children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:O,children:[c.jsxs("div",{className:"relative shrink-0",children:[Rm(e.dataType),Z&&c.jsx("span",{className:X("absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 text-[7px] font-semibold uppercase italic leading-none shadow-sm",Q?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),c.jsx(Ln,{children:c.jsxs(ln,{children:[c.jsx(cn,{asChild:!0,children:c.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:c.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${A?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),c.jsx(dn,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:c.jsx(mJe,{field:e,fieldState:n})})]})}),t==="editor"&&G&&c.jsx("span",{title:G.label,className:X("shrink-0 rounded-full border p-1",G.className),children:c.jsx(G.Icon,{className:"h-3.5 w-3.5"})}),i&&!a&&I(e)&&c.jsx("div",{onClick:K=>K.stopPropagation(),children:c.jsx(hJe,{column:R})}),o&&c.jsx("div",{className:"ml-auto flex items-center",onClick:K=>K.stopPropagation(),onPointerDown:K=>K.stopPropagation(),children:o})]}),A&&c.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:c.jsx(Uo,{className:"",children:c.jsxs(ea,{className:"space-y-2 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(t9,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.label||e.name})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Jie,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.name})]}),c.jsx(qe,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),c.jsx(Zm,{open:N,onOpenChange:S,children:c.jsxs(Sf,{children:[c.jsxs(Nf,{children:[c.jsx(kf,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(Ef,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(jf,{children:[c.jsx(Tf,{children:"Cancel"}),c.jsx(_f,{onClick:L,children:"Remove Filter"})]})]})})]})}var ha="Accordion",pJe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[bP,gJe,bJe]=Px(ha),[mN]=Lr(ha,[bJe,YW]),xP=YW(),Gte=w.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(bP.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(wJe,{...o,ref:t}):c.jsx(vJe,{...s,ref:t})})});Gte.displayName=ha;var[Kte,xJe]=mN(ha),[Zte,yJe]=mN(ha,{collapsible:!1}),vJe=w.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,l]=os({prop:n,defaultProp:r??"",onChange:s,caller:ha});return c.jsx(Kte,{scope:e.__scopeAccordion,value:w.useMemo(()=>a?[a]:[],[a]),onItemOpen:l,onItemClose:w.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(Zte,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(Xte,{...i,ref:t})})})}),wJe=w.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i,a]=os({prop:n,defaultProp:r??[],onChange:s,caller:ha}),l=w.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=w.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return c.jsx(Kte,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(Zte,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(Xte,{...o,ref:t})})})}),[CJe,pN]=mN(ha),Xte=w.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=w.useRef(null),l=ut(a,t),u=gJe(n),f=bu(s)==="ltr",h=$e(e.onKeyDown,m=>{var k;if(!pJe.includes(m.key))return;const p=m.target,g=u().filter(_=>{var E;return!((E=_.ref.current)!=null&&E.disabled)}),b=g.findIndex(_=>_.ref.current===p),x=g.length;if(b===-1)return;m.preventDefault();let y=b;const v=0,C=x-1,N=()=>{y=b+1,y>C&&(y=v)},S=()=>{y=b-1,y<v&&(y=C)};switch(m.key){case"Home":y=v;break;case"End":y=C;break;case"ArrowRight":o==="horizontal"&&(f?N():S());break;case"ArrowDown":o==="vertical"&&N();break;case"ArrowLeft":o==="horizontal"&&(f?S():N());break;case"ArrowUp":o==="vertical"&&S();break}const j=y%x;(k=g[j].ref.current)==null||k.focus()});return c.jsx(CJe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(bP.Slot,{scope:n,children:c.jsx(Ze.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),H1="AccordionItem",[SJe,yP]=mN(H1),Qte=w.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=pN(H1,n),i=xJe(H1,n),a=xP(n),l=yr(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(SJe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(ZW,{"data-orientation":o.orientation,"data-state":sne(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});Qte.displayName=H1;var Jte="AccordionHeader",ene=w.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=pN(ha,n),o=yP(Jte,n);return c.jsx(Ze.h3,{"data-orientation":s.orientation,"data-state":sne(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});ene.displayName=Jte;var kT="AccordionTrigger",tne=w.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=pN(ha,n),o=yP(kT,n),i=yJe(kT,n),a=xP(n);return c.jsx(bP.ItemSlot,{scope:n,children:c.jsx(JSe,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});tne.displayName=kT;var nne="AccordionContent",rne=w.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=pN(ha,n),o=yP(nne,n),i=xP(n);return c.jsx(eNe,{role:"region","aria-labelledby":o.triggerId,"data-orientation":s.orientation,...i,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...e.style}})});rne.displayName=nne;function sne(e){return e?"open":"closed"}var NJe=Gte,jJe=Qte,kJe=ene,one=tne,ine=rne;const vP=NJe,fx=D.forwardRef(({className:e,...t},n)=>c.jsx(jJe,{ref:n,className:X("border-b",e),...t}));fx.displayName="AccordionItem";const hx=D.forwardRef(({className:e,children:t,...n},r)=>c.jsx(kJe,{className:"flex",children:c.jsxs(one,{ref:r,className:X("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,c.jsx(cr,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));hx.displayName=one.displayName;const mx=D.forwardRef(({className:e,children:t,...n},r)=>c.jsx(ine,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:c.jsx("div",{className:X("pb-4 pt-0",e),children:t})}));mx.displayName=ine.displayName;let ane=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,n)=>(n&=63,n<36?t+=n.toString(36):n<62?t+=(n-26).toString(36).toUpperCase():n>62?t+="-":t+="_",t),"");const px=[{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}],fl=e=>e.trim().toLowerCase().replace(/\s+/g,"_"),jl=e=>e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e;function J6(e,t,n,r,s,o,i,a,l,u){const d=px.find(x=>x.id===t);if(!d)throw new Error(`Unknown operation: ${t}`);let f,h=[],m;if(t==="custom"){if(!(a!=null&&a.trim()))throw new Error("Custom expression is required");f=a.trim(),h=u||[]}else if(t==="scale"){if(!n)throw new Error("Metric A is required for scale operation");if(l===void 0||Number.isNaN(l))throw new Error("Constant factor is required for scale operation");f=d.template().replace("{constant}",String(l)),h=[n],m=l}else{if(!n||!r)throw new Error("Metrics A and B are required for standard operations");f=d.template(),h=[n,r]}const p={operation:t,inputFields:h,...m!==void 0&&{constant:m}},g=fl(e);return{id:i||`calc_${ane(10)}`,name:g,label:e,alias:g,qualifiedFieldName:g,dataType:"number",role:"metric",aggregate:"SUM",expression:f,calculatedFormula:p,entityId:o,entityName:ec,entityType:"table",description:`Calculated field: ${e}`}}function EJe(e){var r,s;const t=px.find(o=>o.id===e.operation);if(!t)return"Unknown operation";if(e.operation==="custom")return"Custom expression";if(e.operation==="scale"){const o=((r=e.inputFields[0])==null?void 0:r.label)||((s=e.inputFields[0])==null?void 0:s.name)||"A",i=e.constant??1;return`${o} × ${i}`}return e.inputFields.map(o=>o.label||o.name).join(` ${t.symbol} `)}function _Je(e,t,n,r,s,o){const i=fl(e);return{id:o||`calc_dim_${ane(10)}`,name:i,label:e.trim(),alias:i,qualifiedFieldName:i,dataType:r,role:"groupby",expression:t.trim(),calculatedFormula:{operation:"custom",inputFields:n.map(a=>a.role==="metric"?{...a,role:"metric"}:{...a,role:"groupby"})},entityId:s,entityName:ec,entityType:"table",description:`Calculated field: ${e.trim()}`}}function TJe(){const{domainCalculatedFields:e}=mP(),t=w.useMemo(()=>e.filter(r=>r.role==="metric"),[e]),n=w.useMemo(()=>e.filter(r=>r.role==="groupby"),[e]);return{fields:e,metrics:t,dimensions:n}}function MJe({value:e,onChange:t,disabled:n,options:r=["dimension","metric"]}){const s=r.length>0?r:["dimension","metric"],o=["dimension","metric"].filter(l=>s.includes(l)),i=n||o.length<=1,a=o.includes(e)?e:o[0];return c.jsx(Ls,{value:a,onValueChange:l=>t(l),className:"w-full",children:c.jsx(Cs,{className:"grid h-9 w-full",style:{gridTemplateColumns:`repeat(${o.length}, minmax(0, 1fr))`},children:o.map(l=>c.jsx(rn,{value:l,disabled:i,className:"text-xs",children:l==="metric"?"Calculated Metric":"Calculated Dimension"},l))})})}function DJe({groups:e,searchTerm:t,onSearchTermChange:n,onFieldClick:r,selectedFieldIds:s,disabled:o}){const i=new Set(s||[]),a=e.length>0||t.length>0,l=e.map(f=>f.id),u=(f,h)=>{if(!h)return f;const m=f.toLowerCase(),p=h.toLowerCase();return m.startsWith(`${p}.`)?f.slice(h.length+1):f},d=(f,h)=>{const p=(f.name||f.baseLabel||f.label||f.tokenLabel||"").trim(),g=[h,f.qualifiedEntityName,f.entityName].filter(Boolean);for(const b of g){const x=u(p,b);if(x!==p)return x}return p.includes(".")&&p.split(".").pop()||p};return c.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3 border-r border-border pr-4",children:[a&&c.jsxs("div",{className:"relative",children:[c.jsx(Zo,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),c.jsx(jn,{value:t,onChange:f=>n(f.target.value),placeholder:"Search fields...",className:"pl-10 pr-10"}),t&&c.jsx("button",{type:"button",onClick:()=>n(""),className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",children:c.jsx(St,{className:"size-3.5"})})]}),c.jsx(nl,{className:"min-h-0 flex-1",children:e.length===0?c.jsx("div",{className:"rounded-md border border-dashed border-muted px-3 py-6 text-center text-xs text-muted-foreground",children:"No fields match your search."}):c.jsx(vP,{type:"multiple",defaultValue:l,className:"space-y-2",children:e.map(f=>c.jsxs(fx,{value:f.id,className:"border-none",children:[c.jsx(hx,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:f.label}),c.jsx(qe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:f.fields.length})]})}),c.jsx(mx,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:f.fields.map(h=>{const m=i.has(h.id),p=!h.isCompatible||o,g=h.isCalculated&&h.role==="metric",b=d(h,f.label);return c.jsxs("button",{type:"button",onClick:()=>h.isCompatible&&!o&&r(h),className:X("group/container flex w-full items-center gap-3 rounded-lg border border-transparent px-2 py-2 text-left transition-all",p?"cursor-not-allowed opacity-50":"hover:bg-muted",m&&"border-border bg-muted"),disabled:p,children:[c.jsxs("div",{className:"relative shrink-0",children:[Rm(h.dataType),h.isCalculated&&c.jsx("span",{className:X("absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 text-[7px] font-semibold uppercase italic leading-none shadow-sm",g?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),c.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:c.jsx("span",{className:X("block truncate text-sm text-foreground/80",!p&&"group-hover/container:text-foreground"),children:b})}),m&&c.jsx(qe,{variant:"secondary",className:"shrink-0 text-[10px]",children:"Selected"})]},h.id)})})})]},f.id))})})]})}function IJe({value:e,onChange:t,allowCustom:n,disabled:r}){const s=px.filter(l=>n?!0:l.id!=="custom"),i=!s.some(l=>l.id==="custom")&&e==="custom"?[...s,px.find(l=>l.id==="custom")]:s,a=i.find(l=>l.id===e);return c.jsxs("div",{className:"space-y-2",children:[c.jsxs(it,{value:e,onValueChange:l=>t(l),disabled:r,children:[c.jsx(rt,{children:c.jsx(at,{})}),c.jsx(st,{children:c.jsxs(gI,{children:[c.jsx(oS,{children:"OPERATIONS"}),i.map(l=>c.jsx(we,{value:l.id,children:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"font-mono text-sm",children:l.symbol}),c.jsx("span",{children:l.label})]})},l.id))]})})]}),a&&c.jsx("p",{className:"text-xs text-muted-foreground",children:a.description})]})}const RJe={COUNT:"Count",DISTINCT:"Count Distinct",SUM:"Sum",AVG:"Average",MIN:"Minimum",MAX:"Maximum",MEDIAN:"Median"};function AJe({value:e,onChange:t,disabled:n,fieldDataType:r,allowMedian:s}){const i=(r?vr(r):"number")==="number",a=["SUM","AVG","COUNT","DISTINCT","MIN","MAX"],l=i?s?[...a,"MEDIAN"]:a:["COUNT","DISTINCT"];return c.jsxs(it,{value:e,onValueChange:u=>t(u),disabled:n,children:[c.jsx(rt,{className:"h-9",children:c.jsx(at,{})}),c.jsx(st,{children:l.map(u=>c.jsx(we,{value:u,children:RJe[u]},u))})]})}const PJe=e=>{const n=(e.name||e.baseLabel||e.label||e.tokenLabel||"").trim();return n.includes(".")&&n.split(".").pop()||n};function ez({label:e,input:t,availableFields:n,excludeFieldIds:r,onFieldSelect:s,onAggregateChange:o,onRemove:i,onActivate:a,allowMedian:l,disabled:u}){const d=(t==null?void 0:t.field.id)||"",f=r!=null&&r.length?n.filter(h=>!r.includes(h.id)):n;return c.jsxs("div",{className:X("flex items-center gap-2 rounded-md border border-border px-2 py-2",a&&!u&&"cursor-pointer",u&&"opacity-60"),onClick:u?void 0:a,children:[c.jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded bg-muted font-mono text-xs font-semibold",children:e}),c.jsxs("div",{className:"flex flex-1 gap-2",children:[c.jsxs(it,{value:d,onValueChange:h=>{const m=f.find(p=>p.id===h);m&&s(m)},disabled:u,children:[c.jsx(rt,{className:"h-9 flex-1",children:c.jsx(at,{placeholder:"Select field"})}),c.jsx(st,{children:f.map(h=>c.jsx(we,{value:h.id,children:PJe(h)},h.id))})]}),c.jsx("div",{className:"w-36",children:c.jsx(AJe,{value:(t==null?void 0:t.aggregate)||"SUM",onChange:o,disabled:u||(t==null?void 0:t.isCalculatedField),fieldDataType:t==null?void 0:t.field.dataType,allowMedian:l})})]}),t&&c.jsx(oe,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:h=>{h.stopPropagation(),i()},disabled:u,children:c.jsx(St,{className:"h-3.5 w-3.5"})})]})}const tz=w.forwardRef(function({value:t,onChange:n,onGenerate:r,showGenerate:s,disabled:o},i){return c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("span",{className:"text-sm font-medium",children:"Expression"}),s&&c.jsxs(oe,{type:"button",size:"sm",variant:"outline",onClick:r,disabled:o,className:"h-7 gap-2 text-xs",children:[c.jsx(lC,{className:"h-3.5 w-3.5"}),"Generate with AI"]})]}),c.jsx(nx,{ref:i,value:t,onChange:a=>n(a.target.value),disabled:o,placeholder:"CASE WHEN {Amount} > 100 THEN 'Large' ELSE 'Small' END",className:"min-h-[140px] font-mono text-xs"})]})});function FJe({result:e}){const t=e.errors.length>0;return c.jsxs("div",{className:X("rounded-md border px-3 py-2 text-xs",t?"border-destructive/40 bg-destructive/10 text-destructive":"border-emerald-500/30 bg-emerald-500/10 text-emerald-700"),children:[c.jsx("div",{className:"font-medium",children:t?"Validation Failed":"Validation Passed"}),e.tokens.length>0&&c.jsxs("div",{className:"mt-2 space-y-1",children:[c.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Tokens Found"}),e.tokens.map(n=>c.jsx("div",{children:n.field?`{${n.token}} -> ${n.field.qualifiedFieldName||n.field.name}`:`{${n.token}}`},n.token))]}),e.errors.length>0&&c.jsxs("div",{className:"mt-2 space-y-1",children:[c.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Errors"}),e.errors.map((n,r)=>c.jsxs("div",{children:[n.message,n.suggestion?` (${n.suggestion})`:""]},`${n.code}-${r}`))]}),e.warnings.length>0&&c.jsxs("div",{className:"mt-2 space-y-1",children:[c.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Warnings"}),e.warnings.map((n,r)=>c.jsxs("div",{children:[n.message," ",n.suggestion]},`${n.code}-${r}`))]}),e.inferredDataType&&c.jsxs("div",{className:"mt-2 text-[11px] text-muted-foreground",children:["Inferred Output Type: ",e.inferredDataType]})]})}function nz({onValidate:e,isValidating:t,validationResult:n,fallbackResult:r,error:s,showFallback:o,disabled:i}){return c.jsxs("div",{className:"space-y-2",children:[c.jsx(oe,{type:"button",variant:"outline",onClick:e,disabled:t||i,className:"h-8",children:t?"Validating...":"Validate Expression"}),s&&c.jsx("div",{className:"text-xs text-destructive",children:s}),(n||o)&&c.jsx(FJe,{result:n||r})]})}function OJe({scope:e,onChange:t,showDashboardScope:n,showDomainScope:r,error:s,disabled:o}){return c.jsxs("div",{className:"space-y-3 border-t border-border pt-4",children:[c.jsx(fe,{children:"Availability"}),c.jsxs(so,{value:e,onValueChange:i=>t(i),className:"space-y-2",disabled:o,children:[c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(xn,{id:"scope-card",value:"card"}),c.jsx(fe,{htmlFor:"scope-card",className:"text-sm font-normal",children:"This card only"})]}),n&&c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(xn,{id:"scope-dashboard",value:"dashboard"}),c.jsx(fe,{htmlFor:"scope-dashboard",className:"text-sm font-normal",children:"All cards in this dashboard"})]}),r&&c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(xn,{id:"scope-domain",value:"domain"}),c.jsx(fe,{htmlFor:"scope-domain",className:"text-sm font-normal",children:"Save to domain"})]})]}),s&&c.jsx("p",{className:"text-xs text-red-500",children:s})]})}function $Je({description:e,tags:t,onDescriptionChange:n,onTagsChange:r,descriptionError:s,disabled:o}){return c.jsxs("div",{className:"space-y-3 rounded-md border border-muted bg-muted/30 p-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{htmlFor:"domain-description",children:"Description"}),c.jsx(vu,{id:"domain-description",value:e,onChange:i=>n(i.target.value),placeholder:"Explain what this metric represents",className:X("text-sm",s&&"border-red-500"),rows:3,disabled:o}),s&&c.jsx("p",{className:"text-xs text-red-500",children:s})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{htmlFor:"domain-tags",children:"Tags (optional)"}),c.jsx(pn,{id:"domain-tags",value:t,onChange:i=>r(i.target.value),placeholder:"profitability, kpi",disabled:o})]}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"This field will be visible to all dashboards using this domain."})]})}function LJe({endpoint:e,availableFields:t,fieldType:n,dialect:r}){const{authToken:s}=Xe(),[o,i]=w.useState(!1),[a,l]=w.useState(null);return{generateExpression:w.useCallback(async d=>{var f;if(!e)return l("AI generation is not available"),null;if(!d.trim())return l("Describe what you want to calculate"),null;i(!0),l(null);try{const h={type:"calculated-field-expression",context:{userQuery:d,availableFields:t.map(p=>({name:p.tokenLabel,dataType:p.dataType})),fieldType:n},options:{dialect:r}},m=await Yr(e,(s==null?void 0:s.accessToken)||"",h);if(!m.success||!((f=m.result)!=null&&f.generated))throw new Error(m.error||"No expression generated");return m.result.generated}catch(h){return l((h==null?void 0:h.error)||(h==null?void 0:h.message)||"AI generation failed"),null}finally{i(!1)}},[e,t,n,r,s==null?void 0:s.accessToken]),isGenerating:o,error:a}}function zJe({open:e,onOpenChange:t,availableFields:n,fieldType:r,onExpressionGenerated:s,endpoint:o,dialect:i}){const[a,l]=w.useState(""),[u,d]=w.useState(""),[f,h]=w.useState(""),{generateExpression:m,isGenerating:p,error:g}=LJe({endpoint:o,availableFields:n,fieldType:r,dialect:i}),b=w.useMemo(()=>{const S=f.trim().toLowerCase();return S?n.filter(j=>[j.label,j.baseLabel,j.name,j.tokenLabel,j.entityName,j.qualifiedEntityName].filter(Boolean).join(" ").toLowerCase().includes(S)):n},[n,f]),x=S=>{const k=(S.name||S.baseLabel||S.label||S.tokenLabel||"").trim();return k.includes(".")&&k.split(".").pop()||k},y=S=>{const j=S.entityName||S.qualifiedEntityName||"";return j?j==="SEMAPHOR_CALCULATED_FIELD"?"Calculated":j.includes(".")&&j.split(".").pop()||j:"—"},v=async()=>{const S=await m(a.trim());S&&d(S)},C=()=>{u.trim()&&(s(u.trim()),l(""),d(""),t(!1))},N=()=>{l(""),d(""),h(""),t(!1)};return c.jsx(Kr,{open:e,onOpenChange:S=>{S?t(!0):N()},children:c.jsxs(zr,{className:"max-w-3xl",children:[c.jsxs(Br,{children:[c.jsx(Vr,{children:"Generate Expression with AI"}),c.jsx(as,{children:"Describe what you want to calculate and we will draft a SQL expression."})]}),c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{htmlFor:"ai-prompt",children:"Describe what you want to calculate"}),c.jsx(nx,{id:"ai-prompt",value:a,onChange:S=>l(S.target.value),placeholder:"Create a bucket that categorizes orders as 'Large' when amount is greater than 1000",rows:2})]}),c.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs text-muted-foreground",children:[c.jsx("span",{children:"Be specific about conditions, buckets, or math you want to apply."}),c.jsx(oe,{size:"sm",onClick:v,disabled:p||!a.trim(),children:p?"Generating...":u?"Regenerate":"Generate"})]}),g&&c.jsx("p",{className:"text-xs text-destructive",children:g})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{children:"Available fields"}),c.jsxs("div",{className:"relative",children:[c.jsx(Zo,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),c.jsx(pn,{value:f,onChange:S=>h(S.target.value),placeholder:"Search fields...",className:"pl-9"})]}),c.jsx("div",{className:"overflow-hidden rounded-lg border border-border",children:c.jsx("div",{className:"max-h-48 overflow-y-auto",children:c.jsxs("table",{className:"w-full text-sm",children:[c.jsx("thead",{className:"sticky top-0 z-10 border-b bg-muted",children:c.jsxs("tr",{children:[c.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Field"}),c.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Type"}),c.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Category"})]})}),c.jsx("tbody",{className:"divide-y",children:b.length===0?c.jsx("tr",{children:c.jsx("td",{colSpan:3,className:"py-6 text-center text-xs text-muted-foreground",children:"No fields match your search."})}):b.map(S=>c.jsxs("tr",{className:"hover:bg-muted/30",children:[c.jsx("td",{className:"px-3 py-1.5 font-mono text-xs",children:x(S)}),c.jsx("td",{className:"px-3 py-1.5",children:c.jsx(qe,{variant:"secondary",className:"px-1.5 py-0 text-[11px]",children:S.dataType})}),c.jsx("td",{className:"px-3 py-1.5 text-sm text-muted-foreground",children:y(S)})]},S.id))})]})})})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{children:"Generated expression"}),c.jsx(nx,{value:u,readOnly:!0,rows:2,className:"font-mono text-sm"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Review the generated expression before using it."})]})]}),c.jsxs(is,{className:"gap-2",children:[c.jsx(oe,{variant:"ghost",onClick:N,children:"Cancel"}),c.jsx(oe,{onClick:C,disabled:!u.trim(),children:"Use Expression"})]})]})})}const BJe=/\{([^}]+)\}/g;function gN(e){return e.trim().toLowerCase()}function U1(e){return Array.from(e.matchAll(BJe)).map(t=>t[1]).filter(Boolean)}function VJe(e){const t=new Set,n=[];return e.forEach(r=>{const s=gN(r);t.has(s)||(t.add(s),n.push(r))}),n}function wP(e){const t=new Map,n=(r,s)=>{const o=gN(r),i=t.get(o)||[];i.some(a=>a.id===s.id)||t.set(o,[...i,s])};return e.forEach(r=>{n(r.tokenLabel,r),r.name&&r.name!==r.tokenLabel&&n(r.name,r),r.baseLabel&&r.baseLabel!==r.tokenLabel&&n(r.baseLabel,r)}),t}function ig(e,t){const n=U1(e),r=VJe(n),s=wP(t),o=r.map(a=>{const l=s.get(gN(a))||[];return l.length===1?l[0]:null}),i=r.filter((a,l)=>!o[l]);return{orderedTokens:r,orderedFields:o,unresolvedTokens:i}}function rz(e,t){return t.reduce((n,r,s)=>{const o=new RegExp(`\\{${HJe(r)}\\}`,"gi");return n.replace(o,`{field_${s}}`)},e)}function HJe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const UJe=e=>e.entityName===rm||e.entityName===ec?"Calculated Fields":e.qualifiedEntityName?pb(e.entityName||e.qualifiedEntityName):pb(e.entityName||"Other"),WJe=e=>vr(e.dataType||"")==="number";function qJe(e,t,n){const r=new Set((n||[]).map(s=>jl(s)));return e.filter(s=>{const o=jl(s.id);return o&&r.has(o)?!1:t==="dimension"?s.role!=="metric":!0})}function YJe(e){const t=new Map,n=new Map;return e.forEach(r=>{let o=r.entityName&&r.entityName!==ec?`${r.entityName}.${r.name}`:r.name;const i=o.toLowerCase(),a=n.get(i)||0;a>0&&(o=`${o} ${a+1}`),n.set(i,a+1),t.set(r.id,o)}),t}function GJe(e,t,n,r){if(t!=="metric")return e.map(o=>({...o,isCompatible:!0}));if(!n)return e.map(o=>({...o,isCompatible:!0}));const s=n==="COUNT"||n==="DISTINCT";return e.map(o=>{const i=s||WJe(o);return{...o,isCompatible:i}}).filter(o=>r)}function KJe(e,t){if(!t)return e;const n=t.toLowerCase();return e.filter(r=>r.name.toLowerCase().includes(n)||r.baseLabel.toLowerCase().includes(n)||r.tokenLabel.toLowerCase().includes(n)||r.dataType.toLowerCase().includes(n)||(r.qualifiedEntityName||r.entityName||"").toLowerCase().includes(n))}function ZJe(e){const t=new Map;return e.forEach(n=>{var s;const r=n.qualifiedEntityName||n.entityName||"Other";t.has(r)||t.set(r,{id:r,label:UJe(n),fields:[]}),(s=t.get(r))==null||s.fields.push(n)}),Array.from(t.values())}function XJe({fields:e,mode:t,searchTerm:n,excludeFieldIds:r,selectedAggregate:s,showIncompatible:o}){const i=w.useMemo(()=>qJe(e,t,r),[e,t,r]),a=w.useMemo(()=>YJe(i),[i]),l=w.useMemo(()=>i.map(m=>{const p=m.label||m.name,g=m.role==="metric"&&ic(m)||m.role==="groupby"&&Qx(m);return{...m,baseLabel:p,tokenLabel:a.get(m.id)||p,isCalculated:g,isCompatible:!0}}),[i,a]),u=w.useMemo(()=>wP(l),[l]),d=w.useMemo(()=>GJe(l,t,s,o),[l,t,s,o]),f=w.useMemo(()=>KJe(d,n),[d,n]),h=w.useMemo(()=>ZJe(f),[f]);return{allFields:l,filteredFields:f,groups:h,tokenCandidates:u}}const QJe=e=>{let t=0;for(const n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0},JJe=(e,t)=>{const n=e.toLowerCase(),r=t.toLowerCase();if(n===r)return 0;if(!n.length)return r.length;if(!r.length)return n.length;const s=[];for(let o=0;o<=r.length;o+=1)s[o]=[o];for(let o=0;o<=n.length;o+=1)s[0][o]=o;for(let o=1;o<=r.length;o+=1)for(let i=1;i<=n.length;i+=1)r.charAt(o-1)===n.charAt(i-1)?s[o][i]=s[o-1][i-1]:s[o][i]=Math.min(s[o-1][i-1]+1,s[o][i-1]+1,s[o-1][i]+1);return s[r.length][n.length]},eet=(e,t)=>t.map(r=>({candidate:r,distance:JJe(e,r)})).filter(r=>r.distance>0&&r.distance<=3).sort((r,s)=>r.distance-s.distance).slice(0,3).map(r=>r.candidate),tet=(e,t)=>{var r;const n=e.trim();if(n){if(/\bDATE_TRUNC\b/i.test(n))return"date";if(/\bTIMESTAMP\b/i.test(n))return"datetime";if(/\bDATE\b/i.test(n)&&!/\bUPDATE\b/i.test(n))return"date";if(/['"]/.test(n))return"string";if(/[+\-*/]/.test(n))return"number";if(t.length===1){const s=((r=t[0])==null?void 0:r.dataType)||"";if(/date|timestamp/i.test(s))return"date";if(/int|decimal|float|double|num|real/i.test(s))return"number";if(/boolean/i.test(s))return"boolean"}return"string"}},net=e=>e.map(t=>({id:t.id,name:t.name,label:t.tokenLabel,dataType:t.dataType,entityName:t.entityName,role:t.role}));function ret({expression:e,availableFields:t,excludeFieldIds:n,validationEndpoint:r,connectionId:s,dialect:o}){const{authToken:i}=Xe(),[a,l]=w.useState(null),[u,d]=w.useState(!1),[f,h]=w.useState(null),m=w.useMemo(()=>wP(t),[t]),p=w.useMemo(()=>{const x=[],y=[],v=e.trim();v||x.push({code:"SYNTAX_ERROR",message:"Expression is required"}),v&&!QJe(v)&&x.push({code:"SYNTAX_ERROR",message:"Unbalanced parentheses in expression"});const N=U1(e).map(j=>{const k=m.get(gN(j))||[];if(!k.length){const M=Array.from(m.keys()),T=eet(j,M),P=T.length?`Did you mean {${T[0]}}?`:void 0;return x.push({code:"UNKNOWN_TOKEN",message:`Unknown field token: {${j}}`,suggestion:P}),{token:j,field:null,error:"Unknown token"}}if(k.length>1)return x.push({code:"UNKNOWN_TOKEN",message:`Token {${j}} matches multiple fields. Use a disambiguated label.`}),{token:j,field:null,error:"Ambiguous token"};const _=k[0];return(n||[]).map(jl).includes(jl(_.id))?(x.push({code:"SELF_REFERENCE",message:"Cannot reference the field being edited"}),{token:j,field:null,error:"Self reference"}):{token:j,field:_}});/\bCASE\b/i.test(e)&&!/\bELSE\b/i.test(e)&&y.push({code:"MISSING_ELSE",message:"CASE expression missing ELSE clause",suggestion:"Add an ELSE branch to handle default values."}),/\//.test(e)&&!/NULLIF\s*\(/i.test(e)&&y.push({code:"DIVISION_BY_ZERO",message:"Division may result in divide-by-zero errors",suggestion:"Wrap the denominator in NULLIF(..., 0)."});const S=N.map(j=>j.field).filter(Boolean);return{isValid:x.length===0,tokens:N,errors:x,warnings:y,inferredDataType:tet(e,S)}},[e,n,m]),g=w.useCallback(async()=>{var v;if(h(null),!r||!p.isValid)return l(p),p;const x=r,y={type:"calculated-field-expression",value:e,context:{availableFields:net(t),connectionId:s,excludeFieldIds:n,dialect:o}};d(!0);try{const C=await Yr(x,(i==null?void 0:i.accessToken)||"",y),N=C.errors||[],S=C.warnings||[],j={...p,isValid:C.valid&&N.length===0,errors:N,warnings:S,inferredDataType:((v=C.metadata)==null?void 0:v.inferredType)||p.inferredDataType};return l(j),j}catch(C){return h((C==null?void 0:C.error)||"Validation failed"),l(p),p}finally{d(!1)}},[r,p,e,t,s,n,o,i==null?void 0:i.accessToken]),b=w.useCallback(()=>{l(null),h(null)},[]);return{clientResult:p,validationResult:a,isValidating:u,serverError:f,validateExpression:g,resetValidation:b}}const sz=[{value:"string",label:"String"},{value:"number",label:"Number"},{value:"boolean",label:"Boolean"},{value:"date",label:"Date"},{value:"datetime",label:"Datetime"},{value:"json",label:"JSON"},{value:"geo",label:"Geo"}],hk=e=>{if(!e)return"";const t=e.field.tokenLabel||e.field.label||e.field.name,n=e.aggregate;return n==="DISTINCT"?`COUNT(DISTINCT ${t})`:n==="COUNT"?`COUNT(${t})`:`${n}(${t})`},lne=e=>vr(e.dataType||"")==="number",hh=e=>lne(e)?"SUM":"COUNT",mk=(e,t)=>lne(e)||t==="COUNT"||t==="DISTINCT"?t:hh(e);function pk(e,t){if(e.role==="metric"){const n=e;return ic(n)?n:{...n,aggregate:t}}return{...e,id:`${e.id}_${t.toLowerCase()}`,role:"metric",aggregate:t,alias:`${(e.alias||e.name).toLowerCase()}_${t.toLowerCase()}`,entityName:e.entityName,entityId:e.entityId,qualifiedEntityName:e.qualifiedEntityName}}function ih(e,t){const n=e.role==="metric"&&ic(e);return{field:e,aggregate:n&&e.aggregate||t,isCalculatedField:n}}function cne({open:e,onOpenChange:t,availableFields:n,existingField:r,existingFieldScope:s,onSave:o,onSaveToDashboard:i,onPromoteMetricToDomain:a,onPromoteDimensionToDomain:l,cardId:u,domainId:d,initialFieldType:f="metric",allowedFieldTypes:h}){var Hf;const{tokenProps:m}=Xe(),{selectedConnection:p}=sW(),g=(p==null?void 0:p.dialect)==="bigquery"||(p==null?void 0:p.dialect)==="snowflake",[b,x]=w.useState(f),[y,v]=w.useState(""),[C,N]=w.useState("ratio"),[S,j]=w.useState(null),[k,_]=w.useState(null),[E,M]=w.useState(1),[T,P]=w.useState(""),[F,A]=w.useState(null),[$,q]=w.useState("card"),[W,z]=w.useState(""),[I,L]=w.useState(""),[O,R]=w.useState({}),[H,V]=w.useState("A"),[Y,U]=w.useState(""),[B,G]=w.useState(!1),[Z,Q]=w.useState(null),[K,te]=w.useState(!1),[ie,ue]=w.useState(!1),[he,je]=w.useState(!1),be=w.useRef(null),Me=w.useRef(!1),le=w.useRef(null),{userContext:ae}=$s(),{metrics:xe,dimensions:de}=TJe(),Se=(ae==null?void 0:ae.type)==="organization",ge=!Se,se=!!d&&Se,me=se&&!!a,Oe=se&&!!l,Pe=!!(i||me||Oe),Re=!!i,He=b==="metric"?me:Oe,Ke=(Hf=m==null?void 0:m.apiServiceUrl)==null?void 0:Hf.replace(/\/$/,""),tt=Ke?`${Ke}/v1/validate`:"/v1/validate",mt=Ke?`${Ke}/v1/ai/generate`:"/v1/ai/generate",gt=w.useMemo(()=>{var Mt;const Ee=[...n];return(((Mt=r==null?void 0:r.calculatedFormula)==null?void 0:Mt.inputFields)||[]).forEach(wn=>{Ee.some(Yn=>Yn.id===wn.id||Yn.qualifiedFieldName===wn.qualifiedFieldName||Yn.name===wn.name)||Ee.push(wn)}),Ee},[n,r]),dt=H==="A"?S:k,Ht=b==="metric"&&C!=="custom"?dt==null?void 0:dt.aggregate:void 0,{allFields:Ge,groups:Nt}=XJe({fields:gt,mode:b,searchTerm:Y,excludeFieldIds:r?[r.id]:void 0,selectedAggregate:Ht,showIncompatible:!0}),ce=Ge,{clientResult:Ae,validationResult:Te,validateExpression:Ie,isValidating:Ue,serverError:ke,resetValidation:ye}=ret({expression:T,availableFields:ce,excludeFieldIds:r?[r.id]:void 0,validationEndpoint:tt,connectionId:p==null?void 0:p.id,dialect:p==null?void 0:p.dialect}),ne=(Te==null?void 0:Te.inferredDataType)||Ae.inferredDataType,Ce=F||ne||"string",Fe=px.find(Ee=>Ee.id===C),Qe=w.useMemo(()=>{if(!y.trim())return!1;const Ee=fl(y),lt=s==="domain"&&(r!=null&&r.name)?fl(r.name):null;return(b==="metric"?xe:de).some(wn=>{const Jt=fl(wn.name);return lt&&Jt===lt?!1:Jt===Ee})},[de,xe,r,s,b,y]),Ot=w.useMemo(()=>{if(b==="metric"&&C==="custom"){const{orderedFields:lt}=ig(T,ce);return lt.filter(Mt=>!!Mt).map(Mt=>Mt.id)}const Ee=[];return S!=null&&S.field.id&&Ee.push(S.field.id),k!=null&&k.field.id&&Ee.push(k.field.id),Ee},[ce,T,b,S,k,C]),Xt=Ee=>{ge||(x(Ee),Ee==="dimension"&&$==="domain"&&!Oe&&q("card"),Ee==="metric"&&$==="domain"&&!me&&q("card"))},Dn=Ee=>{ge||(N(Ee),Ee==="scale"&&_(null),Ee==="custom"&&(j(null),_(null)))},Zr=()=>{v(""),N("ratio"),j(null),_(null),M(1),P(""),A(null),q("card"),z(""),L(""),R({}),U(""),G(!1),Q(null),te(!1),je(!1),ye(),t(!1)},Hr=w.useCallback(Ee=>gt.find(lt=>lt.qualifiedFieldName===Ee.qualifiedFieldName||lt.name===Ee.name)||Ee,[gt]),Hs=w.useCallback(Ee=>{if(!Ee.calculatedFormula)return;const lt=Ee.calculatedFormula;if(N(lt.operation),P(""),lt.operation==="scale"){const Jt=lt.inputFields[0];Jt&&j(ih(Hr(Jt),Jt.aggregate||"SUM")),M(lt.constant===void 0?1:lt.constant);return}if(lt.operation==="custom"){P(Ei(Ee.expression||"",lt.inputFields||[])),j(null),_(null);return}const[Mt,wn]=lt.inputFields;Mt&&j(ih(Hr(Mt),Mt.aggregate||"SUM")),wn&&_(ih(Hr(wn),wn.aggregate||"SUM"))},[Hr]),Ei=w.useCallback((Ee,lt)=>Ee.replace(/\{field_(\d+)\}/g,(Mt,wn)=>{var Nr;const Jt=lt[Number(wn)];return Jt?`{${((Nr=ce.find(_i=>_i.id===Jt.id))==null?void 0:Nr.tokenLabel)||Jt.label||Jt.name}}`:Mt}),[ce]);w.useEffect(()=>{var Mt;if(!e){Me.current=!1,le.current=null;return}const Ee=r?`${r.role}-${r.id||r.name}`:"new";if(Me.current&&le.current===Ee)return;if(Me.current=!0,le.current=Ee,R({}),U(""),je(!1),ye(),r){const wn=r.tags||[];if(r.role==="metric"){x("metric"),v(r.label||r.name),q(s||"card"),z(r.description||""),L(wn.join(", ")),Hs(r);return}x("dimension");const Jt=r;v(Jt.label||Jt.name),q(s||"card"),P(Ei(Jt.expression||"",((Mt=Jt.calculatedFormula)==null?void 0:Mt.inputFields)||[]));const Yn=sz.some(Nr=>Nr.value===Jt.dataType)?Jt.dataType:"string";A(Yn),z(Jt.description||""),L(wn.join(", "));return}const lt=h&&h.length>0?h.includes(f)?f:h[0]:f;x(lt),v(""),N("ratio"),j(null),_(null),M(1),P(""),A(null),q("card"),z(""),L("")},[e,r,s,f,h,Hs,Ei,ye]);const Ou=Ee=>{const lt=`{${Ee}}`,Mt=be.current;if(!Mt){P(Nr=>Nr+lt);return}const wn=Mt.selectionStart||0,Jt=Mt.selectionEnd||0,Yn=`${T.slice(0,wn)}${lt}${T.slice(Jt)}`;P(Yn),requestAnimationFrame(()=>{Mt.focus();const Nr=wn+lt.length;Mt.setSelectionRange(Nr,Nr)})},yN=Ee=>{if(ge)return;if(b==="dimension"||C==="custom"){Ou(Ee.tokenLabel||Ee.label||Ee.name);return}const lt=mk(Ee,H==="A"?(S==null?void 0:S.aggregate)||hh(Ee):(k==null?void 0:k.aggregate)||hh(Ee)),Mt=ih(Ee,lt);if(H==="A"){j(Mt),k||V("B");return}_(Mt),S||V("A")},Uy=(Ee,lt)=>{if(!ge){if(Ee==="A"&&S){j({...S,aggregate:lt});return}Ee==="B"&&k&&_({...k,aggregate:lt})}},fc=async()=>{const Ee={};if(y.trim()||(Ee.name="Name is required"),C==="custom")T.trim()||(Ee.expression="Expression is required"),U1(T).length===0&&(Ee.expression=Ee.expression||"Expression must include field tokens"),ig(T,ce).unresolvedTokens.length>0&&(Ee.expression=Ee.expression||"Expression contains unknown or ambiguous tokens"),Ee.expression||(await Ie()).isValid||(Ee.expression="Fix validation errors before saving");else if(C==="scale")S||(Ee.inputA="Please select a metric for input A"),Number.isNaN(E)&&(Ee.constant="Please enter a valid multiplication factor");else{if(S||(Ee.inputA="Please select a metric for input A"),k||(Ee.inputB="Please select a metric for input B"),S&&k){const lt=S.field.id===k.field.id,Mt=S.aggregate===k.aggregate;lt&&Mt&&(Ee.inputs="Inputs A and B must be different metrics")}if(r&&r.role==="metric"){const lt=jl(r.id);(jl(S==null?void 0:S.field.id)===lt||jl(k==null?void 0:k.field.id)===lt)&&(Ee.inputs="Cannot reference the field being edited")}}return Pe&&($==="domain"&&!me&&(Ee.scope="You do not have permission to save to domain"),$==="domain"&&!W.trim()&&(Ee.description="Description is required for domain fields"),$==="domain"&&Qe&&(Ee.name="A domain field with this name already exists")),R(Ee),Object.keys(Ee).length===0},vN=async()=>{const Ee={};return y.trim()||(Ee.name="Name is required"),T.trim()||(Ee.expression="Expression is required"),U1(T).length===0&&(Ee.expression=Ee.expression||"Expression must include field tokens"),ig(T,ce).unresolvedTokens.length>0&&(Ee.expression=Ee.expression||"Expression contains unknown or ambiguous tokens"),Ee.expression||(await Ie()).isValid||(Ee.expression="Fix validation errors before saving"),Pe&&($==="domain"&&!Oe&&(Ee.scope="You do not have permission to save to domain"),$==="domain"&&!W.trim()&&(Ee.description="Description is required for domain fields"),$==="domain"&&Qe&&(Ee.name="A domain field with this name already exists")),R(Ee),Object.keys(Ee).length===0},wN=()=>{const{orderedTokens:Ee,orderedFields:lt}=ig(T,ce),Mt=lt.filter(Yn=>!!Yn),wn=rz(T,Ee),Jt=_Je(y,wn,Mt,Ce,u,r==null?void 0:r.id);return r&&r.role==="groupby"?{...r,...Jt}:Jt},CN=()=>{var wn;if(C==="custom"){const{orderedTokens:Jt,orderedFields:Yn}=ig(T,ce),Nr=Yn.filter($t=>!!$t),_i=(r==null?void 0:r.role)==="metric"?((wn=r.calculatedFormula)==null?void 0:wn.inputFields)||[]:[],jo=new Map;_i.forEach($t=>{const dr=jl($t.id);dr&&jo.set(dr,$t),$t.qualifiedFieldName&&jo.set($t.qualifiedFieldName,$t),$t.name&&jo.set($t.name,$t)});const hc=Nr.map($t=>{const dr=jl($t.id),Ti=dr&&jo.get(dr)||$t.qualifiedFieldName&&jo.get($t.qualifiedFieldName)||jo.get($t.name),jN=((Ti==null?void 0:Ti.role)==="metric"?Ti.aggregate:void 0)||($t.role==="metric"?$t.aggregate:void 0)||hh($t);return pk($t,jN)}),er=rz(T,Jt),sn=J6(y,C,null,null,{},u,r==null?void 0:r.id,er,void 0,hc);return r&&r.role==="metric"?{...r,...sn}:sn}const Ee=S?pk(S.field,S.aggregate):null,lt=k?pk(k.field,k.aggregate):null,Mt=J6(y,C,Ee,lt,{},u,r==null?void 0:r.id,void 0,C==="scale"?E:void 0);return r&&r.role==="metric"?{...r,...Mt}:Mt},Wy=async Ee=>{var Mt,wn,Jt;if(b==="dimension"){const Yn=wN();if(Ee==="dashboard"){if(!i){R(Nr=>({...Nr,scope:"Dashboard scope is not available"}));return}i(Yn),Zr();return}if(Ee==="domain"){if(!l){R(sn=>({...sn,scope:"Domain scope is not available"}));return}const Nr=((Mt=Yn.calculatedFormula)==null?void 0:Mt.inputFields)||[],_i=new Map,jo=Nr.map(sn=>{const $t=fl(sn.label||sn.name),dr=_i.get($t)||0;return _i.set($t,dr+1),dr===0?$t:`${$t}_${dr+1}`}),hc=((wn=Yn.expression)==null?void 0:wn.replace(/\{field_(\d+)\}/g,(sn,$t)=>`{${jo[Number($t)]||$t}}`))||"",er=jo.reduce((sn,$t,dr)=>{const Ti=Nr[dr];return Qx(Ti)?sn[$t]={dimension:Ti.name}:sn[$t]={dataset:Ti.entityName,field:Ti.name},sn},{});try{await l({name:fl(y),label:y.trim(),description:W.trim(),expression:hc,inputs:er,dataType:Ce,tags:I.split(",").map(sn=>sn.trim()).filter(Boolean),overwrite:s==="domain",previousName:s==="domain"?r==null?void 0:r.name:void 0})}catch(sn){R($t=>({...$t,scope:(sn==null?void 0:sn.message)||"Failed to save to domain"}));return}Zr();return}o(Yn),Zr();return}const lt=CN();if(Ee==="dashboard"){if(!i){R(Yn=>({...Yn,scope:"Dashboard scope is not available"}));return}i(lt),Zr();return}if(Ee==="domain"){if(!a){R(er=>({...er,scope:"Domain scope is not available"}));return}if(!lt.calculatedFormula){R(er=>({...er,scope:"Calculated formula missing"}));return}const Yn=lt.calculatedFormula.inputFields,Nr=new Map,_i=Yn.map(er=>{const sn=fl(er.label||er.name),$t=Nr.get(sn)||0;return Nr.set(sn,$t+1),$t===0?sn:`${sn}_${$t+1}`}),jo=((Jt=lt.expression)==null?void 0:Jt.replace(/\{field_(\d+)\}/g,(er,sn)=>`{${_i[Number(sn)]||sn}}`))||"",hc=_i.reduce((er,sn,$t)=>{const dr=Yn[$t];return dr.role==="metric"?ic(dr)?er[sn]={metric:dr.name}:er[sn]={dataset:dr.entityName,field:dr.name,aggregate:dr.aggregate}:er[sn]={dataset:dr.entityName,field:dr.name},er},{});try{await a({name:fl(y),label:y.trim(),description:W.trim(),expression:jo,inputs:hc,tags:I.split(",").map(er=>er.trim()).filter(Boolean),overwrite:s==="domain",previousName:s==="domain"?r==null?void 0:r.name:void 0})}catch(er){R(sn=>({...sn,scope:(er==null?void 0:er.message)||"Failed to save to domain"}));return}Zr();return}o(lt),Zr()},SN=async()=>{if(ge)return;if(R({}),b==="metric"){if(!await fc())return}else if(!await vN())return;const Ee=Pe?$:s||"card";if(b==="metric"&&Ee!=="domain"&&Qe&&!r){Q(Ee),te(!0);return}ue(!0);try{await Wy(Ee)}finally{ue(!1)}},NN=w.useMemo(()=>{if(!Fe||C==="custom")return"";if(C==="scale"){const Ee=Number.isFinite(E)?E:1;return`${hk(S)} x ${Ee}`}return`${hk(S)||"A"} ${Fe.symbol} ${hk(k)||"B"}`},[Fe,C,S,k,E]);return c.jsxs(c.Fragment,{children:[c.jsxs(Kr,{modal:!1,open:e,onOpenChange:Ee=>{Ee?t(!0):Zr()},children:[e&&c.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),c.jsxs(zr,{className:"max-w-5xl max-h-[90vh] overflow-hidden",onInteractOutside:Ee=>{Ee.preventDefault()},children:[c.jsxs(Br,{children:[c.jsxs(Vr,{children:[r?"Edit":"Create"," Calculated Field"]}),c.jsx(as,{children:"Build calculated metrics and dimensions using expressions."})]}),c.jsxs("div",{className:"grid h-[70vh] min-h-0 grid-cols-[320px_1fr] gap-6",children:[c.jsx(DJe,{groups:Nt,searchTerm:Y,onSearchTermChange:U,onFieldClick:yN,selectedFieldIds:Ot,disabled:ge}),c.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-4 overflow-y-auto pr-2",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{children:"Field Type"}),c.jsx(MJe,{value:b,onChange:Xt,disabled:ge||!!r,options:h||["metric","dimension"]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{htmlFor:"calculated-name",children:"Name"}),c.jsx(pn,{id:"calculated-name",value:y,onChange:Ee=>v(Ee.target.value),placeholder:"e.g., Profit Margin",className:O.name?"border-red-500":"",disabled:ge}),O.name&&c.jsx("p",{className:"text-xs text-red-500",children:O.name})]}),b==="metric"&&c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{children:"Operation"}),c.jsx(IJe,{value:C,onChange:Dn,allowCustom:!0,disabled:ge}),O.operation&&c.jsx("p",{className:"text-xs text-red-500",children:O.operation})]}),C==="custom"?c.jsxs("div",{className:"space-y-4",children:[c.jsx(tz,{ref:be,value:T,onChange:Ee=>{P(Ee),je(!1)},onGenerate:()=>G(!0),showGenerate:!!mt&&!ge,disabled:ge}),c.jsx(nz,{onValidate:async()=>{je(!0),await Ie()},isValidating:Ue,validationResult:Te,fallbackResult:Ae,error:ke,showFallback:he,disabled:ge}),O.expression&&c.jsx("p",{className:"text-xs text-red-500",children:O.expression})]}):c.jsxs("div",{className:"space-y-3",children:[c.jsx(fe,{children:"Inputs"}),c.jsx(ez,{label:"A",input:S,availableFields:ce,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:Ee=>{const lt=mk(Ee,(S==null?void 0:S.aggregate)||hh(Ee));j(ih(Ee,lt))},onAggregateChange:Ee=>Uy("A",Ee),onRemove:()=>j(null),onActivate:()=>V("A"),allowMedian:g,disabled:ge}),O.inputA&&c.jsx("p",{className:"text-xs text-red-500",children:O.inputA}),C!=="scale"&&c.jsxs(c.Fragment,{children:[c.jsx(ez,{label:"B",input:k,availableFields:ce,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:Ee=>{const lt=mk(Ee,(k==null?void 0:k.aggregate)||hh(Ee));_(ih(Ee,lt))},onAggregateChange:Ee=>Uy("B",Ee),onRemove:()=>_(null),onActivate:()=>V("B"),allowMedian:g,disabled:ge}),O.inputB&&c.jsx("p",{className:"text-xs text-red-500",children:O.inputB})]}),C==="scale"&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{htmlFor:"constantFactor",children:"Multiplication Factor"}),c.jsx(pn,{id:"constantFactor",type:"number",step:"any",value:Number.isNaN(E)?"":E,onChange:Ee=>M(Ee.target.value===""?Number.NaN:Number(Ee.target.value)),className:O.constant?"border-red-500":"",placeholder:"e.g., 0.15",disabled:ge}),O.constant&&c.jsx("p",{className:"text-xs text-red-500",children:O.constant})]}),c.jsx("div",{className:"rounded-md border border-border bg-muted/40 p-3 text-sm font-mono",children:NN||"Select inputs to preview formula"}),O.inputs&&c.jsxs(SS,{variant:"destructive",children:[c.jsx(Yl,{className:"h-4 w-4"}),c.jsx(NS,{children:O.inputs})]})]})]}),b==="dimension"&&c.jsxs("div",{className:"space-y-4",children:[c.jsx(tz,{ref:be,value:T,onChange:Ee=>{P(Ee),je(!1)},onGenerate:()=>G(!0),showGenerate:!!mt&&!ge,disabled:ge}),c.jsx(nz,{onValidate:async()=>{je(!0),await Ie()},isValidating:Ue,validationResult:Te,fallbackResult:Ae,error:ke,showFallback:he,disabled:ge}),O.expression&&c.jsx("p",{className:"text-xs text-red-500",children:O.expression}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{children:"Output Type"}),c.jsxs(it,{value:Ce,onValueChange:Ee=>A(Ee),disabled:ge,children:[c.jsx(rt,{className:"h-9 w-full",children:c.jsx(at,{placeholder:"Select output type"})}),c.jsx(st,{children:sz.map(Ee=>c.jsx(we,{value:Ee.value,children:Ee.label},Ee.value))})]}),ne&&!F&&c.jsxs("p",{className:"text-xs text-muted-foreground",children:["Suggested type: ",ne]})]})]}),Pe&&(Re||He)&&c.jsxs("div",{className:"space-y-3",children:[c.jsx(OJe,{scope:$,onChange:q,showDashboardScope:Re,showDomainScope:He,error:O.scope,disabled:ge}),$==="domain"&&c.jsx($Je,{description:W,tags:I,onDescriptionChange:z,onTagsChange:L,descriptionError:O.description,disabled:ge})]})]})]}),c.jsxs(is,{children:[c.jsx(oe,{variant:"outline",onClick:Zr,children:"Cancel"}),c.jsxs(oe,{onClick:SN,disabled:ie||ge,children:[r?"Update":"Create"," ",b==="metric"?"Metric":"Dimension"]})]})]})]}),c.jsx(zJe,{open:B,onOpenChange:G,availableFields:ce,fieldType:b,onExpressionGenerated:async Ee=>{P(Ee),je(!1),ye()},endpoint:mt,dialect:p==null?void 0:p.dialect}),c.jsx(Zm,{open:K,onOpenChange:te,children:c.jsxs(Sf,{children:[c.jsxs(Nf,{children:[c.jsx(kf,{children:"Name Conflict"}),c.jsxs(Ef,{children:['A domain metric named "',y.trim(),'" already exists. Your local version will override it in this'," ",Z==="dashboard"?"dashboard":"card",". Continue?"]})]}),c.jsxs(jf,{children:[c.jsx(Tf,{onClick:()=>{Q(null)},children:"Choose Different Name"}),c.jsx(_f,{onClick:async()=>{if(Z){te(!1),ue(!0);try{await Wy(Z)}finally{ue(!1),Q(null)}}},children:"Continue"})]})]})})]})}function une({domainId:e}){const{authToken:t,tokenProps:n}=Xe(),[r,s]=w.useState(!1),[o,i]=w.useState(null),a=w.useMemo(()=>{var m;if(!e)return null;const f=(m=n==null?void 0:n.apiServiceUrl)==null?void 0:m.replace(/\/$/,""),h=`/v1/domains/${e}/calculated-metrics`;return f?`${f}${h}`:h},[e,n==null?void 0:n.apiServiceUrl]),l=w.useMemo(()=>{var m;if(!e)return null;const f=(m=n==null?void 0:n.apiServiceUrl)==null?void 0:m.replace(/\/$/,""),h=`/v1/domains/${e}/calculated-dimensions`;return f?`${f}${h}`:h},[e,n==null?void 0:n.apiServiceUrl]),u=w.useCallback(async f=>{if(!a){const h="Domain promotion is not available";throw i(h),new Error(h)}if(!(t!=null&&t.accessToken)){const h="Missing authentication token";throw i(h),new Error(h)}s(!0),i(null);try{return await Yr(a,t.accessToken,f)}catch(h){const m=(h==null?void 0:h.error)||(h==null?void 0:h.message)||"Failed to save to domain";throw i(m),new Error(m)}finally{s(!1)}},[a,t==null?void 0:t.accessToken]),d=w.useCallback(async f=>{if(!l){const h="Domain promotion is not available";throw i(h),new Error(h)}if(!(t!=null&&t.accessToken)){const h="Missing authentication token";throw i(h),new Error(h)}s(!0),i(null);try{return await Yr(l,t.accessToken,f)}catch(h){const m=(h==null?void 0:h.error)||(h==null?void 0:h.message)||"Failed to save to domain";throw i(m),new Error(m)}finally{s(!1)}},[l,t==null?void 0:t.accessToken]);return{promoteMetric:u,promoteDimension:d,isPromoting:r,error:o}}const dne=w.memo(function({context:t="editor",onFieldSelect:n,inlineFilters:r}={}){var Ie,Ue,ke,ye;const[s,o]=w.useState(""),[i,a]=w.useState("all"),[l,u]=w.useState(!1),[d,f]=w.useState(null),[h,m]=w.useState("card"),[p,g]=w.useState("metric");Le(ne=>ne.isDevMode);const b=Le(ne=>ne.card.dataSource),x=Le(ne=>ne.card.config),y=Le(ne=>ne.card),v=Le(ne=>ne.frame),C=Le(ne=>ne.actions.updateCardConfig),N=Le(ne=>ne.actions.updateFrame),{userContext:S}=$s(),{autoJoinMetadata:j}=Wa(y),{columns:k,rawColumnGroups:_,scopedFields:E,dashboardCalculatedFields:M,cardCalculatedFields:T,isLoading:P,error:F,refetch:A}=mP(),$=(b==null?void 0:b.mode)==="semanticDomain"?b.semanticDomainId:void 0,{data:q}=pP($),{promoteMetric:W,promoteDimension:z}=une({domainId:$}),I=w.useMemo(()=>[...(x==null?void 0:x.groupByColumns)||[],...(x==null?void 0:x.metricColumns)||[],...(x==null?void 0:x.detailColumns)||[]],[x==null?void 0:x.groupByColumns,x==null?void 0:x.metricColumns,x==null?void 0:x.detailColumns]);(Ue=(Ie=x==null?void 0:x.joinPlan)==null?void 0:Ie.baseEntity)==null||Ue.name,(ye=(ke=j==null?void 0:j.resolvedJoinPlan)==null?void 0:ke.baseEntity)==null||ye.name,Hte();const L=t==="editor",O=(S==null?void 0:S.type)==="organization",R=L?E:k,H=_,V=s.toLowerCase(),Y=(x==null?void 0:x.metricColumns)||[],U=(x==null?void 0:x.groupByColumns)||[],B=w.useCallback(async ne=>{await W(ne),A()},[W,A]),G=w.useCallback(async ne=>{await z(ne),A()},[z,A]),Z=ne=>ne.name.toLowerCase().includes(V)||ne.dataType.toLowerCase().includes(V)||ne.label&&ne.label.toLowerCase().includes(V)||ne.qualifiedEntityName&&ne.qualifiedEntityName.toLowerCase().includes(V),Q=R.filter(Z),K=ne=>{if(ne.role==="metric"&&ic(ne)||ne.role==="groupby"&&ne.expression)return"calculated";if(ne.dataType==="number"||ne.dataType==="integer"||ne.dataType==="float"||ne.dataType==="decimal"||ne.dataType==="currency")return"metrics";const Ce=vr(ne.dataType);return["date","string","boolean"].includes(Ce)?"dimensions":Ce==="number"?"metrics":"dimensions"},te=ne=>{const Ce=ne.filter(Z);return i==="all"?Ce:Ce.filter(Fe=>K(Fe)===i)},ie=i==="all"?Q:Q.filter(ne=>K(ne)===i),ue=L?[...M,...T]:[],he=L?te(ue):[],be=te(k).reduce((ne,Ce)=>{const Fe=Ce.qualifiedEntityName||"Other Fields";return ne[Fe]||(ne[Fe]={label:pb(Ce.entityName),fields:[]}),ne[Fe].fields.push(Ce),ne},{}),Me=ne=>ne.id||`${ne.entityName}-${ne.qualifiedEntityName}-${ne.name}-${ne.role||"field"}`,le=w.useMemo(()=>{const ne=new Map;return(L?E:k).forEach(Fe=>{ne.set(Me(Fe),QD(Fe,{joinabilityMap:(q==null?void 0:q.joinabilityMap)||null,selectedFields:I,cardConfig:x,autoJoinMetadata:j}))}),ne},[L,E,k,q==null?void 0:q.joinabilityMap,I,x,j]),ae=L?[{key:"scope-calculated",label:"Calculated Fields",fields:he}].filter(ne=>ne.fields.length>0):[],de=[...ae.map(ne=>ne.key),...Object.keys(be)],Se=Q.filter(ne=>K(ne)==="dimensions").length,ge=Q.filter(ne=>K(ne)==="metrics").length,se=Q.filter(ne=>K(ne)==="calculated").length,me=Q.length>0&&t!=="inline-filter",Oe=t==="inline-filter"?"w-full":"w-[290px]";if(P)return c.jsx("div",{className:X("flex h-full flex-col items-center justify-center py-8",Oe),children:c.jsx(tc,{size:"md",color:"muted","aria-label":"Loading data"})});if(F)return c.jsxs("div",{className:X("flex h-full flex-col items-center justify-center py-8",Oe),children:[c.jsx($l,{className:"mb-4 h-12 w-12 text-red-300"}),c.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),c.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:F.message||"Failed to load column data"})]});if(!b||!b.selectedEntities||b.selectedEntities.length===0)return c.jsxs("div",{className:X("flex flex-col items-center justify-center py-8 text-center",Oe),children:[c.jsx($l,{className:"mb-4 h-12 w-12 text-gray-300"}),c.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),c.jsx("p",{className:"px-4 text-xs text-gray-400",children:t==="filter"||t==="inline-filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]});const Pe=t==="inline-filter"?"px-3 pb-3":"px-6 pb-6",Re=t==="inline-filter"?"overflow-hidden":"",He=ne=>ne!=null&&ne.startsWith("card-source-")?ne.replace("card-source-",""):ne,Ke=(ne,Ce,Fe)=>{const Qe=He(ne.id),Ot=He(Ce.id);return Qe&&Ot&&Qe===Ot?!0:!Qe||!Ot||Fe!=null&&Fe.allowNameFallback?ne.name===Ce.name&&ne.role===Ce.role:!1},tt=(ne,Ce,Fe)=>ne.findIndex(Qe=>Ke(Qe,Ce,Fe)),mt=ne=>{if(!v)return ne;const Ce=v.calculatedFields||[],Fe=tt(Ce,ne),Qe=Fe>=0&&Ce[Fe].id!==ne.id?{...ne,id:Ce[Fe].id}:ne,Ot=Fe>=0?Ce.map((Xt,Dn)=>Dn===Fe?Qe:Xt):[...Ce,Qe];return N({calculatedFields:Ot}),Qe},gt=(ne,Ce,Fe,Qe)=>{var Xt;const Ot=tt(ne,Fe||Ce,Qe);if(Ot>=0){const Dn=(Xt=ne[Ot])==null?void 0:Xt.id,Zr=Dn&&Dn!==Ce.id?{...Ce,id:Dn}:Ce;return ne.map((Hr,Hs)=>Hs===Ot?Zr:Hr)}return[...ne,Ce]},dt=ne=>{if(ne.role==="metric")return Y.find(Ce=>Ke(Ce,ne));if(ne.role==="groupby")return U.find(Ce=>Ke(Ce,ne))},Ht=ne=>{var Ce;return(Ce=v==null?void 0:v.calculatedFields)==null?void 0:Ce.find(Fe=>Ke(Fe,ne))},Ge=ne=>{if(ne.role==="metric"){C(y.id,{metricColumns:Y.filter(Ce=>!Ke(Ce,ne,{allowNameFallback:ne.fieldScope==="dashboard"}))});return}ne.role==="groupby"&&C(y.id,{groupByColumns:U.filter(Ce=>!Ke(Ce,ne,{allowNameFallback:ne.fieldScope==="dashboard"}))})},Nt=ne=>{if(!v)return;const Ce=(v.calculatedFields||[]).filter(Fe=>!Ke(Fe,ne));N({calculatedFields:Ce})},ce=ne=>{if(!O)return;if(ne.fieldScope==="domain"){f(ne),m("domain"),g(ne.role==="metric"?"metric":"dimension"),u(!0);return}if(ne.fieldScope==="dashboard"){const Fe=Ht(ne);if(!Fe)return;f(Fe),m("dashboard"),g(Fe.role==="metric"?"metric":"dimension"),u(!0);return}const Ce=dt(ne);Ce&&(f(Ce),m("card"),g(Ce.role==="metric"?"metric":"dimension"),u(!0))},Ae=ne=>{if(O&&ne.fieldScope!=="domain"){if(ne.fieldScope==="dashboard"){Nt(ne),Ge(ne);return}Ge(ne)}},Te=ne=>{if(!O)return null;const Ce=ne.fieldScope==="domain";return c.jsxs(wf,{children:[c.jsx(Cf,{asChild:!0,children:c.jsx(oe,{variant:"ghost",size:"icon",className:"h-6 w-6","aria-label":"Calculated field actions",children:c.jsx(U8,{className:"h-4 w-4"})})}),c.jsxs(yu,{align:"end",className:"w-40",children:[c.jsx(xo,{onClick:()=>ce(ne),children:"Edit"}),c.jsx(xo,{disabled:Ce,onClick:()=>Ae(ne),children:"Delete"})]})]})};return c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:X("mt-2 flex h-full w-full grow flex-col gap-2",Pe,Re),children:[c.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[R.length>0&&c.jsxs("div",{className:"relative",children:[c.jsx(Zo,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),c.jsx(jn,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:s,onChange:ne=>o(ne.target.value)}),s&&c.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>o(""),type:"button",children:c.jsx(St,{className:"size-3.5"})})]}),me&&c.jsx(Ls,{defaultValue:"all",value:i,onValueChange:ne=>a(ne),className:"mb-4",children:c.jsxs(Cs,{className:"grid h-9 w-full grid-cols-4",children:[c.jsxs(rn,{value:"all",className:"text-xs",children:["All",c.jsx("span",{className:"ml-2 text-xs font-semibold",children:Q.length})]}),c.jsxs(rn,{value:"dimensions",className:"text-xs",children:[c.jsx(iC,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:Se})]}),c.jsxs(rn,{value:"metrics",className:"text-xs",children:[c.jsx(Lm,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:ge})]}),c.jsxs(rn,{value:"calculated",className:"text-xs",children:[c.jsx(iM,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:se})]})]})}),t==="editor"&&i==="calculated"&&O&&c.jsx("div",{className:"flex items-center justify-end gap-2",children:c.jsxs(oe,{size:"sm",variant:"outline",className:"w-full",onClick:()=>{f(null),m("card"),g("dimension"),u(!0)},children:[c.jsx(Mr,{className:"mr-2 h-3.5 w-3.5"}),"Add calculated field"]})})]}),c.jsxs(nl,{className:"min-h-0 flex-1",children:[c.jsxs(vP,{type:"multiple",defaultValue:de,className:"space-y-2",children:[ae.map(ne=>c.jsxs(fx,{value:ne.key,className:"border-none",children:[c.jsx(hx,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:ne.label}),c.jsx(qe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:ne.fields.length})]})}),c.jsx(mx,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:ne.fields.map(Ce=>{const Fe=le.get(Me(Ce)),Qe=t==="editor"&&i==="calculated";return c.jsx(Q6,{field:Ce,context:t,fieldState:Fe,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0,actions:Qe?Te(Ce):void 0},Ce.id)})})})]},ne.key)),Object.entries(be).map(([ne,Ce])=>{const Fe=H.find(Ot=>Ot.entityName===ne)||{entityName:ne,label:Ce.label},Qe=ne===rm?"Domain Calculated Fields":Fe.label||Fe.entityName;return c.jsxs(fx,{value:ne,className:"border-none",children:[c.jsx(hx,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{title:Qe,className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:Qe}),c.jsx(qe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:Ce.fields.length})]})}),c.jsx(mx,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:Ce.fields.map(Ot=>{const Xt=le.get(Me(Ot));return c.jsx(Q6,{field:Ot,context:t,fieldState:Xt,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0},Ot.id)})})})]},ne)})]}),R.length===0&&c.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[c.jsx("p",{children:"No fields found for selected data source"}),c.jsx("p",{className:"mt-1 text-xs text-gray-400",children:t==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),R.length>0&&ie.length===0&&c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),c.jsx(yi,{orientation:"horizontal"}),c.jsx(yi,{orientation:"vertical"})]})]}),c.jsx(cne,{open:l,onOpenChange:ne=>{u(ne),ne||(f(null),m("card"))},availableFields:E,existingField:d??void 0,existingFieldScope:h,initialFieldType:p,onSave:ne=>{if(ne.role==="metric"){if(d&&h==="card"){C(y.id,{metricColumns:gt(Y,ne,d)});return}C(y.id,{metricColumns:gt(Y,ne)});return}if(d&&h==="card"){C(y.id,{groupByColumns:gt(U,ne,d)});return}C(y.id,{groupByColumns:gt(U,ne)})},onSaveToDashboard:ne=>{const Ce=!!(d&&h==="dashboard"),Fe=Ce?d:void 0;if(ne.role==="metric"){const Ot=mt(ne);C(y.id,{metricColumns:gt(Y,Ot,Fe,{allowNameFallback:Ce})});return}const Qe=mt(ne);C(y.id,{groupByColumns:gt(U,Qe,Fe,{allowNameFallback:Ce})})},cardId:y.id,onPromoteMetricToDomain:$?B:void 0,onPromoteDimensionToDomain:$?G:void 0,domainId:$})]})}),fne=w.memo(function({context:t="editor"}={}){return c.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",c.jsx(dne,{context:t})," "]})});function hne(){const e=Le(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=Cr();w.useEffect(()=>{var m;if(!e)return;const{tableName:i,schemaName:a,databaseName:l,connectionId:u}=gP(e),d=(m=e.selectedEntities)==null?void 0:m[0],h=(d==null?void 0:d.type)==="model"&&"id"in d?d.id:"";t(u||""),n(l||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function set(){hne();const e=J(l=>l.selectedSheetId),t=J(l=>l.selectedFrameId),n=J(l=>l.dashboard),r=J(l=>l.actions.getSelectedFrame),{setSelectedFrameId:s}=Bt(),{setCard:o}=Cr(),i=Le(l=>l.card.dataSource);return w.useEffect(()=>{var u,d;let l=r();if(!l){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(m=>m.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),l=h)}if(l){const f=l.cards.find(h=>h.id===l.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function oet(){const e=J(o=>o.dashboard.filterLayout),{setFilterLayout:t}=Bt(),n=(e==null?void 0:e.displayMode)||"canvas",r=(e==null?void 0:e.toolbarWrap)??!1,s=(e==null?void 0:e.showDownloadButton)??!1;return c.jsxs(gs,{children:[c.jsx(bs,{asChild:!0,children:c.jsx(oe,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0","aria-label":"Filter display settings",children:c.jsx(Ll,{className:"h-4 w-4"})})}),c.jsx(xs,{className:"w-[280px]",align:"end",children:c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{children:[c.jsx("h4",{className:"mb-3 text-sm font-medium",children:"Filter Display"}),c.jsxs(so,{value:n,onValueChange:o=>t({displayMode:o}),className:"space-y-2",children:[c.jsxs("div",{className:"flex items-start space-x-3",children:[c.jsx(xn,{value:"canvas",id:"canvas",className:"mt-0.5"}),c.jsxs("div",{className:"grid gap-0.5",children:[c.jsx(fe,{htmlFor:"canvas",className:"cursor-pointer font-normal",children:"Canvas Cards"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Filters as draggable, resizable cards on the dashboard"})]})]}),c.jsxs("div",{className:"flex items-start space-x-3",children:[c.jsx(xn,{value:"toolbar",id:"toolbar",className:"mt-0.5"}),c.jsxs("div",{className:"grid gap-0.5",children:[c.jsx(fe,{htmlFor:"toolbar",className:"cursor-pointer font-normal",children:"Toolbar"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Compact horizontal toolbar below dashboard controls"})]})]})]})]}),n==="toolbar"&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-center space-x-2 border-t pt-4",children:[c.jsx(un,{id:"wrap",checked:r,onCheckedChange:o=>t({toolbarWrap:o===!0})}),c.jsx(fe,{htmlFor:"wrap",className:"cursor-pointer text-sm font-normal",children:"Wrap filters to multiple lines"})]}),c.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[c.jsx(un,{id:"download",checked:s,onCheckedChange:o=>t({showDownloadButton:o===!0})}),c.jsx(fe,{htmlFor:"download",className:"cursor-pointer text-sm font-normal",children:"Show download button"})]})]}),c.jsx("p",{className:"border-t pt-3 text-xs text-muted-foreground",children:"Individual filters can override this setting in their configuration."})]})})]})}function iet(){const e=J(n=>n.actions.setShowFilters),{hasEntities:t}=set();return c.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col overflow-hidden border-l",children:[c.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[c.jsx(fe,{className:"px-2 text-base",children:"Dashboard Filters"}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(oet,{}),c.jsx(oe,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:c.jsx(WX,{})})]})]}),!t&&c.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[c.jsx($l,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),c.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&c.jsx("div",{className:"flex grow overflow-y-auto",children:c.jsx(Ry,{collisionDetection:My,children:c.jsx(Ay,{items:[],strategy:NA,children:c.jsx(fne,{context:"filter"})})})})]})}function aet(){const e=J(r=>r.dashboard.filters),t=J(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?c.jsx("div",{className:X("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>c.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[c.jsx(bA,{filter:r}),c.jsx(Ep,{filter:r})]},r.id))}):null}function cet(){const e=J(r=>r.showFilters),t=J(r=>r.isVisualEditing),n=J(r=>r.isDashboardEditing);return c.jsxs("div",{role:"dashboard-plus-main",className:X("",{"max-h-0 overflow-hidden":t,"flex grow overflow-hidden":!t}),children:[c.jsxs("section",{className:"flex grow flex-col overflow-y-auto",children:[n&&c.jsx(aet,{}),c.jsx(Fte,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:c.jsx(iet,{})})]})}const uet=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-DgtdC01F.js"))),det=w.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-BIYh-RkG.js"))),fet=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-Bmbz02KL.js"))),het=w.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-DIFmTV1p.js")).then(e=>({default:e.ResourceManagementPanel})));function met({showControls:e=!1,showFooter:t=!0,...n}){const r=J(l=>l.isDashboardPanelOpen),s=J(l=>l.isVisualEditing),o=J(l=>l.showDashboardJSON),i=J(l=>l.actions.setIsDashboardPanelOpen),{preferences:a}=n;return c.jsx(sa,{FallbackComponent:FS,children:c.jsxs(oM,{dashboardProps:n,children:[c.jsx(Gde,{}),c.jsx(hP,{componentType:"surfboard",componentId:n.id}),c.jsx(fP,{children:c.jsxs(Ote,{preferences:a,children:[o&&c.jsx(w.Suspense,{fallback:null,children:c.jsx(fet,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&c.jsx(w.Suspense,{fallback:null,children:c.jsx(uet,{})}),c.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&c.jsx(w.Suspense,{fallback:null,children:c.jsx(het,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),c.jsx("div",{className:"flex min-w-0 flex-1",children:c.jsxs(NI,{...n,type:"dashboard",children:[s&&c.jsx(w.Suspense,{fallback:null,children:c.jsx(det,{})}),c.jsx(cet,{})]})})]})]})]})})]})})}const mne=D.forwardRef(({className:e,...t},n)=>c.jsx(Fy,{className:X("peer inline-flex h-[22px] w-[36px] shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:n,children:c.jsx(kA,{className:X("pointer-events-none block size-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));mne.displayName=Fy.displayName;var pet=Object.defineProperty,get=(e,t,n)=>t in e?pet(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,wv=(e,t,n)=>get(e,typeof t!="symbol"?t+"":t,n);const bet={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},xet={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{if(typeof window<"u"&&e in window)return window[e];if(typeof global<"u"&&e in global)return global[e]})();return typeof r=="function"?r.bind(n):void 0}},yet={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function vet(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function pne(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const wet={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=pne(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},Cet={stringify:e=>`${e}`,parse:e=>parseFloat(e)},Net={stringify:e=>e,parse:e=>e},gk={string:Net,number:Cet,boolean:bet,function:xet,method:wet,json:yet},ag=Symbol.for("r2wc.render"),Cv=Symbol.for("r2wc.connected"),Ku=Symbol.for("r2wc.context"),To=Symbol.for("r2wc.props");function jet(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),l={},u={},d={},f={};for(const m of i){l[m]=Array.isArray(t.props)?"string":t.props[m];const p=vet(m);d[m]=p,f[p]=m}for(const m of a)u[m]=Array.isArray(t.events)?{}:t.events[m];class h extends HTMLElement{constructor(){super(),wv(this,o,!0),wv(this,s),wv(this,r,{}),wv(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[To].container=this.container;for(const p of i){const g=d[p],b=this.getAttribute(g),x=l[p],y=x?gk[x]:null;if(x==="method"){const v=pne(g);Object.defineProperty(this[To].container,v,{enumerable:!0,configurable:!0,get(){return this[To][v]},set(C){this[To][v]=C,this[ag]()}}),this[To][p]=y.parse(b,g,this)}y!=null&&y.parse&&b&&(this[To][p]=y.parse(b,g,this))}for(const p of a)this[To][p]=g=>{const b=p.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[p]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[Cv]=!0,this[ag]()}disconnectedCallback(){this[Cv]=!1,this[Ku]&&n.unmount(this[Ku]),delete this[Ku]}attributeChangedCallback(p,g,b){const x=f[p],y=l[x],v=y?gk[y]:null;x in l&&v!=null&&v.parse&&b&&(this[To][x]=v.parse(b,p,this),this[ag]())}[(o=Cv,s=Ku,r=To,ag)](){this[Cv]&&(this[Ku]?n.update(this[Ku],this[To]):this[Ku]=n.mount(this.container,e,this[To]))}}for(const m of i){const p=d[m],g=l[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[To][m]},set(b){this[To][m]=b;const x=g?gk[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,p,this);this.getAttribute(p)!==y&&this.setAttribute(p,y)}else this[ag]()}})}return h}function ket(e,t,n){const r=fre.createRoot(e),s=w.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function Eet({root:e,ReactComponent:t},n){const r=w.createElement(t,n);e.render(r)}function _et({root:e}){e.unmount()}function Tet(e,t={}){return jet(e,t,{mount:ket,update:Eet,unmount:_et})}const Met={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",currentTheme:"string",customCards:"json",customStyle:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},Det=Tet($te,{props:Met});function oz(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Iet(e){if(Array.isArray(e))return e}function Ret(e,t,n){return(t=zet(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Aet(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,s,o,i,a=[],l=!0,u=!1;try{if(o=(n=n.call(e)).next,t!==0)for(;!(l=(r=o.call(n)).done)&&(a.push(r.value),a.length!==t);l=!0);}catch(d){u=!0,s=d}finally{try{if(!l&&n.return!=null&&(i=n.return(),Object(i)!==i))return}finally{if(u)throw s}}return a}}function Pet(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1077
+ `)}})}});var aQe=eXe(()=>fte(Ci([ir({type:Vt("text-start"),id:ft(),providerMetadata:jr.optional()}),ir({type:Vt("text-delta"),id:ft(),delta:ft(),providerMetadata:jr.optional()}),ir({type:Vt("text-end"),id:ft(),providerMetadata:jr.optional()}),ir({type:Vt("error"),errorText:ft()}),ir({type:Vt("tool-input-start"),toolCallId:ft(),toolName:ft(),providerExecuted:ho().optional(),dynamic:ho().optional()}),ir({type:Vt("tool-input-delta"),toolCallId:ft(),inputTextDelta:ft()}),ir({type:Vt("tool-input-available"),toolCallId:ft(),toolName:ft(),input:wa(),providerExecuted:ho().optional(),providerMetadata:jr.optional(),dynamic:ho().optional()}),ir({type:Vt("tool-input-error"),toolCallId:ft(),toolName:ft(),input:wa(),providerExecuted:ho().optional(),providerMetadata:jr.optional(),dynamic:ho().optional(),errorText:ft()}),ir({type:Vt("tool-output-available"),toolCallId:ft(),output:wa(),providerExecuted:ho().optional(),dynamic:ho().optional(),preliminary:ho().optional()}),ir({type:Vt("tool-output-error"),toolCallId:ft(),errorText:ft(),providerExecuted:ho().optional(),dynamic:ho().optional()}),ir({type:Vt("reasoning-start"),id:ft(),providerMetadata:jr.optional()}),ir({type:Vt("reasoning-delta"),id:ft(),delta:ft(),providerMetadata:jr.optional()}),ir({type:Vt("reasoning-end"),id:ft(),providerMetadata:jr.optional()}),ir({type:Vt("source-url"),sourceId:ft(),url:ft(),title:ft().optional(),providerMetadata:jr.optional()}),ir({type:Vt("source-document"),sourceId:ft(),mediaType:ft(),title:ft(),filename:ft().optional(),providerMetadata:jr.optional()}),ir({type:Vt("file"),url:ft(),mediaType:ft(),providerMetadata:jr.optional()}),ir({type:ate(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:ft().optional(),data:wa(),transient:ho().optional()}),ir({type:Vt("start-step")}),ir({type:Vt("finish-step")}),ir({type:Vt("start"),messageId:ft().optional(),messageMetadata:wa().optional()}),ir({type:Vt("finish"),finishReason:ste(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:wa().optional()}),ir({type:Vt("abort")}),ir({type:Vt("message-metadata"),messageMetadata:wa()})])));function lQe(e){return e.type.startsWith("data-")}function vte(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const s=t[r];if(s===void 0)continue;const o=r in e?e[r]:void 0,i=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),a=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);i&&a?n[r]=vte(o,s):n[r]=s}return n}function cQe(e){const t=["ROOT"];let n=-1,r=null;function s(l,u,d){switch(l){case'"':{n=u,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,r=u,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function o(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":s(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=l,t.pop();break}default:{n=l,s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l)):n=l;break}}}let a=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?a+="true".slice(d.length):"false".startsWith(d)?a+="false".slice(d.length):"null".startsWith(d)&&(a+="null".slice(d.length))}}return a}async function wte(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await z1({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await z1({text:cQe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Yv(e){return e.type.startsWith("tool-")}function uQe(e){return e.type==="dynamic-tool"}function CT(e){return Yv(e)||uQe(e)}function q6(e){return e.type.split("-").slice(1).join("-")}function dQe({lastMessage:e,messageId:t}){return{message:(e==null?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function fQe({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await r(async({state:u,write:d})=>{var f,h,m,p;function g(C){const S=u.message.parts.filter(Yv).find(j=>j.toolCallId===C);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function b(C){const S=u.message.parts.filter(j=>j.type==="dynamic-tool").find(j=>j.toolCallId===C);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function x(C){var N;const S=u.message.parts.find(_=>Yv(_)&&_.toolCallId===C.toolCallId),j=C,k=S;S!=null?(S.state=C.state,k.input=j.input,k.output=j.output,k.errorText=j.errorText,k.rawInput=j.rawInput,k.preliminary=j.preliminary,k.providerExecuted=(N=j.providerExecuted)!=null?N:S.providerExecuted,j.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:`tool-${C.toolName}`,toolCallId:C.toolCallId,state:C.state,input:j.input,output:j.output,rawInput:j.rawInput,errorText:j.errorText,providerExecuted:j.providerExecuted,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}function y(C){var N,S;const j=u.message.parts.find(E=>E.type==="dynamic-tool"&&E.toolCallId===C.toolCallId),k=C,_=j;j!=null?(j.state=C.state,_.toolName=C.toolName,_.input=k.input,_.output=k.output,_.errorText=k.errorText,_.rawInput=(N=k.rawInput)!=null?N:_.rawInput,_.preliminary=k.preliminary,_.providerExecuted=(S=k.providerExecuted)!=null?S:j.providerExecuted,k.providerMetadata!=null&&j.state==="input-available"&&(j.callProviderMetadata=k.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:C.toolName,toolCallId:C.toolCallId,state:C.state,input:k.input,output:k.output,errorText:k.errorText,preliminary:k.preliminary,providerExecuted:k.providerExecuted,...k.providerMetadata!=null?{callProviderMetadata:k.providerMetadata}:{}})}async function v(C){if(C!=null){const N=u.message.metadata!=null?vte(u.message.metadata,C):C;t!=null&&await B6({value:N,schema:t}),u.message.metadata=N}}switch(a.type){case"text-start":{const C={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=C,u.message.parts.push(C),d();break}case"text-delta":{const C=u.activeTextParts[a.id];C.text+=a.delta,C.providerMetadata=(f=a.providerMetadata)!=null?f:C.providerMetadata,d();break}case"text-end":{const C=u.activeTextParts[a.id];C.state="done",C.providerMetadata=(h=a.providerMetadata)!=null?h:C.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const C={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=C,u.message.parts.push(C),d();break}case"reasoning-delta":{const C=u.activeReasoningParts[a.id];C.text+=a.delta,C.providerMetadata=(m=a.providerMetadata)!=null?m:C.providerMetadata,d();break}case"reasoning-end":{const C=u.activeReasoningParts[a.id];C.providerMetadata=(p=a.providerMetadata)!=null?p:C.providerMetadata,C.state="done",delete u.activeReasoningParts[a.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),d();break}case"tool-input-start":{const C=u.message.parts.filter(Yv);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:C.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const C=u.partialToolCalls[a.toolCallId];C.text+=a.inputTextDelta;const{value:N}=await wte(C.text);C.dynamic?y({toolCallId:a.toolCallId,toolName:C.toolName,state:"input-streaming",input:N}):x({toolCallId:a.toolCallId,toolName:C.toolName,state:"input-streaming",input:N}),d();break}case"tool-input-available":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d();break}case"tool-output-available":{if(a.dynamic){const C=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:C.toolName,state:"output-available",input:C.input,output:a.output,preliminary:a.preliminary})}else{const C=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:q6(C),state:"output-available",input:C.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const C=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:C.toolName,state:"output-error",input:C.input,errorText:a.errorText,providerExecuted:a.providerExecuted})}else{const C=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:q6(C),state:"output-error",input:C.input,rawInput:C.rawInput,errorText:a.errorText,providerExecuted:a.providerExecuted})}d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{a.messageId!=null&&(u.message.id=a.messageId),await v(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&d();break}case"finish":{a.finishReason!=null&&(u.finishReason=a.finishReason),await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"message-metadata":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"error":{s==null||s(new Error(a.errorText));break}default:if(lQe(a)){(n==null?void 0:n[a.type])!=null&&await B6({value:a.data,schema:n[a.type]});const C=a;if(C.transient){i==null||i(C);break}const N=C.id!=null?u.message.parts.find(S=>C.type===S.type&&C.id===S.id):void 0;N!=null?N.data=C.data:u.message.parts.push(C),i==null||i(C),d()}}l.enqueue(a)})}}))}async function hQe({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:r}=await n.read();if(r)break}}catch(r){t==null||t(r)}finally{n.releaseLock()}}Vy({prefix:"aitxt",size:24});Vy({prefix:"aiobj",size:24});var mQe=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{await e(),t()}catch(r){n(r)}}),this.processQueue()})}};Vy({prefix:"aiobj",size:24});var pQe={};XXe(pQe,{object:()=>bQe,text:()=>gQe});var gQe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),bQe=({schema:e})=>{const t=KXe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await wte(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const s=r.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:n},r){const s=await z1({text:n});if(!s.success)throw new U6({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const o=await aP({value:s.value,schema:t});if(!o.success)throw new U6({message:"No object generated: response did not match schema.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return o.value}}};async function xQe(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async t=>{const{name:n,type:r}=t,s=await new Promise((o,i)=>{const a=new FileReader;a.onload=l=>{var u;o((u=l.target)==null?void 0:u.result)},a.onerror=l=>i(l),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var yQe=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:s,prepareSendMessagesRequest:o,prepareReconnectToStreamRequest:i}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=s,this.prepareSendMessagesRequest=o,this.prepareReconnectToStreamRequest=i}async sendMessages({abortSignal:e,...t}){var n,r,s,o,i;const a=await oh(this.body),l=await oh(this.headers),u=await oh(this.credentials),d={...ed(l),...ed(t.headers)},f=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:d,credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),h=(r=f==null?void 0:f.api)!=null?r:this.api,m=(f==null?void 0:f.headers)!==void 0?ed(f.headers):d,p=(f==null?void 0:f.body)!==void 0?f.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},g=(s=f==null?void 0:f.credentials)!=null?s:u,x=await((o=this.fetch)!=null?o:globalThis.fetch)(h,{method:"POST",headers:L6({"Content-Type":"application/json",...m},`ai-sdk/${W6}`,$6()),body:JSON.stringify(p),credentials:g,signal:e});if(!x.ok)throw new Error((i=await x.text())!=null?i:"Failed to fetch the chat response.");if(!x.body)throw new Error("The response body is empty.");return this.processResponseStream(x.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await oh(this.body),a=await oh(this.headers),l=await oh(this.credentials),u={...ed(a),...ed(e.headers)},d=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:u,credentials:l,requestMetadata:e.metadata})),f=(n=d==null?void 0:d.api)!=null?n:`${this.api}/${e.chatId}/stream`,h=(d==null?void 0:d.headers)!==void 0?ed(d.headers):u,m=(r=d==null?void 0:d.credentials)!=null?r:l,g=await((s=this.fetch)!=null?s:globalThis.fetch)(f,{method:"GET",headers:L6(h,`ai-sdk/${W6}`,$6()),credentials:m});if(g.status===204)return null;if(!g.ok)throw new Error((o=await g.text())!=null?o:"Failed to fetch the chat response.");if(!g.body)throw new Error("The response body is empty.");return this.processResponseStream(g.body)}},cP=class extends yQe{constructor(e={}){super(e)}processResponseStream(e){return rXe({stream:e,schema:aQe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},vQe=class{constructor({generateId:e=YZe,id:t=e(),transport:n=new cP,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new mQe,this.sendMessage=async(f,h)=>{var m,p,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(m=this.lastMessage)==null?void 0:m.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await xQe(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:x=f,f.messageId!=null){const y=this.state.messages.findIndex(v=>v.id===f.messageId);if(y===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[y].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,y+1),this.state.replaceMessage(y,{...x,id:f.messageId,role:(p=x.role)!=null?p:"user",metadata:f.metadata})}else this.state.pushMessage({...x,id:(g=x.id)!=null?g:this.generateId(),role:(b=x.role)!=null?b:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const m=f==null?this.state.messages.length-1:this.state.messages.findIndex(p=>p.id===f);if(m===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[m].role==="assistant"?m:m+1),await this.makeRequest({trigger:"regenerate-message",messageId:f,...h})},this.resumeStream=async(f={})=>{await this.makeRequest({trigger:"resume-stream",...f})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolOutput=async({state:f="output-available",tool:h,toolCallId:m,output:p,errorText:g})=>this.jobExecutor.run(async()=>{var b,x;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(C=>CT(C)&&C.toolCallId===m?{...C,state:f,output:p,errorText:g}:C)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(C=>CT(C)&&C.toolCallId===m?{...C,state:f,output:p,errorText:g}:C)),this.status!=="streaming"&&this.status!=="submitted"&&((b=this.sendAutomaticallyWhen)!=null&&b.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(x=this.lastMessage)==null?void 0:x.id})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=l,this.onData=u,this.sendAutomaticallyWhen=d}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:s}){var o,i,a,l;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;let d=!1,f=!1,h=!1;try{const m={state:dQe({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};m.abortController.signal.addEventListener("abort",()=>{d=!0}),this.activeResponse=m;let p;if(e==="resume-stream"){const b=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(b==null){this.setStatus({status:"ready"});return}p=b}else p=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:m.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const g=b=>this.jobExecutor.run(()=>b({state:m.state,write:()=>{var x;this.setStatus({status:"streaming"}),m.state.message.id===((x=this.lastMessage)==null?void 0:x.id)?this.state.replaceMessage(this.state.messages.length-1,m.state.message):this.state.pushMessage(m.state.message)}}));await hQe({stream:fQe({stream:p,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:g,onError:b=>{throw b}}),onError:b=>{throw b}}),this.setStatus({status:"ready"})}catch(m){if(d||m.name==="AbortError")return d=!0,this.setStatus({status:"ready"}),null;h=!0,m instanceof TypeError&&(m.message.toLowerCase().includes("fetch")||m.message.toLowerCase().includes("network"))&&(f=!0),this.onError&&m instanceof Error&&this.onError(m),this.setStatus({status:"error",error:m})}finally{try{(i=this.onFinish)==null||i.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:d,isDisconnect:f,isError:h,finishReason:(o=this.activeResponse)==null?void 0:o.state.finishReason})}catch(m){console.error(m)}this.activeResponse=void 0}(a=this.sendAutomaticallyWhen)!=null&&a.call(this,{messages:this.state.messages})&&!h&&await this.makeRequest({trigger:"submit-message",messageId:(l=this.lastMessage)==null?void 0:l.id,metadata:t,headers:n,body:r})}};function wQe({messages:e}){const t=e[e.length-1];if(!t||t.role!=="assistant")return!1;const n=t.parts.reduce((s,o,i)=>o.type==="step-start"?i:s,-1),r=t.parts.slice(n+1).filter(CT).filter(s=>!s.providerExecuted);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function CQe(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...o){clearTimeout(n);const i=Date.now(),a=i-r,l=t-a;l<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},l)}}var SQe=CQe;const NQe=hf(SQe);var Cte=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Kn=(e,t,n)=>(Cte(e,t,"read from private field"),n?n.call(e):t.get(e)),ga=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},Cc=(e,t,n,r)=>(Cte(e,t,"write to private field"),t.set(e,n),n);function jQe(e,t){return t!=null?NQe(e,t):e}var Jo,Gv,Kv,Ig,Rg,Ag,dh,ST,NT,kQe=class{constructor(e=[]){ga(this,Jo,void 0),ga(this,Gv,"ready"),ga(this,Kv,void 0),ga(this,Ig,new Set),ga(this,Rg,new Set),ga(this,Ag,new Set),this.pushMessage=t=>{Cc(this,Jo,Kn(this,Jo).concat(t)),Kn(this,dh).call(this)},this.popMessage=()=>{Cc(this,Jo,Kn(this,Jo).slice(0,-1)),Kn(this,dh).call(this)},this.replaceMessage=(t,n)=>{Cc(this,Jo,[...Kn(this,Jo).slice(0,t),this.snapshot(n),...Kn(this,Jo).slice(t+1)]),Kn(this,dh).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?jQe(t,n):t;return Kn(this,Ig).add(r),()=>{Kn(this,Ig).delete(r)}},this["~registerStatusCallback"]=t=>(Kn(this,Rg).add(t),()=>{Kn(this,Rg).delete(t)}),this["~registerErrorCallback"]=t=>(Kn(this,Ag).add(t),()=>{Kn(this,Ag).delete(t)}),ga(this,dh,()=>{Kn(this,Ig).forEach(t=>t())}),ga(this,ST,()=>{Kn(this,Rg).forEach(t=>t())}),ga(this,NT,()=>{Kn(this,Ag).forEach(t=>t())}),Cc(this,Jo,e)}get status(){return Kn(this,Gv)}set status(e){Cc(this,Gv,e),Kn(this,ST).call(this)}get error(){return Kn(this,Kv)}set error(e){Cc(this,Kv,e),Kn(this,NT).call(this)}get messages(){return Kn(this,Jo)}set messages(e){Cc(this,Jo,[...e]),Kn(this,dh).call(this)}};Jo=new WeakMap;Gv=new WeakMap;Kv=new WeakMap;Ig=new WeakMap;Rg=new WeakMap;Ag=new WeakMap;dh=new WeakMap;ST=new WeakMap;NT=new WeakMap;var fh,Y6=class extends vQe{constructor({messages:e,...t}){const n=new kQe(e);super({...t,state:n}),ga(this,fh,void 0),this["~registerMessagesCallback"]=(r,s)=>Kn(this,fh)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>Kn(this,fh)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>Kn(this,fh)["~registerErrorCallback"](r),Cc(this,fh,n)}};fh=new WeakMap;function Ste({experimental_throttle:e,resume:t=!1,...n}={}){const r=w.useRef("chat"in n?n.chat:new Y6(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new Y6(n));const o="id"in n?n.id:null,i=w.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=w.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),l=w.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=w.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=w.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return w.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:a,setMessages:d,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:u,resumeStream:r.current.resumeStream,status:l,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput}}function EQe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function _Qe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function TQe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function MQe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function Nte(e){return e.map(r=>{const s=r.connectionType==="API"||r.connectionType==="S3"||r.connectionType==="S3Tables"?"DuckDb":r.connectionType;return r.datamodelName?{...r,databaseName:"",schemaName:"",tableName:"",connectionType:s,tableReferenceFormat:"dm.{table_name}"}:{...r,connectionType:s,tableReferenceFormat:MQe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function jte(e){var n,r;if(!e)return"";let t="";try{const s=JSON.parse((e==null?void 0:e.message)||"{}");t=((r=(n=s==null?void 0:s.error)==null?void 0:n.lastError)==null?void 0:r.message)||(s==null?void 0:s.error)||e.message}catch{t=e.message}return t}function DQe(){var b;const{authToken:e,tokenProps:t}=Xe(),n=J(x=>x.dashboard.aiScopeTables),r=(b=tC().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=Ste({transport:new cP({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=ua.getState();return{assistantId:"dashboard-assistant",assistantProfileId:r,aiContext:x.currentAIContext,reasoningEffort:x.reasoningEffort,showReasoning:x.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:x,body:y})=>({body:{...y,messages:lY(x)}})}),onToolCall:m,sendAutomaticallyWhen:wQe,onFinish({isAbort:x,isDisconnect:y,isError:v}){console.log(x?"[Dashboard Assistant] Stream aborted by user":y?"[Dashboard Assistant] Stream disconnected (network error)":v?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully")},onError(x){var y;if(x.name==="AbortError"||(y=x.message)!=null&&y.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)");return}console.error("[Dashboard Assistant] Stream error:",x)}});async function m({toolCall:x}){if(x.toolName==="getCurrentTableScope"&&u({tool:x.toolName,toolCallId:x.toolCallId,output:{tables:Nte(n||[])}}),x.toolName==="getDashboardContext"){const y=J.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const p=!["ready","error"].includes(l),g=jte(d);return{sendMessage:s,regenerate:a,isLoading:p,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function kte(){var u;const{authToken:e,tokenProps:t}=Xe(),n=(u=tC().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=mn({queryKey:["assistant-profile",n],queryFn:()=>rr(`${t.apiServiceUrl}/v1/assistant/${n}`,(e==null?void 0:e.accessToken)||""),enabled:r()});return{assistantProfile:s==null?void 0:s.assistantProfile,isLoading:o,isFetching:i,isError:a}}function Ete({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:c.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[c.jsxs("div",{className:"mb-3 flex items-center",children:[c.jsx(B8,{className:"mr-2 h-4 w-4 text-muted-foreground"}),c.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),c.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>c.jsx(oe,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function B1(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(NM,{className:r});case"view":return c.jsx(ru,{className:r});case"materialized view":return c.jsx($ie,{className:r});case"model":return c.jsx(iC,{className:r});case"file":return c.jsx(bi,{className:r});case"dataset":return c.jsx($l,{className:r});case"upload":return c.jsx(_M,{className:r});case"url":return c.jsx(Y8,{className:r});default:return c.jsx(Ix,{className:r})}}const _te=D.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(Zo,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(Bs.Input,{ref:n,className:X("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));_te.displayName=Bs.Input.displayName;const yv=e=>e.label||(e==null?void 0:e.name),G6=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function IQe({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:u}){const{tokenProps:d}=Xe(),f=(d==null?void 0:d.type)==="dashboard",[h,m]=w.useState(""),[p,g]=w.useState(""),b=s.filter(S=>{if(!h)return!0;const j=yv(S).toLowerCase(),k=G6(S).toLowerCase(),_=h.toLowerCase();return j.includes(_)||k.includes(_)});w.useEffect(()=>{e||(m(""),g(""))},[e]),w.useEffect(()=>{b.length>0&&!p&&g(yv(b[0]))},[b,p]);const x=()=>{if(!p)return;const S=b.find(j=>yv(j)===p);S&&(o.some(k=>"id"in S&&"id"in k?S.id===k.id:S.name===k.name&&S.connectionId===k.connectionId)||t(S),i(S),r())},y=S=>{(S.key==="Tab"||S.key==="Enter")&&(S.preventDefault(),x())};if(!e)return null;const v=S=>o.some(j=>"id"in S&&"id"in j?S.id===j.id:S.name===j.name&&S.connectionId===j.connectionId),C=o.length===s.length,N=o.length>0;return c.jsx(c.Fragment,{children:c.jsxs(cp,{shouldFilter:!1,value:p,onValueChange:g,onKeyDown:y,children:[s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[c.jsx(_te,{placeholder:"Search entities...",value:h,onValueChange:m,className:"flex-1 border-0",autoFocus:!0}),!f&&c.jsxs(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u==null||u()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[c.jsx(Mr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[c.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),a==null||a()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},disabled:C,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),N&&c.jsxs(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),l==null||l()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[c.jsx(St,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),c.jsxs(up,{className:"min-h-60",children:[c.jsx(dp,{children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[c.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&c.jsxs(oe,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u==null||u()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[c.jsx(Mr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx(fp,{children:b.map((S,j)=>{const k=v(S),_="id"in S?S.id:`${S.connectionId}-${S.name}`,E=yv(S);return c.jsxs(hp,{value:E,onSelect:()=>{k?n==null||n(S):t(S)},onMouseDown:M=>{M.preventDefault(),M.stopPropagation()},className:X("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[c.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:B1(S.type)}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate font-medium",children:E}),c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:G6(S)})]}),k&&c.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:c.jsx(Ar,{className:"h-3 w-3 text-background"})})]},_)})})]})]})})}const jT=e=>e.name||e.name,RQe=e=>{const t=jT(e),n="description"in e?e.description:"",r=e.database||"",s=e.schema||"";return c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"font-medium",children:t}),n&&c.jsx("div",{className:"text-sm text-muted-foreground",children:n}),c.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,s&&` • Schema: ${s}`]})]})};function AQe({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r}){const[s,o]=w.useState(!1),i=e.length>0;e.length,t.length,e.length<t.length;const a=e.length>=3?e.slice(0,2):e,l=e.length>=3?e.slice(2):[],u=l.length>0;return c.jsx(Ln,{children:c.jsx("div",{className:"space-y-2",children:i&&c.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.map((d,f)=>{const h="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs(ln,{children:[c.jsx(cn,{asChild:!0,children:c.jsxs(qe,{variant:"secondary",className:"group relative cursor-pointer gap-2 transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[B1(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:jT(d)}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(d),children:c.jsx(St,{className:"h-3 w-3"})})]})}),c.jsx(dn,{side:"top",className:"max-w-xs",children:RQe(d)})]},h)}),u&&c.jsxs(ln,{open:s,onOpenChange:o,children:[c.jsx(cn,{asChild:!0,children:c.jsxs(qe,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>o(!0),children:[c.jsx(U8,{className:"h-3 w-3"}),c.jsxs("span",{className:"text-xs",children:[l.length," more"]}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(l),children:c.jsx(St,{className:"h-3 w-3"})})]})}),c.jsx(dn,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),c.jsx("div",{className:"space-y-2",children:l.map(d=>{const f="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:B1(d.type,{size:"h-3 w-3"})}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate text-sm font-medium",children:jT(d)}),c.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(d),l.length===1&&o(!1)},children:c.jsx(St,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function Tte(e){return e.type==="dataset"&&e.label||e.name}function PQe(e){const t=[];return t.push({label:"Type",value:e.type}),t.push({label:"Name",value:e.name}),e.connectionType&&t.push({label:"Connection",value:e.connectionType}),e.database&&t.push({label:"Database",value:e.database}),e.schema&&t.push({label:"Schema",value:e.schema}),e.type==="dataset"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="dataset"&&e.description&&t.push({label:"Description",value:e.description}),e.type==="model"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="model"&&e.description&&t.push({label:"Description",value:e.description}),t}function FQe({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:c.jsxs("div",{className:"mb-4 space-y-2",children:[c.jsxs(fe,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),c.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:c.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>c.jsxs(qe,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[c.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),Tte(n),c.jsx("button",{onClick:s=>{s.stopPropagation(),t(n)},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-0 transition-opacity hover:bg-red-100 group-hover:opacity-100",children:c.jsx(St,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function OQe(e){const{tokenProps:t}=Xe(),n=J(l=>l.authToken)||e;Le(l=>l.selectedConnectionId),Le(l=>{var u,d;return(d=(u=l==null?void 0:l.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=mn({queryKey:["semantic-domains"],queryFn:()=>rr(`${t.apiServiceUrl}/v1/domains`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)});return{isPending:s,error:a,semanticDomainsData:o,semanticDomains:(o==null?void 0:o.domains)||[],isSemanticDomainsLoading:i,isSemanticDomainsError:a,refetchSemanticDomains:r}}function $Qe(e,t){const{tokenProps:n}=Xe(),r=J(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:l}=mn({queryKey:["datasets",e],queryFn:()=>rr(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:o,error:l,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:l,refetchDatasets:s}}function LQe(e){var g,b;const{tokenProps:t}=Xe(),n=J(x=>x.authToken)||e,{connections:r}=Ni(e),s=Le(x=>{var y,v;return(v=(y=x==null?void 0:x.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(x=>x.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(x){var y;return!s||!x?!1:!!((y=o==null?void 0:o.capabilities)!=null&&y.path.includes("database"))}const{data:d,isPending:f,error:h,refetch:m}=mn({queryKey:["databases",s],queryFn:()=>rr(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),p=(b=d==null?void 0:d.databases)==null?void 0:b.map(x=>({id:x.database_name,name:x.database_name}));return{isPending:f,error:h,databases:p||[],refetch:m,label:l}}function zQe(e){var g;const{tokenProps:t}=Xe(),n=J(b=>b.authToken)||e,{connections:r}=Ni(e),s=Le(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=Le(b=>{var x,y,v;return(v=(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(b=>b.id===s),a=i==null?void 0:i.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){var b;return!(!s||!((b=i==null?void 0:i.capabilities)!=null&&b.path.includes("schema"))||!o)}const{data:d,isPending:f,error:h,refetch:m}=mn({queryKey:["schemas",s,o],queryFn:()=>rr(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),p=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:p||[],refetch:m,label:l}}function Mte(e){const{tokenProps:t}=Xe(),n=J(h=>h.authToken)||e,{connections:r}=Ni(e),s=Le(h=>{var m,p;return(p=(m=h==null?void 0:h.card)==null?void 0:m.dataSource)==null?void 0:p.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:l,error:u,refetch:d}=mn({queryKey:["dataModels",s],queryFn:()=>rr(`${t.apiServiceUrl}/v1/datamodels`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:i()}),f=a==null?void 0:a.datamodels.map(h=>({id:h.id,name:h.name,label:h.label,description:h.description,connectionId:s,dialect:h.dialect,connectionType:o==null?void 0:o.type,type:"model",database:h.database,schema:h.schema}));return{isPending:l,error:u,dataModels:f||[],refetch:d}}function BQe(){var N,S,j;const e=Le(k=>k.card.dataSource);Le(k=>k.actions.updateDirectSource);const t=Le(k=>k.actions.updateDataSource),[n,r]=w.useState(""),{selectedConnection:s,error:o}=Ni(),{databases:i,isPending:a,error:l,label:u}=LQe(),{schemas:d,isPending:f,error:h,label:m}=zQe(),{error:p}=Mte(),g=s==null?void 0:s.capabilities.path.includes("schema"),b=s==null?void 0:s.capabilities.path.includes("database"),x=u==null?void 0:u.toLowerCase(),y=m==null?void 0:m.toLowerCase(),v=k=>{e&&t({...e,dbSelection:{database:k,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},C=k=>{var E;if(!((E=e==null?void 0:e.dbSelection)!=null&&E.database))return;const _=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{..._,schema:k},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return c.jsxs(c.Fragment,{children:[(o||l||h||p)&&c.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[c.jsx("div",{className:"flex items-center",children:c.jsxs("div",{className:"text-sm text-red-800",children:[c.jsx("strong",{children:"Error loading data:"}),c.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&c.jsxs("li",{children:["Connections: ",o]}),l&&c.jsxs("li",{children:[u,": ",l.message]}),h&&c.jsxs("li",{children:[m,": ",h.message]}),p&&c.jsxs("li",{children:["Data Models: ",p.message]})]})]})}),c.jsx(oe,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),c.jsxs("div",{className:"space-y-4",children:[b&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{className:"text-sm font-medium",children:u}),c.jsxs(it,{value:((N=e==null?void 0:e.dbSelection)==null?void 0:N.database)||"",onValueChange:v,disabled:a,children:[c.jsx(rt,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[a&&c.jsx(yn,{className:"h-4 w-4 animate-spin"}),c.jsx(at,{placeholder:l?`Error loading ${x}`:a?`Loading ${x}...`:`Select ${x}...`})]})}),c.jsx(st,{children:i.map(k=>c.jsx(we,{className:"hover:bg-muted",value:k.id,children:k.name},k.id))})]})]}),((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)&&g&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{className:"text-sm font-medium",children:m}),c.jsxs(it,{value:((j=e==null?void 0:e.dbSelection)==null?void 0:j.schema)||"",onValueChange:C,disabled:f,children:[c.jsx(rt,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[f&&c.jsx(yn,{className:"h-4 w-4 animate-spin"}),c.jsx(at,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),c.jsx(st,{children:d.map(k=>c.jsx(we,{className:"hover:bg-muted",value:k.id,children:k.name},k.id))})]})]})]})]})}function VQe(){const e=Le(l=>l.card.dataSource),t=Le(l=>l.actions.updateDataSource),[n,r]=w.useState(!1),s=l=>{if(!l||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(l).map(f=>({id:`file-${Date.now()}-${Math.random()}`,name:f.name,type:"upload",connectionId:"default",connectionType:"none",label:f.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:f.name,file:f})),d=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...d,...u]})},o=l=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==l);t({...e,selectedEntities:u})},i=l=>{if(l===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(l)/Math.log(u));return Number.parseFloat((l/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{className:"text-sm font-medium",children:"Upload Files"}),c.jsxs("div",{className:`rounded-lg border-2 border-dashed p-6 text-center transition-colors ${n?"border-blue-400 bg-blue-50":"border-gray-300 hover:border-gray-400"}`,onDragOver:l=>{l.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:l=>{l.preventDefault(),r(!1),s(l.dataTransfer.files)},children:[c.jsx(_M,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),c.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),c.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:l=>s(l.target.files),accept:".csv,.json,.xlsx,.xls"}),c.jsx(oe,{variant:"outline",size:"sm",onClick:()=>{var l;return(l=document.getElementById("file-upload"))==null?void 0:l.click()},children:"Select Files"}),c.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(fe,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(l=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(bi,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:l.originalName}),c.jsx("p",{className:"text-xs text-gray-500",children:l.file?i(l.file.size):""})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(l.id),children:c.jsx(St,{className:"h-3 w-3"})})]},l.id))})]})]})}function HQe(){const e=Le(f=>f.card.dataSource),t=Le(f=>f.actions.updateDataSource),[n,r]=w.useState(""),[s,o]=w.useState(""),[i,a]=w.useState("api"),l=()=>{if(!n.trim()||!s.trim()||!e)return;const f={id:`url-${Date.now()}-${Math.random()}`,name:n.trim(),type:"url",connectionId:"default",connectionType:"none",label:n.trim(),description:`URL source of type ${i}`,url:s.trim(),sourceType:i,originalName:n.trim()},h=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...h,f]}),r(""),o(""),a("api")},u=f=>{if(!e)return;const h=(e.selectedEntities||[]).filter(m=>m.id!==f);t({...e,selectedEntities:h})},d=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),c.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{className:"text-xs text-gray-600",children:"Source Name"}),c.jsx(pn,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{className:"text-xs text-gray-600",children:"URL"}),c.jsx(pn,{placeholder:"https://api.example.com/data",value:s,onChange:f=>o(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{className:"text-xs text-gray-600",children:"Type"}),c.jsxs("select",{value:i,onChange:f=>a(f.target.value),className:"h-8 w-full rounded-md border border-gray-300 px-2 text-sm",children:[c.jsx("option",{value:"api",children:"API Endpoint"}),c.jsx("option",{value:"csv",children:"CSV File"}),c.jsx("option",{value:"json",children:"JSON File"})]})]}),c.jsxs(oe,{onClick:l,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[c.jsx(Mr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(fe,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(Ix,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),c.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:c.jsx(St,{className:"h-3 w-3"})})]},f.id))})]})]})}function UQe(e,t){var y,v;const{tokenProps:n}=Xe(),r=J(C=>C.authToken)||t,{connections:s}=Ni(t),o=Le(C=>{var N,S;return(S=(N=C==null?void 0:C.card)==null?void 0:N.dataSource)==null?void 0:S.connectionId}),i=Le(C=>{var N,S,j;return(j=(S=(N=C==null?void 0:C.card)==null?void 0:N.dataSource)==null?void 0:S.dbSelection)==null?void 0:j.database}),a=Le(C=>{var N,S,j;return(j=(S=(N=C==null?void 0:C.card)==null?void 0:N.dataSource)==null?void 0:S.dbSelection)==null?void 0:j.schema}),l=s==null?void 0:s.find(C=>C.id===o),u=l==null?void 0:l.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){if(!o)return!1;const C=(u==null?void 0:u.path)||[];return!(C.includes("database")&&!i||C.includes("schema")&&!a)}const{data:h,isPending:m,isLoading:p,error:g,refetch:b}=mn({queryKey:[e,o,i,a],queryFn:()=>rr(`${n.apiServiceUrl}/v1/${e}s`,(r==null?void 0:r.accessToken)||"",{connection_id:o,database_name:i,schema_name:a}),enabled:f()}),x=(v=h==null?void 0:h[`${e}s`])==null?void 0:v.map(C=>{var N;return{connectionId:l==null?void 0:l.id,connectionType:l==null?void 0:l.type,dialect:l==null?void 0:l.dialect,type:e,dbObjectType:(N=C==null?void 0:C.table_type)==null?void 0:N.toLowerCase(),id:C[`${e}_name`],database:i,schema:a,name:C[`${e}_name`]}});return{isPending:m,isLoading:p,error:g,entities:x||[],refetch:b,label:d}}function V1({title:e,message:t}){return c.jsx("div",{className:"rounded-xl border border-destructive/40 bg-destructive/10 p-4 text-destructive shadow-sm",children:c.jsxs("div",{className:"flex items-start gap-4",children:[c.jsx(Yl,{className:"h-6 w-6 flex-shrink-0"}),c.jsxs("div",{className:"flex-1",children:[c.jsx("h4",{className:"text-base font-semibold",children:e}),t&&c.jsx("p",{className:"mt-1 text-sm text-destructive/90",children:t})]})]})})}function WQe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=Ni(),[i,a]=w.useState(""),[l,u]=w.useState(""),[d,f]=w.useState("tables"),{updateDataSource:h,setSelectedConnectionId:m}=Cr(),{entities:p,isLoading:g,error:b}=UQe("table"),{dataModels:x,isPending:y,error:v}=Mte(),C=E=>{const M=s.find(P=>P.id===E);if(!M)return;const T=M.type==="upload"?"upload":M.type==="url"?"url":"database";h({...e,connectionId:E,connectionType:M.type,mode:T,dbSelection:{database:"",schema:"",entityType:"table"}}),m(E)},N=E=>{var F,A;const M=n||[],T=M.some($=>$.name===E.name&&$.type===E.type);let P;if(T)P=M.filter($=>!($.name===E.name&&$.type===E.type));else{const $={connectionId:e.connectionId,connectionType:e.connectionType,type:E.type,dbObjectType:E.dbObjectType,database:((F=e.dbSelection)==null?void 0:F.database)||"",schema:((A=e.dbSelection)==null?void 0:A.schema)||"",name:E.name,dialect:E.dialect};P=[...M,$]}t==null||t(P)},S=E=>{const M=n||[],T=M.some(F=>F.type==="model"&&F.name===E.name);let P;T?P=M.filter(F=>!(F.type==="model"&&F.name===E.name)):P=[...M,E],t==null||t(P)},j=p.filter(E=>E.name.toLowerCase().includes(i.toLowerCase())),k=x.filter(E=>E.name.toLowerCase().includes(l.toLowerCase())),_=w.useCallback(()=>{if(!t)return;const E=n||[];let M=[...E];if(d==="tables"){const P=j.filter(F=>!E.some(A=>A.name===F.name&&A.type==="table")).map(F=>{var A,$;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:F.dbObjectType,database:((A=e.dbSelection)==null?void 0:A.database)||"",schema:(($=e.dbSelection)==null?void 0:$.schema)||"",name:F.name,dialect:F.dialect}});M=[...E,...P]}else if(d==="datamodels"){const T=k.filter(P=>!E.some(F=>F.name===P.name&&F.type==="model"));M=[...E,...T]}t(M)},[d,j,k,n,e,t]);return w.useEffect(()=>{r&&r(_)},[r,_]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{className:"font-medium= text-sm",children:"Connection"}),c.jsxs(it,{value:(e==null?void 0:e.connectionId)||"",onValueChange:C,disabled:o,children:[c.jsx(rt,{className:"w-full",children:c.jsx(at,{placeholder:o?"Loading connections...":"Select connection..."})}),c.jsx(st,{children:s.map(E=>c.jsx(we,{className:"hover:bg-muted",value:E.id,children:c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx($l,{className:"h-4 w-4 flex-shrink-0"}),c.jsx("span",{className:"truncate",children:E.name}),c.jsx(qe,{variant:"secondary",className:"flex-shrink-0 text-xs",children:E.type})]})},E.id))})]})]}),(e==null?void 0:e.connectionId)&&c.jsxs(c.Fragment,{children:[e.connectionType==="upload"&&c.jsx(VQe,{}),e.connectionType==="url"&&c.jsx(HQe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(BQe,{}),c.jsx("div",{className:"space-y-4",children:c.jsx("div",{className:"space-y-2",children:c.jsxs(Ls,{defaultValue:"tables",value:d,onValueChange:E=>f(E),className:"w-full",children:[c.jsxs(Cs,{className:"grid w-full grid-cols-2",children:[c.jsxs(rn,{value:"tables",children:["Tables & Views (",j.length,")"]}),c.jsxs(rn,{value:"datamodels",children:["Data Models (",k.length,")"]})]}),c.jsxs(pr,{value:"tables",className:"space-y-2",children:[c.jsx(jn,{placeholder:"Search tables and views...",value:i,onChange:E=>a(E.target.value),className:"h-8 text-sm",disabled:g}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):b?c.jsx(V1,{title:"Error loading tables",message:b.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):j.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):j.map(E=>{const M=n.some(T=>T.name===E.name&&T.type==="table");return c.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>N(E),children:[c.jsx(un,{id:`table-${E.name}`,checked:M,onCheckedChange:()=>N(E),onClick:T=>T.stopPropagation(),disabled:g}),c.jsxs(fe,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[E.name,E.dbObjectType==="view"&&c.jsx(qe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),E.dbObjectType==="materialized view"&&c.jsx(qe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},E.name)})})]}),c.jsxs(pr,{value:"datamodels",className:"space-y-2",children:[c.jsx(jn,{placeholder:"Search data models...",value:l,onChange:E=>u(E.target.value),className:"h-8 text-sm",disabled:y}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?c.jsx(V1,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):k.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):k.map(E=>{const M=n.some(T=>T.name===E.name&&T.type==="model");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(E),children:[c.jsx(un,{id:`dataModel-${E.name}`,checked:M,onCheckedChange:()=>S(E),onClick:T=>T.stopPropagation(),disabled:y}),c.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[c.jsx(fe,{className:"cursor-pointer",children:E.name}),c.jsx("span",{className:"text-xs text-muted-foreground",children:E.description})]})]},E.name)})})]})]})})})]})]})]})}function qQe({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:s=[],isRestricted:o=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var N;const[l,u]=w.useState(""),d=w.useCallback(S=>{const j={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:S};t({...j})},[e,t]);w.useEffect(()=>{i&&!(e!=null&&e.semanticDomainId)&&d(i)},[i,e==null?void 0:e.semanticDomainId,d]);const{semanticDomains:f,isPending:h,error:m}=OQe(),p=o?f.filter(S=>s.includes(S.id)):f,{datasets:g,isPending:b,error:x}=$Qe(e==null?void 0:e.semanticDomainId),y=S=>{const j=r||[],k=j.some(E=>E.id===S.id&&E.type==="dataset");let _;if(k)_=j.filter(E=>!(E.id===S.id&&E.type==="dataset"));else{const E={id:S.id,datasetType:S.type,name:S.name||S.table,label:S.label,domainId:S.domainId,description:S.description,database:S.database,schema:S.schema,type:"dataset",connectionId:S.connectionId,connectionType:S.connectionType,dialect:S.dialect,datamodelId:S.datamodelId,sql:S.sql};_=[...j,E]}n==null||n(_)},v=g.filter(S=>S.name.toLowerCase().includes(l.toLowerCase())),C=w.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const S=r||[],k=v.filter(E=>!S.some(M=>M.id===E.id&&M.type==="dataset")).map(E=>({id:E.id,datasetType:E.type,name:E.name||E.table,label:E.label,domainId:E.domainId,description:E.description,database:E.database,schema:E.schema,type:"dataset",connectionId:E.connectionId,connectionType:E.connectionType,dialect:E.dialect,datamodelId:E.datamodelId,sql:E.sql})),_=[...S,...k];n(_)},[v,r,e==null?void 0:e.semanticDomainId,n]);return w.useEffect(()=>{a&&a(C)},[a,C]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{className:"text-sm font-medium",children:"Semantic Domain"}),c.jsxs(it,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:d,disabled:h||o&&!!i,children:[c.jsx(rt,{className:"w-full",children:c.jsx(at,{placeholder:h?"Loading semantic domains...":o&&i?"Loading domain...":"Select semantic domain...",children:((N=p.find(S=>S.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:N.label)||"Select semantic domain"})}),c.jsx(st,{children:p.map(S=>c.jsx(we,{className:"hover:bg-muted",value:S.id,children:c.jsxs("div",{className:"flex flex-col items-start",children:[c.jsx("span",{className:"font-medium",children:S.label}),c.jsx("span",{className:"text-xs",children:S.description})]})},S.id))})]}),m&&c.jsx(V1,{title:"Error loading semantic models",message:m.message})]}),(e==null?void 0:e.semanticDomainId)&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(jn,{placeholder:"Search datasets...",value:l,onChange:S=>u(S.target.value),className:"h-8 text-sm",disabled:b}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:b?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):x?c.jsx(V1,{title:"Error loading datasets",message:x.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):v.length===0?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:l?"No datasets match your search":"No datasets available"}):v.map(S=>{const j=r.some(k=>k.id===S.id&&k.type==="dataset");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>y(S),children:[c.jsx(un,{id:`dataset-${S.id}`,checked:j,onCheckedChange:()=>y(S),onClick:k=>k.stopPropagation(),disabled:b}),c.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[c.jsx(fe,{className:"cursor-pointer font-medium",children:S.label||S.name}),c.jsx("span",{className:"text-xs text-gray-500",children:S.description})]})]},S.label||S.name)})})]})]})]})}function uP({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s}){const{tokenProps:o}=Xe(),{allowedSemanticDomains:i}=o,[a,l]=w.useState([]),{updateDataSource:u}=Cr(),d=J(M=>M.isVisualEditing),f=J(M=>M.dashboard.aiContext),{setAiContext:h}=Bt(),m=w.useRef(null),[p,g]=w.useState(!1),b=i&&i.length>0,x=!b,y=b&&i.length===1?i[0]:void 0,v=w.useCallback(M=>{const T=M;u({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:T,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...T!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,u]),C=w.useCallback(M=>{u({...n,...M})},[n,u]);w.useEffect(()=>{b&&n.mode!=="semanticDomain"&&v("semanticDomain")},[b,n.mode,v]),w.useEffect(()=>{y&&!n.semanticDomainId&&C({semanticDomainId:y})},[y,n.semanticDomainId,C]),w.useEffect(()=>{e?l(s||[]):(m.current=null,g(!1))},[e,n==null?void 0:n.selectedEntities,r,u,s,n]);const N=M=>{const T=a.filter(P=>!(P.name===M.name&&P.type===M.type));l(T)},S=()=>{l([])},j=w.useCallback(M=>{l(M)},[]),k=w.useCallback(()=>{m.current&&m.current()},[]),_=w.useCallback(M=>{m.current=M,g(!0)},[]);function E(){var M,T;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const P=(M=a==null?void 0:a[0])==null?void 0:M.connectionId,F=(T=a==null?void 0:a[0])==null?void 0:T.connectionType;u({...n,connectionId:P,connectionType:F,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return c.jsx(Kr,{open:e,onOpenChange:t,children:c.jsx(zr,{className:"flex max-w-2xl flex-col",children:c.jsxs("div",{children:[c.jsxs(Br,{className:"flex-shrink-0",children:[c.jsx(Vr,{children:r==="aiContext"?"Data Context":"Select Data Source"}),c.jsx(as,{children:r==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),c.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:c.jsxs("div",{className:"space-y-4",children:[x&&c.jsx("div",{className:"space-y-2",children:c.jsx(Ls,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:v,className:"w-full",children:c.jsxs(Cs,{className:"grid w-full grid-cols-2",children:[c.jsx(rn,{value:"database",children:"Direct Source"}),c.jsx(rn,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&c.jsx(qQe,{dataSource:n,onDataSourceUpdate:C,selectedEntities:a,onSelectionChange:j,allowedDomainIds:i||[],isRestricted:b,autoSelectedDomainId:y,onRegisterSelectAll:_}),(n==null?void 0:n.mode)==="database"&&x&&c.jsx(WQe,{dataSource:n,onDataSourceUpdate:C,selectedEntities:a,onSelectionChange:j,onRegisterSelectAll:_})]})}),c.jsx(FQe,{selectedEntities:a,onDeselectEntity:N}),c.jsx(is,{className:"flex-shrink-0",children:c.jsx("div",{className:"flex w-full justify-between",children:c.jsxs("div",{className:"flex grow justify-end gap-2",children:[c.jsx(oe,{variant:"outline",onClick:k,disabled:!p,children:"Select All"}),c.jsx(oe,{variant:"outline",onClick:S,disabled:a.length===0,children:"Clear All"}),c.jsxs(oe,{variant:"outline",onClick:()=>t(!1),children:[c.jsx(St,{className:"mr-2 h-4 w-4"}),"Close"]}),c.jsxs(oe,{onClick:E,children:[c.jsx(Ar,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function YQe({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=w.useRef(null),o=async a=>{const l=Array.from(a.target.files||[]);if(l.length===0)return;const u=gl-n;if(l.length>u){We.error(`You can only attach ${gl} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=mee(l);if(f.forEach(({file:h,error:m})=>{We.error(`${h.name}: ${m}`)}),d.length>0)try{const h=await Promise.all(d.map(m=>JA(m)));e(h)}catch(h){console.error("Failed to process files:",h),We.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:s,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:o,className:"hidden",disabled:t||n>=gl}),c.jsx(oe,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=gl,title:n>=gl?`Maximum ${gl} files allowed`:"Attach files",children:c.jsx(vM,{className:"h-4 w-4 text-muted-foreground"})})]})}function GQe({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=w.useState(!1),a=w.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),l=w.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),m=f.clientX,p=f.clientY;(m<h.left||m>=h.right||p<h.top||p>=h.bottom)&&i(!1)},[]),u=w.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=w.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const m=gl-r;if(h.length>m){We.error(`You can only attach ${gl} files per message. You have ${m} slot(s) remaining.`);return}const{valid:p,errors:g}=mee(h);if(g.forEach(({file:b,error:x})=>{We.error(`${b.name}: ${x}`)}),p.length>0)try{const b=await Promise.all(p.map(x=>JA(x)));t(b),We.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),We.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:X("relative",s),onDragEnter:a,onDragLeave:l,onDragOver:u,onDrop:d,children:[e,o&&!n&&c.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-lg border-2 border-dashed border-primary bg-primary/5 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-2",children:[c.jsx(_M,{className:"h-8 w-8 text-primary"}),c.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:[gl-r," slot(s) available"]})]})})]})}const dP=w.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:l},u)=>{const[d,f]=w.useState(!1),[h,m]=w.useState(!1),[p,g]=w.useState(!1),b=w.useRef(null),x=pp();lje(),aje();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:C,setShowReasoning:N}=cS(),{queueMessage:S}=gp(),{addFileAttachment:j,removeFileAttachment:k,clearFileAttachments:_,getFileAttachments:E}=SI(),M=CI(l),T=Le(B=>B.card.dataSource),P=J(B=>B.dashboard.aiContext),F=J(B=>{var G;return(G=B.dashboard.aiContext)==null?void 0:G.selectedEntities});w.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const A=w.useCallback(()=>{const B=b.current;if(B){if(!e||e.length===0){B.style.height="10px";return}B.style.height="auto";const G=Math.min(Math.max(B.scrollHeight,10),200);B.style.height=`${G}px`}},[e]);w.useEffect(()=>{A()},[A]),w.useEffect(()=>{const B=setTimeout(()=>{A()},0);return()=>clearTimeout(B)},[A]);const $=()=>{const B=e.trim();!B&&M.length===0||(a!=="ready"?(S(l,B,M),t(""),_(l)):r({preventDefault:()=>{}}))},q=B=>{B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),$()),B.key==="@"&&(U(),f(!0))},W=w.useCallback(B=>{const G=xqe(B.nativeEvent);G.length>0&&(B.preventDefault(),G.forEach(async Z=>{const Q=await JA(Z);j(l,Q)}))},[j,l]),z=w.useCallback(B=>{B.forEach(G=>{j(l,G)})},[j,l]),I=w.useCallback(B=>{B.forEach(G=>{j(l,G)})},[j,l]),L=w.useCallback(B=>{k(l,B)},[k,l]),O=B=>{if(x.selectedEntities.some(Z=>Z.id&&Z.id===B.id||Z.name===B.name)){const Z=x.selectedEntities.filter(Q=>!(Q.id&&Q.id===B.id||Q.name===B.name));y({selectedEntities:Z})}else{const Z=[...x.selectedEntities,B];y({selectedEntities:Z})}},R=B=>{O(B)},H=B=>{var Q;if(!x.selectedEntities.some(K=>K.id&&K.id===B.id||K.name===B.name)){const K=[...x.selectedEntities,B];y({selectedEntities:K})}const Z="label"in B?B.label:B.name;t(e+`@${Z} `),f(!1),(Q=b.current)==null||Q.focus()},V=B=>{const G=x.selectedEntities.filter(K=>!(K.id&&K.id===B.id||K.name===B.name));y({selectedEntities:G});const Q=`@${"label"in B?B.label:B.name}`;e.includes(Q)&&t(e.replace(Q,"").trim())},Y=B=>{const G=new Set(B.map(K=>K.id||K.name)),Z=x.selectedEntities.filter(K=>!G.has(K.id||K.name));y({selectedEntities:Z});let Q=e;B.forEach(K=>{const ie=`@${"label"in K?K.label:K.name}`;Q=Q.replace(ie,"").trim()}),t(Q)},U=w.useCallback(()=>{x.selectedEntities.length===0&&y({selectedEntities:(P==null?void 0:P.selectedEntities)||[]})},[x.selectedEntities.length,P==null?void 0:P.selectedEntities,y]);return c.jsxs(GQe,{onFilesDropped:z,currentFileCount:M.length,disabled:s,className:"space-y-4",children:[c.jsx(AQe,{entities:x.selectedEntities,availableEntities:F||[],onRemoveEntity:V,onRemoveEntities:Y}),M.length>0&&c.jsx(yqe,{files:M,onRemove:L,showRemove:!s,className:"mb-2"}),c.jsxs("div",{className:"rounded-lg border border-border bg-background shadow-sm focus-within:ring-1 focus-within:ring-foreground/40",children:[c.jsx("textarea",{ref:b,value:e,onChange:n,onKeyDown:q,onPaste:W,onFocus:()=>{A(),i==null||i()},placeholder:"Ask a question...",className:"max-h-[200px] min-h-[40px] w-full resize-none overflow-y-auto border-0 bg-transparent px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),c.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[l==="dashboard"&&c.jsxs(gs,{open:d,onOpenChange:B=>{B&&U(),f(B)},children:[c.jsx(bs,{asChild:!0,children:c.jsx(oe,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:c.jsx(Rie,{className:"h-4 w-4 text-muted-foreground"})})}),c.jsx(xs,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:B=>B.preventDefault(),children:c.jsx(IQe,{isOpen:!0,onSelect:O,onDeselect:R,onClose:()=>{var B;f(!1),(B=b.current)==null||B.focus()},availableEntities:F||[],selectedEntities:x.selectedEntities,onTabComplete:H,onSelectAll:()=>{F&&y({selectedEntities:F})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),m(!0)}})})]}),c.jsx(YQe,{onFilesSelected:I,disabled:s,currentFileCount:M.length})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[s&&c.jsx(oe,{className:"rounded-full",size:"sm",onClick:o,children:c.jsx(Gie,{className:"size-3.5 bg-background"})}),!s&&c.jsx(oe,{disabled:!e.trim()&&M.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:$,title:a!=="ready"?"Message will be queued":void 0,children:c.jsx(J8,{className:"size-4"})})]})]})]}),c.jsx(uP,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:m,dataSource:T||cN,dialogMode:"aiContext"})]})});dP.displayName="ChatInputWithContext";function Dte({assistantType:e,className:t}){const n=cY(e),{removeFromQueue:r}=gp();return n.length===0?null:c.jsxs("div",{className:X("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(Gl,{className:"h-3 w-3"}),c.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),c.jsx("div",{className:"space-y-2",children:n.map(s=>c.jsx("div",{className:"group relative rounded-lg border border-dashed border-muted-foreground/30 bg-muted/30 px-3 py-2 text-sm animate-in fade-in-0 slide-in-from-bottom-1",children:c.jsxs("div",{className:"flex items-start justify-between gap-2",children:[c.jsx("div",{className:"flex-1 space-y-1",children:c.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:c.jsx(St,{className:"h-3 w-3"})})]})},s.id))})]})}function Ite({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=cY(e),{dequeueMessage:o}=gp();w.useEffect(()=>{if(t!=="ready"||n||!(s&&s.length>0))return;const a=o(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,s,o,r,e])}function Rte(e,t={}){const{threshold:n=50,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=w.useRef(null),[a,l]=w.useState(!0),[u,d]=w.useState(!0),[f,h]=w.useState(!1),[m,p]=w.useState(0),g=w.useRef(0),b=w.useRef(!1),x=w.useRef(0),y=w.useRef(a),v=w.useRef(void 0),C=w.useRef({key:null,count:0,length:0}),N=w.useCallback(()=>{const _=i.current;return _?_.scrollHeight-_.scrollTop-_.clientHeight:0},[]),S=w.useCallback((_={})=>{if(!i.current)return;const{force:M=!1,instant:T=!1}=_;if(!M&&!y.current||!a&&!M)return;const P=T||r==="auto"||r==="instant"?"auto":r;v.current&&cancelAnimationFrame(v.current),b.current=!0,v.current=requestAnimationFrame(()=>{if(!M&&!y.current){b.current=!1,v.current=void 0;return}const F=i.current;if(!F){b.current=!1,v.current=void 0;return}const A=F.scrollHeight;P==="smooth"&&"scrollTo"in F?F.scrollTo({top:A,behavior:P}):F.scrollTop=A,g.current=F.scrollTop,d(!0),l(!0),y.current=!0,h(!1),p(0),b.current=!1,v.current=void 0})},[r,a]),j=w.useCallback(()=>{const _=i.current;if(!_)return;const E=g.current,M=_.scrollTop,T=M-E;if(g.current=M,T<-1){v.current&&(cancelAnimationFrame(v.current),v.current=void 0),b.current=!1,y.current=!1,l(!1),d(!1);return}if(b.current)return;const P=N()<=n;d(P),l(P),y.current=P,P&&(h(!1),p(0))},[N,n]),k=w.useCallback(()=>{p(0),h(!1)},[]);return w.useEffect(()=>{y.current=a},[a]),w.useEffect(()=>{const _=i.current;if(!_||!e||e.length===0){h(!1),p(0),C.current={key:null,count:0,length:0},g.current=_?_.scrollTop:0,x.current=_?_.scrollHeight:0;return}g.current=_.scrollTop,x.current=_.scrollHeight;const E=C.current,M=e[e.length-1],T=(M==null?void 0:M.id)??(M==null?void 0:M.messageId)??(M==null?void 0:M.createdAt)??(M==null?void 0:M.timestamp)??e.length,P=Array.isArray(M==null?void 0:M.parts)?M.parts.reduce((z,I)=>I?typeof I=="string"?z+I.length:typeof I.text=="string"?z+I.text.length:typeof I.content=="string"?z+I.content.length:typeof I.value=="string"?z+I.value.length:z:z,0):typeof(M==null?void 0:M.content)=="string"?M.content.length:typeof(M==null?void 0:M.text)=="string"?M.text.length:0,F=e.length>E.count,A=T!==E.key,$=P>E.length,q=s&&(M==null?void 0:M.role)==="assistant"&&!F&&(A||$),W=o||q;if(C.current={key:T,count:e.length,length:P},a&&(F||A||$||W)){S({force:!1,instant:W});return}if(!a&&F){const z=e.length-E.count;z>0&&(h(!0),p(I=>I+z))}else!a&&$&&(h(!0),p(z=>z>0?z:1))},[e,S,a,s,o]),w.useEffect(()=>{S({instant:!0})},[S]),w.useEffect(()=>{if(typeof ResizeObserver>"u")return;const _=i.current;if(!_)return;x.current=_.scrollHeight;const E=new ResizeObserver(()=>{const M=i.current;if(!M)return;const T=x.current,P=M.scrollHeight;x.current=P,!b.current&&y.current&&P>T&&S({force:!1,instant:!0})});return E.observe(_),()=>{E.disconnect()}},[S]),w.useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:u,hasNewMessages:f,newMessageCount:m,scrollToBottom:S,handleScroll:j,resetNewMessageCount:k}}function Ate(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=w.useState(r),a=w.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),l=e.length>o,u=o>=e.length,d=w.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=w.useCallback(()=>{i(r)},[r]);return w.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:l,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}function Pte(e){var n;if(!e||e.length===0)return{hasActiveTools:!1};const t=e[e.length-1];if(!(t!=null&&t.parts))return{hasActiveTools:!1};for(const r of t.parts){if(r.type==="reasoning"&&"state"in r&&r.state==="streaming")return{hasActiveTools:!0,activeToolText:r.text||"Reasoning...",toolType:"reasoning"};if(((n=r.type)!=null&&n.startsWith("tool-")||r.type==="dynamic-tool")&&"state"in r&&["input-streaming","input-available"].includes(r.state)){const s=r,o=s.state;return{hasActiveTools:!0,activeToolText:pee(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const KQe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function ZQe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=w.useState(!1),[a,l]=w.useState(LT),[u,d]=w.useState(!1),[f,h]=w.useState(!1),[m,p]=w.useState(!1),g=n??m,{isLocalDev:b,isConsoleMode:x}=Km(),y=w.useRef(null);J(Ge=>Ge.dashboard.aiScopeTables),J(Ge=>Ge.isDashboardEditing);const v=J(Ge=>Ge.selectedSheetId),{setDataSource:C}=Cr(),{addFrame:N,setSelectedFrameId:S,setIsDashboardEditing:j}=Bt(),k=pp(),{setCurrentAIContext:_,updateSelectedEntities:E,setReasoningEffort:M,setShowReasoning:T}=cS(),{clearQueue:P}=gp(),{clearFileAttachments:F,getFileAttachments:A}=SI(),$=CI("dashboard"),q=J(Ge=>Ge.dashboard.aiContext),W=Le(Ge=>Ge.card.dataSource),{assistantProfile:z}=kte(),I=J(Ge=>Ge.handleOpenAssistantProfile),{sendMessage:L,isLoading:O,messages:R,setMessages:H,status:V,stop:Y,errorMessage:U,clearError:B}=DQe(),G=w.useCallback(Ge=>{r==null||r(Ge),n===void 0&&p(Ge)},[n,r]),Z=w.useCallback(()=>{G(!g)},[g,G]);w.useEffect(()=>{if(!g)return;function Ge(Nt){Nt.key==="Escape"&&G(!1)}return window.addEventListener("keydown",Ge),()=>{window.removeEventListener("keydown",Ge)}},[g,G]);const[Q,K]=w.useState(""),te=Ge=>{K(Ge.target.value)};function ie({sql:Ge,cardTitle:Nt,connectionId:ce,cardType:Ae,python:Te,cardConfig:Ie,dataSource:Ue,customVisualPreferences:ke}){if(!v)return;const ye={id:kr(),title:Nt||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Ae==="horizontalBar"?"y":"x"}},type:Ae,sql:Ge,python:Te,dataSource:Ue,config:Ie,connectionId:ce,customCardPreferences:ke?{url:ke.url,componentName:ke.componentName,pluginChartType:ke.pluginChartType,settings:ke.settings,type:"component"}:void 0},ne={id:kr(),cards:[ye],activeCardId:ye.id};j(!0),N(v,ne,"end"),S(ne.id)}const ue=Ge=>{Ge.preventDefault();const Nt=Q.trim();if(!Nt&&$.length===0)return;const ce=[];Nt&&ce.push({type:"text",text:Nt}),$.forEach(Ae=>{Ae.data&&ce.push({type:"file",mediaType:Ae.type,filename:Ae.name,url:`data:${Ae.type};base64,${Ae.data}`})}),L({role:"user",parts:ce}),K(""),F("dashboard"),se({force:!0})};w.useEffect(()=>{var Ge;e&&((Ge=y.current)==null||Ge.focus())},[e]),Ite({assistantType:"dashboard",status:V,isLoading:O,sendMessage:L});const{hasActiveTools:he}=Pte(R),{visibleMessages:je,hasMoreMessages:be,totalMessageCount:Me,loadMoreMessages:le,resetMessageWindow:ae}=Ate(R,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:xe,isAtBottom:de,hasNewMessages:Se,newMessageCount:ge,scrollToBottom:se,handleScroll:me,resetNewMessageCount:Oe}=Rte(je,{threshold:50,behavior:"smooth",isStreaming:O});function Pe(Ge){tt();const Nt={role:"user",parts:[{type:"text",text:Ge.title+" "+Ge.subtitle}]};L(Nt)}function Re(Ge){tt(),L({role:"user",parts:[{type:"text",text:Ge}]})}function He(Ge){tt(),L({role:"user",parts:[{type:"text",text:Ge}]}),se({force:!0})}const Ke=w.useCallback(async()=>{const Ge=JSON.stringify(R??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Ge),We.success("Conversation copied")}catch(Nt){console.error("Failed to copy conversation",Nt),We.error("Unable to copy conversation")}},[R]);function tt(){k.selectedEntities.length===0&&_({selectedEntities:(q==null?void 0:q.selectedEntities)||[]})}const mt=(Q==null?void 0:Q.length)===0&&(R==null?void 0:R.filter(Ge=>Ge.role==="user").length)===0;function gt(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function dt(){return c.jsxs(wf,{children:[c.jsx(Cf,{asChild:!0,children:c.jsx(Yc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(zm,{className:"size-3.5"})})}),c.jsxs(yu,{align:"end",children:[c.jsx(Mh,{children:"Options"}),c.jsx(Kd,{}),c.jsx(Fg,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(Fg,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(Fg,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const Ht=c.jsxs("div",{"data-role":"dashboard-assistant",className:X("flex h-full grow flex-col justify-between break-words px-6 py-4",g&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[c.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[gt(),I&&c.jsx(oe,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:I,children:(z==null?void 0:z.name)||"Default Profile"}),c.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[x&&dt(),a&&c.jsx(oe,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Ke,children:"Copy Conversation"}),c.jsx(Yc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:Z,children:g?c.jsx(yM,{className:"size-4"}):c.jsx(aC,{className:"size-4"})}),c.jsx(Yc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{H([]),P("dashboard"),B(),ae()},children:c.jsx(cC,{className:"size-4"})}),c.jsx(Yc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(St,{className:"size-4"})})]})]}),c.jsxs(nl,{"data-role":"dashboard-assistant-scroll-area",ref:xe,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:me,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[be&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(oe,{variant:"outline",size:"sm",onClick:le,className:"text-xs",children:["Load ",Math.min(5,Me-je.length)," ","more messages (",Me-je.length," ","hidden)"]})}),c.jsx(bee,{showTools:a,showSystemMessage:u,messages:je,onAddToDashboard:ie,onQuickReply:He,disableQuickReplies:O}),!he&&c.jsx(gee,{status:V,errorMessage:U})]}),c.jsx(yi,{orientation:"horizontal"})]}),e&&!de&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(oe,{onClick:()=>{se({force:!0}),Oe()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(cr,{className:"h-4 w-4"}),Se&&ge>0&&c.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:ge>9?"9+":ge})]})}),c.jsxs("div",{className:"space-y-3",children:[!z&&mt&&c.jsx(xee,{onClick:Pe,placeholders:KQe}),c.jsx("div",{children:mt&&z&&c.jsx(Ete,{seedQuestions:z.seedQuestions||[],handleSeedQuestionClick:Re})}),c.jsx(Dte,{assistantType:"dashboard",className:"mb-3"}),c.jsx(dP,{ref:y,setInput:K,stop:Y,input:Q,handleInputChange:te,handleSubmit:Ge=>{tt(),ue(Ge),se({force:!0})},isLoading:O,status:V,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx(uP,{incomingSelectedEntities:(q==null?void 0:q.selectedEntities)||[],open:f,onOpenChange:h,dataSource:W||cN,dialogMode:"aiContext"})]});return g&&s?Xn.createPortal(c.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:c.jsx("div",{className:"flex h-full w-full",children:Ht})}),s):Ht}function XQe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Bt(),o=J(d=>d.dashboard.sheets),a=J(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),l=J(d=>d.isDashboardEditing),u=J(d=>d.isVisualEditing);w.useEffect(()=>{if(!l||u)return;async function d(m){const p=m.ctrlKey||m.metaKey;p&&m.key==="c"?(await f(),We.success("Card copied to clipboard"),m.preventDefault()):p&&m.key==="v"&&(await h(),m.preventDefault())}async function f(){try{const m=n();m&&await navigator.clipboard.writeText(JSON.stringify(m))}catch(m){console.error("Failed to copy text:",m)}}async function h(){if(!a)return null;try{const m=await navigator.clipboard.readText();try{const p=JSON.parse(m);if(p!=null&&p.id){const g=tA(p),b=g.cards.findIndex(x=>x.id===g.activeCardId);b!==-1&&(g.cards[b].title=`${g.cards[b].title} (Copy)`),r(a,g),s(g.id),We.success("Card pasted from clipboard")}}catch(p){console.error("Failed to parse clipboard contents: ",p)}return m}catch(m){return console.error("Failed to paste text:",m),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[r,n,s,a,l,u,t])}function QQe(e,t){switch(e.interactionMode){case"drillToDetail":JQe(e,t);break;case"drillThrough":eJe(e,t);break;case"drillToURL":tJe(e);break;case"inlineDrill":console.warn("Inline drill execution not yet implemented");break;case"clickFilter":case"drillDown":case"dynamicDrill":break;default:console.warn("Unknown interaction mode:",e.interactionMode)}}function JQe(e,t){var l;const{targetInsightId:n,contextMode:r,displayMode:s,filterGroups:o}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=o.flatMap(u=>u.filters);break;case"full":{const u=((l=t.getCurrentFilters)==null?void 0:l.call(t))||[],d=o.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}s==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function eJe(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:s,sourceCardId:o}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=s.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",l=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:l,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:l,filters:i,contextMode:r})}function tJe(e){const{url:t}=e;if(!t){console.warn("drillToURL event missing url");return}try{new URL(t)}catch(n){console.error("Invalid URL:",t,n);return}window.open(t,"_blank","noopener,noreferrer")}function nJe({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(Kr,{open:e,onOpenChange:t,children:c.jsxs(zr,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(Br,{children:[c.jsx(Vr,{children:i||"Insight Detail"}),c.jsx(as,{children:a||"View detailed insight data with applied filters"})]}),c.jsx($X,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(VX,{insightId:n,filters:r,contextMode:o}):c.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function rJe(){const e=Pt(C=>C.interactionStates),t=Pt(C=>C.setInteractionState),n=Pt(C=>C.clearLastInteractionEvent),r=Pt(C=>C.replaceCardWithInsight),s=Pt(C=>C.setPendingDrillThrough),o=Pt(C=>C.pendingDrillThrough),i=Pt(C=>C.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Bt(),{selectDashboard:u}=Dx(),d=J(C=>C.dashboard),f=J(C=>C.filterValues),{data:h,isLoading:m}=mB((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[p,g]=w.useState({open:!1,insightId:""}),b=HX(p.insightId,{enabled:p.open&&!!p.insightId}),x=w.useRef(new Set),y=w.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:C,filters:N,contextMode:S})=>{g({open:!0,insightId:C,filters:N,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:S})},replaceCardContent:({cardId:C,insightId:N,filters:S,contextMode:j})=>{r(C,N,S,j)},getCurrentFilters:()=>f||[],navigateWithDrill:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:C,contextMode:N,sourceDashboardId:S,sourceDashboardTitle:j,targetDashboardId:k})=>{const E={sourceCardId:Ra,interactionMode:"clickFilter",filterGroups:[{filters:C}]},M={...ai(),appliedClickFilters:[E],contextMode:N,sourceDashboardId:S,sourceDashboardTitle:j,targetDashboardId:k};t(Ra,M)}}),[a,r,f,l,d,s,t]);w.useEffect(()=>{Object.entries(e).forEach(([C,N])=>{if(N!=null&&N.lastInteractionEvent){const S=N.lastInteractionEvent,j=`${C}-${S.interactionMode}-${S.sourceCardId}-${Date.now()}`;if(x.current.has(j))return;x.current.add(j);try{QQe(S,y)}catch(k){console.error("Error executing interaction event:",k)}finally{n(C),setTimeout(()=>{x.current.delete(j)},5e3)}}})},[e,n,y]),w.useEffect(()=>{if(!(!o||!h||m))try{u(h),l(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(C){console.error("[DrillThrough] Error during automatic navigation:",C),i()}},[o,h,m,u,l,i]);const v=()=>{g({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(nJe,{open:p.open,onOpenChange:v,insightId:p.insightId,filters:p.filters,filterDefinitions:p.filterDefinitions,contextMode:p.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&m&&c.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border bg-background p-6 shadow-lg",children:[c.jsx(yn,{className:"h-8 w-8 animate-spin text-primary"}),c.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function sJe(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=oJe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function oJe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function iJe(e){return e?`Back to ${e}`:"Back"}function aJe(){var x,y,v,C,N;const e=Pt(S=>S.interactionStates[Ra]),t=J(S=>S.actions.goBackFromDrill),n=J(S=>S.actions.clearDrillContext),{selectDashboard:r}=Dx(),[s,o]=w.useState({x:16,y:16}),[i,a]=w.useState(!1),l=w.useRef({x:0,y:0});w.useEffect(()=>{if(!i)return;const S=k=>{o({x:k.clientX-l.current.x,y:k.clientY-l.current.y})},j=()=>{a(!1)};return document.addEventListener("mousemove",S),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",S),document.removeEventListener("mouseup",j)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((C=(v=(y=(x=e==null?void 0:e.appliedClickFilters)==null?void 0:x[0])==null?void 0:y.filterGroups)==null?void 0:v[0])==null?void 0:C.filters)||[],h=u?{id:u,title:d||"Previous Dashboard",description:"",isPrivate:!1,isPublic:!1,version:"",createdBy:null,createdByTenantUser:"",tenantId:"",projectId:"",createdAt:"",updatedAt:"",lastModified:"",lastModifiedBy:"",createdByUser:null,createdByTenantUserRel:{name:"",email:""},permissions:{canEdit:!0,canShare:!0,canDelete:!0},ownership:{status:"private",isOwner:!0,sharedCount:0,createdBy:{type:"user",userId:"",name:"",email:""}}}:null;if(!e||!((N=e.appliedClickFilters)!=null&&N.length))return null;const m=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(S){console.error("[DrillBack] Error during back navigation:",S)}},p=()=>{n()},g=S=>{S.target.closest("button")||(a(!0),l.current={x:S.clientX-s.x,y:S.clientY-s.y})};sJe(f);const b=iJe(d);return c.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:c.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:g,style:{cursor:i?"grabbing":"grab"},children:[c.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((S,j)=>{const k=S.field.label||S.field.name,_=String(S.value);return c.jsxs(qe,{variant:"secondary",className:"pointer-events-none text-xs",children:[k," = ",_]},j)})})]}),c.jsx(oe,{variant:"ghost",size:"sm",onClick:p,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(St,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(oe,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(R8,{className:"mr-2 h-4 w-4"}),b]})})]})})}function Fte(){var Me;const{showAssistant:e,tokenProps:t}=Xe(),{preferences:n,isConsoleMode:r}=Km(),s=((Me=n==null?void 0:n.cardDisplay)==null?void 0:Me.mode)==="print",o=w.useRef(null),i=w.useRef(null),[a,l]=w.useState(!1),{handleDragStart:u,isDraggingRef:d,getStyle:f,getPositionClasses:h}=f8e({initialPosition:"bottom-right"}),m=Fd(le=>le.setFullscreen),p=Fd(le=>le.setPanelOpen),g=Fd(le=>le.setContainer),b=oY("dashboard"),x=iY(),y=aY("dashboard"),v=b.isOpen,C=x==="dashboard",N=J(le=>le.isVisualEditing),S=J(le=>le.themeStyle),j=J(le=>{var ae;return(ae=le.dashboard)==null?void 0:ae.sheets}),k=J(le=>le.showFilters),_=J(le=>le.isDashboardEditing),E=J(le=>le.selectedSheetId),M=J(le=>{var ae,xe;return((xe=(ae=le.dashboard)==null?void 0:ae.summary)==null?void 0:xe.position)||"top"}),T=J(le=>{var ae;return(ae=le.dashboard)==null?void 0:ae.id}),P=J(le=>le.isDashboardPanelOpen),F=J(le=>le.actions.setIsDashboardPanelOpen),{getDefaultSheetId:A,setDefaultSheetId:$,clearDefaultSheetId:q}=_8(T),[W,z]=w.useState(null);CC(qt.DASHBOARD);const{setSelectedSheetId:I,setSheetTitle:L,addSheet:O,setSheets:R}=Bt();XQe(i);const{setActiveAssistantType:H}=cS();w.useEffect(()=>{if(T){const le=A();z(le)}},[T,A]),w.useEffect(()=>{v?H("dashboard"):x==="dashboard"&&m(null)},[v,H,x,m]),w.useEffect(()=>{var le;v||(le=o.current)==null||le.resize(0)},[v]);function V(le){var ae,xe;le?((ae=o.current)==null||ae.resize(40),p("dashboard",!0),H("dashboard")):(p("dashboard",!1),m(null),(xe=o.current)==null||xe.resize(0),H(null))}function Y(){const le={id:kr(),title:"New Sheet"};O(le),I(le.id)}function U(le,ae){if(!T)return;W===le?(q(),z(null),We.success("Default sheet cleared")):($(le),z(le),We.success(`"${ae}" set as default sheet`))}function B(le){var ae;le<1?(p("dashboard",!1),m(null),H(null),(ae=o.current)==null||ae.resize(0)):(v||p("dashboard",!0),H("dashboard"))}function G(){return(S==null?void 0:S.canvasTheme)==="muted"||!(S!=null&&S.canvasTheme)?"hsl(var(--semaphor-muted))":(S==null?void 0:S.canvasTheme)==="clear"?"":S==null?void 0:S.canvasTheme}const Z=(le,ae)=>{le.dataTransfer.setData("tabIndex",ae.toString())},Q=le=>{le.preventDefault()},K=(le,ae)=>{const xe=le.dataTransfer.getData("tabIndex");if(xe===ae.toString())return;const de=Array.from(j||[]),[Se]=de.splice(parseInt(xe),1);de.splice(ae,0,Se),R(de)},te=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail,ie=e===!0&&!s&&!v&&!N&&!k;function ue(){var le,ae;if(j&&j.length>1||_)return c.jsxs(Cs,{role:"tab-list",className:"flex h-12 w-0 min-w-full items-center justify-start gap-2 overflow-x-auto rounded-none border-b border-b-muted bg-transparent px-3",children:[r&&te&&c.jsx(oe,{style:{borderRadius:S==null?void 0:S.controlInputRadius},variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{F(!P)},className:"h-8 shrink-0 p-2",children:P?c.jsx($8,{className:"h-4 w-4"}):c.jsx(L8,{className:"h-4 w-4"})}),j==null?void 0:j.map((xe,de)=>{const Se=E===xe.id,ge=W===xe.id;return c.jsxs(rn,{draggable:!0,onDragStart:se=>Z(se,de),onDragOver:Q,onDrop:se=>K(se,de),style:{borderRadius:S==null?void 0:S.controlInputRadius},onClick:()=>I(xe.id),className:"flex shrink-0 items-center gap-1 border px-2 py-1",value:xe.id,children:[c.jsx(Zb,{enabled:_&&Se,text:xe.title,onSave:se=>L(xe.id,se),children:xe.title},xe.id),!_&&Se&&c.jsx("div",{title:ge?"Clear default sheet":"Set as default sheet",children:c.jsx(SM,{className:X("ml-1 size-3 cursor-pointer transition-all",ge?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:se=>{se.stopPropagation(),U(xe.id,xe.title||"Sheet")}})}),_&&Se&&j.length>1&&c.jsx(St,{className:"ml-1 size-3",onClick:()=>l(!0)})]},xe.id)}),_&&c.jsx("div",{style:{borderRadius:(ae=(le=S==null?void 0:S.chart)==null?void 0:le.options)==null?void 0:ae.borderRadius},className:"flex h-7 shrink-0 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:Y,children:c.jsx(Mr,{className:"size-3"})})]})}function he(){return c.jsx("div",{ref:i,style:{},className:"grow",children:j==null?void 0:j.map(le=>c.jsx(pr,{style:{backgroundColor:G()},className:X("mt-0",{}),value:le.id,children:c.jsx(Fze,{sheet:le})},le.id))})}function je(){var le;return c.jsxs(Ls,{"data-role":"dashboard-tabs-container",className:X("relative flex h-full flex-col",S==null?void 0:S.dashboardTabsContainer),onValueChange:ae=>{I(ae)},value:E||((le=j==null?void 0:j[0])==null?void 0:le.id),children:[ue(),M==="top"&&c.jsx(q_,{}),c.jsx(nl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:he()}),M==="bottom"&&c.jsx(q_,{}),c.jsx(h8e,{open:a,setOpen:l})]})}const be=w.useCallback(le=>{g("dashboard",le)},[g]);return j?c.jsxs(c.Fragment,{children:[c.jsx(rJe,{}),c.jsx(aJe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(QQ,{className:X("flex-1 basis-0 overflow-y-auto transition-opacity",C&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(tT,{children:je()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx(d8e,{open:v,onTabClick:V,withHandle:!0,disabled:!v}),c.jsx(tT,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:B,defaultSize:v?40:0,ref:o,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(ZQe,{open:v,setOpen:V,isFullscreen:C,onFullscreenChange:le=>m(le?"dashboard":null),fullscreenContainer:y})})})]})]}),c.jsx("div",{ref:be,className:X("absolute inset-0",!C&&"pointer-events-none")}),ie&&c.jsx("div",{className:X("absolute z-50 transition-all duration-300 ease-in-out",h().horizontal,h().vertical),style:f(),children:c.jsx(oe,{size:"sm",variant:"outline",className:"h-12 w-12 cursor-grab rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted active:cursor-grabbing",onClick:()=>{d.current||V(!0)},onMouseDown:u,onTouchStart:u,title:"Open Assistant (drag to move)",children:c.jsx(lC,{className:"h-5 w-5"})})})]})]}):null}function fP({children:e}){return c.jsx(la,{style:{height:"100%",width:"100%"},children:c.jsx(Yoe,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(Ln,{delayDuration:0,children:e})})})}function Ote({children:e,preferences:t}){const{currentUser:n}=$s(),r=w.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return c.jsx(W7.Provider,{value:r,children:c.jsx(hA,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function lJe(e=2e3,t=500){const n=Cie(),[r,s]=w.useState(!1),[o,i]=w.useState(!1),a=w.useRef(null);return w.useEffect(()=>{const l=setTimeout(()=>s(!0),e);return()=>clearTimeout(l)},[e]),w.useEffect(()=>{if(r){if(n>0){i(!1),a.current&&(clearTimeout(a.current),a.current=null);return}return a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i(!0)},t),()=>{a.current&&clearTimeout(a.current)}}},[r,n,t]),o}function hP({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=lJe(e,t);return w.useEffect(()=>(s&&(window.__SEMAPHOR_READY__={ready:!0,type:n,componentId:r||null,timestamp:Date.now()}),()=>{window.__SEMAPHOR_READY__={ready:!1,type:n,componentId:r||null,timestamp:Date.now()}}),[s,n,r]),c.jsx("div",{id:"idle-check","aria-hidden":"true",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s?"ready":""})}function $te(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(sa,{FallbackComponent:FS,children:c.jsxs(oM,{dashboardProps:e,children:[c.jsx(hP,{componentType:"dashboard",componentId:e.id}),c.jsx(fP,{children:c.jsx(Ote,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(NI,{...e,type:"dashboard",children:c.jsx(Fte,{})})})})})]})})}function K6(e,t){return e.map(n=>({...n,fieldScope:t}))}function cJe(e){const t=new Map;return e.forEach(n=>{const r=`${n.name}-${n.role||"unknown"}`;t.has(r)||t.set(r,n)}),Array.from(t.values())}function Z6(e){if(ic(e)||Qx(e))return e.expression}function mP(){const{columns:e,columnGroups:t,isLoading:n,hasError:r,error:s,refetch:o}=XD(),i=Le(g=>g.frame.calculatedFields),a=Le(g=>g.card.config),l=w.useMemo(()=>e.filter(g=>g.fieldScope==="domain"),[e]),u=w.useMemo(()=>e.filter(g=>g.fieldScope!=="domain"),[e]),d=w.useMemo(()=>i!=null&&i.length?K6(i,"dashboard"):[],[i]),f=w.useMemo(()=>{const g=new Map;return d.forEach(b=>{const x=`${b.name}-${b.role||"unknown"}`;g.set(x,b)}),g},[d]),h=w.useMemo(()=>{const g=((a==null?void 0:a.metricColumns)||[]).filter(ic),b=((a==null?void 0:a.groupByColumns)||[]).filter(Qx),y=cJe([...g,...b]).filter(v=>{const C=`${v.name}-${v.role||"unknown"}`,N=f.get(C);if(!N)return!0;const S=Z6(v),j=Z6(N);return S&&j?S!==j:!0});return K6(y,"card").map(v=>({...v,id:`card-source-${v.id}`}))},[a==null?void 0:a.groupByColumns,a==null?void 0:a.metricColumns,f]),m=w.useMemo(()=>[...l,...d,...h,...u],[h,u,d,l]),p=w.useMemo(()=>t.filter(g=>g.entityId!==Gz),[t]);return{columns:e,columnGroups:p,rawColumnGroups:t,columnFields:u,domainCalculatedFields:l,dashboardCalculatedFields:d,cardCalculatedFields:h,scopedFields:m,isLoading:n,hasError:r,error:s,refetch:o}}function pP(e){const{tokenProps:t,authToken:n}=Xe(),r=t==null?void 0:t.apiServiceUrl;return mn({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return rr(s,n.accessToken)},enabled:!!e&&!!(n!=null&&n.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:s=>Math.min(1e3*2**s,3e4)})}function Lte(e,t,n){if(t==="source")return{isValid:!0};const r=vr(e.dataType);if(n==="detailTable"&&t!=="detailColumns"&&t!=="sortBy")return{isValid:!1,reason:"Detail tables only accept columns"};if(n==="kpi"){if(t==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(t==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function zte(e,t,n,r,s){if(e!=="kpi"||s.length<3)return;const o=(t==null?void 0:t.groupByColumns)&&t.groupByColumns.length>0,i=s.some(a=>a.comparisonType&&a.comparisonType!=="none");!o&&!i||n(r,{groupByColumns:[],metricColumns:s.map(a=>({...a,comparisonType:"none",targetValue:void 0}))})}function uJe(e,t){return(e||[]).map(n=>({...n,id:t(n),label:n.label!==void 0?n.label:n.name}))}const Bte=e=>{var F;const t=(F=e==null?void 0:e.dataSource)==null?void 0:F.semanticDomainId,{data:n}=pP(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=Cr(),h=Le(A=>A.card.type),m=e==null?void 0:e.id,p=(A,$)=>{if(A.id)return A.id;const q=A.qualifiedEntityName||A.entityName||$;return`${$}-${q}-${A.name}`},g=w.useCallback(A=>{if(!(e!=null&&e.config))return[];switch(A){case"groupBy":return(e.config.groupByColumns||[]).map($=>({...$,id:p($,"groupBy"),label:$.label!==void 0?$.label:$.name}));case"metrics":return(e.config.metricColumns||[]).map($=>({...$,id:p($,"metrics"),label:$.label!==void 0?$.label:$.name}));case"pivotBy":return(e.config.pivotByColumns||[]).map($=>({id:p($,"pivotBy"),name:$.name,dataType:$.dataType,label:$.label!==void 0?$.label:$.name,qualifiedEntityName:$.qualifiedEntityName,entityId:$.entityId,entityName:$.entityName,entityType:$.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map($=>({id:p($,"sortBy"),name:$.name,dataType:$.dataType,label:$.label!==void 0?$.label:$.name,qualifiedEntityName:$.qualifiedEntityName,entityId:$.entityId,entityName:$.entityName,entityType:$.entityType,direction:$.direction}));case"detailColumns":return uJe(e.config.detailColumns,$=>p($,"detailColumns"));case"source":return[];default:return[]}},[e]),b=w.useCallback((A,$)=>{if(m)switch(A){case"groupBy":{r(m,{groupByColumns:$});break}case"metrics":{r(m,{metricColumns:$});break}case"pivotBy":{r(m,{pivotByColumns:$});break}case"sortBy":{r(m,{sortByColumns:$});break}case"detailColumns":{r(m,{detailColumns:$});break}}},[m,r]),x=w.useCallback((A,$,q)=>{if(!m)return;const W=g(A),z=W[$];if(z)switch(A){case"groupBy":s(m,z.id,{label:q});break;case"metrics":o(m,z.id,{label:q});break;case"pivotBy":i(m,z.id,{label:q});break;case"sortBy":a(m,z.id,{label:q});break;case"detailColumns":{const I=W.map((L,O)=>O===$?{...L,label:q}:L);r(m,{detailColumns:I});break}}},[m,g,s,o,i,a,r]),y=w.useCallback((A,$)=>{if(!m)return;const W=g("metrics")[A];W&&o(m,W.id,{aggregate:$,label:cW(W.name,$)})},[m,g,o]),v=w.useCallback((A,$,q,W="groupBy")=>{if(!m)return;const z=g(W),I=z[A];if(!I)return;const L={dateFormat:$,customFormat:$==="custom"&&q?q:void 0};if(W==="detailColumns"){const O=z.map((R,H)=>H===A?{...R,...L}:R);r(m,{detailColumns:O});return}s(m,I.id,L)},[m,g,r,s]),C=w.useCallback((A,$)=>{if(!m)return;const W=g("groupBy")[A];W&&s(m,W.id,{granularity:$})},[m,g,s]),N=w.useCallback((A,$)=>{if(!m)return;const W=g("metrics")[A];W&&o(m,W.id,{aliasTemplate:$})},[m,g,o]),S=w.useCallback((A,$)=>{if(console.log("handleValueAliasesChange",A,$),!m)return;console.log("handleValueAliasesChange",A,$);const W=g("metrics")[A];W&&(console.log("handleValueAliasesChange",$),o(m,W.id,{valueAliases:$}))},[m,g,o]),j=w.useCallback((A,$)=>{if(!m)return;const W=g("metrics")[A];W&&o(m,W.id,{comparisonType:$,...$!=="target"?{targetValue:void 0}:{}})},[m,g,o]),k=w.useCallback(A=>{m&&r(m,{showTrendline:A})},[m,r]),_=w.useCallback(A=>{m&&r(m,{trendlineWindow:A})},[m,r]),E=w.useCallback(A=>{m&&r(m,{trendlineGranularity:A})},[m,r]),M=w.useCallback((A,$)=>{if(!m)return;const W=g("metrics")[A];W&&o(m,W.id,{targetValue:$})},[m,g,o]),T=w.useCallback(async A=>{var R;if(!m)return;const $=[...g("groupBy"),...g("pivotBy"),...g("metrics"),...g("sortBy"),...g("detailColumns")],q=A,W=zCe(q,$,{joinPlan:(R=e==null?void 0:e.config)==null?void 0:R.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!W.isValid){W.showError&&iW();return}const z=HCe(q,$,h);if(!z){We.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const I=Lte(q,z,h);if(!I.isValid){We.error("Invalid Field Type",{description:I.reason,position:"top-center",duration:3e3});return}const L=g(z);if(aW(q,L))return;const O=uW(q,z,L);if(O){const H=[...L,O];b(z,H),z==="metrics"&&zte(h,e==null?void 0:e.config,r,m,H)}},[m,e==null?void 0:e.config,g,b,t,n,h,r]),P=w.useCallback((A,$)=>{if(!m)return;const W=g(A)[$];if(W){if(A!=="sortBy"){const z=g("sortBy"),I=z.filter(L=>!(L.name===W.name&&L.qualifiedEntityName===W.qualifiedEntityName));I.length!==z.length&&r(m,{sortByColumns:I})}switch(A){case"groupBy":l(m,W.id);break;case"metrics":u(m,W.id);break;case"pivotBy":d(m,W.id);break;case"sortBy":f(m,W.id);break;case"detailColumns":{r(m,{detailColumns:(g("detailColumns")||[]).filter((z,I)=>I!==$)});break}}}},[m,g,l,u,d,f,r]);return{getFieldsForContainer:g,setFieldsForContainer:b,updateLabel:x,handleAggregationChange:y,handleDateFormatChange:v,handleGranularityChange:C,handleAliasTemplateChange:N,handleValueAliasesChange:S,removeField:P,handleFieldClick:T,handleMetricComparisonChange:j,handleKpiShowTrendlineChange:k,handleKpiTrendlineWindowChange:_,handleKpiTrendlineGranularityChange:E,handleMetricTargetValueChange:M,cardType:h}};function hN(e,t){var Ke,tt,mt,gt,dt,Ht,Ge,Nt;const{tokenProps:n}=Xe(),r=ws(),s=Xe().authToken||e,o=Le(ce=>ce.selectedConnectionId),i=Le(ce=>ce.card),{queryKey:a}=ame(i),l=Le(ce=>ce.selectedDatamodelId),u=Le(ce=>ce.isDevMode),d=Le(ce=>ce.selectedDatabaseName),f=Le(ce=>ce.selectedSchemaName),h=Le(ce=>ce.selectedTableName),m=Le(ce=>ce.actions.setSelectedConnectionId),p=Le(ce=>ce.actions.setSelectedDatamodelId),g=Le(ce=>ce.actions.setSelectedDatabaseName),b=Le(ce=>ce.actions.setSelectedSchemaName),x=Le(ce=>ce.actions.setSelectedTableName);Le(ce=>ce.actions.setCardSql);const{setQueryConfig:y}=Cr();function v(ce){var ke;if(!o||!ce)return!1;const Ae=((ke=_==null?void 0:_.capabilities)==null?void 0:ke.path)||[],Te=Ae.includes("database"),Ie=Ae.includes("schema");return!(!Ae.includes("table")||Te&&(!d||d==="NA")||Ie&&!f)}function C(ce){var Ae;return!o||!ce?!1:!!((Ae=_==null?void 0:_.capabilities)!=null&&Ae.path.includes("database"))}const{refetchConnections:N,connectionsData:S,isConnectionsLoading:j,isConnectionsError:k,selectedConnection:_}=Ni(e),{refetch:E,data:M,isLoading:T,isError:P}=mn({queryKey:["models",o],queryFn:()=>rr(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),F=_==null?void 0:_.type,A=((Ke=_==null?void 0:_.capabilities)==null?void 0:Ke.path.includes("schema"))??!1,$=((tt=_==null?void 0:_.capabilities)==null?void 0:tt.path.length)===1&&((mt=_==null?void 0:_.capabilities)==null?void 0:mt.path[0])==="table",q=$,{data:W,isLoading:z,isFetching:I,isError:L,refetch:O}=mn({queryKey:["databases",o],queryFn:()=>rr(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:C(F)}),{data:R,isLoading:H,isFetching:V,isError:Y,refetch:U}=mn({queryKey:["schemas",o,d],queryFn:()=>rr(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&A&&d!=="NA"}),{data:B,isLoading:G,isFetching:Z,isError:Q,refetch:K}=mn({queryKey:["tables",o,d,f],queryFn:()=>rr(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(F)}),{columns:te,isColumnsLoading:ie,isColumnsFetching:ue,isColumnsError:he,refetchColumns:je}=dW(e);w.useEffect(()=>{$&&(g(""),b(""),p(""),F==="API"&&x("api"))},[F,x,g,b,p,$]);const be=(_==null?void 0:_.type)==="API"?(gt=_==null?void 0:_.type)==null?void 0:gt.toLowerCase():h||"",Me=A&&f||"";function le(ce){x(ce),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function ae(ce){b(ce),x("")}function xe(ce){g(ce==="none"?"":ce),b(""),x(""),ce!=="none"&&ce!==""&&p("")}function de(ce){m(ce)}function Se(ce){p(ce==="none"?"":ce),ce!=="none"&&ce!==""&&g("")}W&&((dt=W==null?void 0:W.databases)==null?void 0:dt.length)>0,R&&((Ht=R==null?void 0:R.schemas)==null?void 0:Ht.length)>0;const ge=S==null?void 0:S.connections.map(ce=>({id:ce.id,name:ce.name,type:ce.type})),se=(Ge=M==null?void 0:M.datamodels)==null?void 0:Ge.map(ce=>({id:ce.id,name:ce.name})),me=W==null?void 0:W.databases.map(ce=>({id:ce.database_name,name:ce.database_name})),Oe=R==null?void 0:R.schemas.map(ce=>({id:ce.schema_name,name:ce.schema_name})),Pe=B==null?void 0:B.tables.map(ce=>({id:ce.table_name,name:ce.table_name})),Re=(Nt=M==null?void 0:M.datamodels.find(ce=>ce.id===l))==null?void 0:Nt.name,He=_!=null&&_.capabilities?tw({schemaName:Me,tableName:be,modelName:Re,databaseName:d||"",capabilities:_.capabilities}):be;return{connectionItems:ge,selectedConnectionId:o,selectedConnection:_,isConnectionsLoading:j,isConnectionsError:k,modelItems:se,selectedDatamodelId:l,selectedDatamodelName:Re,isModelsLoading:T,isModelsError:P,selectedDatabaseName:d,databaseItems:me,isDatabasesLoadingOrFetching:z||I,isDatabaseError:L,schemaItems:Oe,selectedSchemaName:f,isSchemaLoadingOrFetching:H||V,isSchemaError:Y,tableItems:Pe,selectedTableName:h,isTableLoadingOrFetching:G||Z,isTableError:Q,columns:te,isColumnsLoadingOrFetching:ie||ue,isColumnsError:he,isNonDbConnection:q,connectionType:F,tableName:be,formattedTableName:He,schemaName:Me,refetchConnections:N,refetchModels:E,refetchDatabases:O,refetchSchemas:U,refetchTables:K,refetchColumns:je,handleConnectionChange:de,handleDatamodelChange:Se,handleDatabaseChange:xe,handleSchemaChange:ae,handleTableChange:le}}function vv(e){return`${e}-${kr()}`}function X6(e,t){const n=gi(e.replace(/_/g," "));switch(t){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function dJe(e,t){const n=gi(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function gP(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return{tableName:void 0,schemaName:void 0,databaseName:void 0,connectionId:e==null?void 0:e.connectionId,connectionType:e==null?void 0:e.connectionType};const t=e.selectedEntities[0];return{tableName:t==null?void 0:t.name,schemaName:t==null?void 0:t.schema,databaseName:t==null?void 0:t.database,connectionId:e.connectionId,connectionType:e.connectionType}}function Vte(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Hte(){const e=Le(j=>j.sqlGen),t=Le(j=>j.isDevMode),n=Le(j=>j.card.dataSource),r=Le(j=>{var k,_;return(_=(k=j.card)==null?void 0:k.queryConfig)==null?void 0:_.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=gP(n),a=Vte(n),l=Le(j=>j.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:m,setIsShowingVisual:p}=Cr(),{modelItems:g,selectedDatamodelName:b}=hN(),{selectedConnection:x}=Ni(),y=x==null?void 0:x.capabilities,v=j=>({column_name:j.name,data_type:j.dataType,label:j.label,description:j.description});return{handleDevModeFieldClick:j=>{var _;if(!t)return;const k=v(j);if(t&&a&&s&&y){const E=WT(k,e);m(E);const M=(_=g==null?void 0:g.find(P=>P.id===l))==null?void 0:_.name,T=UT(E,o||"",s,M||"",i||"",y,j.qualifiedEntityName);T&&(f(T),h(!0))}else if(!t){if(_x(k.data_type))if(r&&r.length>0){const E={...k,role:"groupby",id:vv(k.column_name),name:k.column_name,type:k.data_type};d(E)}else{const E={...k,role:"metric",id:vv(k.column_name),name:k.column_name,label:X6(k.column_name,"COUNT"),type:k.data_type,aggregate:"COUNT"};u(E)}if(Xi(k.data_type)){const E={...k,role:"groupby",id:vv(k.column_name),name:k.column_name,type:k.data_type,label:dJe(k.column_name,"month"),granularity:"month"};d(E)}if(Zi(k.data_type)){const E={...k,role:"metric",id:vv(k.column_name),name:k.column_name,label:X6(k.column_name,"SUM"),type:k.data_type,aggregate:"SUM"};u(E)}}},handleShowSample:()=>{if(!a||!s||!y){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const j=tw({schemaName:o||"",tableName:s,modelName:b,databaseName:i||"",capabilities:y});p(!1);const _=(x==null?void 0:x.type)==="MSSQL"?`SELECT top 10 * FROM ${j}`:`SELECT * FROM ${j} LIMIT 10`;f(_),h(!0)},handleShowCount:()=>{if(!a||!s||!y){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const j=tw({schemaName:o||"",tableName:s,modelName:b,databaseName:i||"",capabilities:y});f(`SELECT COUNT(*) as count FROM ${j}`),h(!0)},isNumberField:j=>Zi(j.dataType)}}function fJe(e){const t=e.qualifiedFieldName,r=(e.qualifiedEntityName||e.qualifiedFieldName.split(".").slice(0,-1).join(".")).split(".").map(o=>hb(o)).join("."),s=hb(e.name);return{qualifiedColumnName:t,qualifiedTableName:r,formattedColumnName:s}}function Ute(e){const t=e;return{name:e.name,qualifiedFieldName:e.qualifiedFieldName,qualifiedEntityName:e.qualifiedEntityName,entityName:e.entityName,entityId:e.entityId,entityType:e.entityType,dataType:e.dataType,role:e.role,expression:t.expression,calculatedFormula:t.calculatedFormula}}function Wte(e,t){if(!(!e&&!t))return{semanticDomainId:e==null?void 0:e.semanticDomainId,selectedEntities:(e==null?void 0:e.selectedEntities)||[],connectionId:(e==null?void 0:e.connectionId)||(t==null?void 0:t.connectionId),connectionType:(e==null?void 0:e.connectionType)||(t==null?void 0:t.connectionType)}}function qte(e){var t,n;return e?!!(e.entityName===ec||e.expression||(n=(t=e.calculatedFormula)==null?void 0:t.inputFields)!=null&&n.length):!1}function Yte(){const e=J(l=>l.dashboard.filters)||[],t=J(l=>l.selectedSheetId),n=J(l=>l.actions.addFilter),r=J(l=>l.actions.removeFilter),{removeFilterValues:s}=Bt(),o=Le(l=>l.card.dataSource),{selectedConnection:i}=Ni();function a(l,u="sheet"){const{qualifiedColumnName:d,qualifiedTableName:f,formattedColumnName:h}=fJe(l);let m;if(u==="sheet"&&t?m=Xke(e,d,f,t):m=e==null?void 0:e.find(p=>km(p.column)===km(d)),m)s(m.id),r(m.id);else{const p=kr(),g=Ute(l),b=Wte(o,{connectionId:i==null?void 0:i.id,connectionType:i==null?void 0:i.type}),x=qte(g),y=u==="sheet"&&t?[t]:void 0;return n({id:p,location:u,column:d,title:l.label||l.name,dataType:l.dataType,qualifiedTableName:f,connectionId:(i==null?void 0:i.id)||"",operation:"in",applyToSheetIds:y,sql:x?"":rZ(l.dataType,f,h),fieldMeta:g,semanticContext:b}),p}}return{assignFilter:a}}function hJe({column:e}){const[t,n]=w.useState(!1),r=Le(y=>y.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=gP(r),a=Le(y=>y.selectedDatamodelId),l=Le(y=>y.sqlGen),{modelItems:u,selectedConnection:d}=hN(),f=d==null?void 0:d.capabilities,h=Le(y=>y.actions.setSqlGen),m=Le(y=>y.actions.setCardSql),p=Le(y=>y.actions.setRunSql),g=Vte(r);function b(y,v){var k,_;if(!g||!s){console.warn("Cannot generate SQL: missing table metadata");return}const C=WT(y,l,v),N=(k=u==null?void 0:u.find(E=>E.id===a))==null?void 0:k.name;if(h(C),!f){console.warn("Cannot generate SQL: missing connection capabilities");return}const S=(_=y.qualifiedFieldName)==null?void 0:_.split(".").slice(0,-1).join("."),j=UT(C,o||"",s,N||"",i||"",f,S);j&&(m(j),p(!0)),n(!1)}function x(){return c.jsxs("ul",{className:"text-xs",children:[c.jsx("li",{onClick:()=>b(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),c.jsx("li",{onClick:()=>b(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),c.jsx("li",{onClick:()=>b(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),c.jsx("li",{onClick:()=>b(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),c.jsx("li",{onClick:()=>b(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return g?c.jsxs(Mf,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(Df,{asChild:!0,children:c.jsx(zm,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(If,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:x()})]}):null}function mJe({field:e,fieldState:t}){return c.jsxs("div",{className:"w-64 bg-background p-0",children:[c.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[c.jsx("h3",{className:"text-sm font-medium text-foreground",children:e.label||e.name}),c.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:e.dataType})]}),e.description&&c.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:e.description}),t&&t.tooltip&&c.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:c.jsx("p",{className:"text-xs text-muted-foreground",children:t.tooltip})}),c.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:c.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:e.name})})]})}function Q6({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s,actions:o}){const i=Le(K=>K.isDevMode),a=t==="filter"||t==="inline-filter",l=i||a||(n==null?void 0:n.state)==="unreachable"&&!a,u=J(K=>K.dashboard.filters),d=J(K=>K.selectedSheetId),f=J(K=>K.actions.removeFilter),{removeFilterValues:h}=Bt(),{assignFilter:m}=Yte(),p=t==="filter"?ac(u,d):u,g=t==="filter"?p==null?void 0:p.find(K=>{if(K.title===e.name)return!0;const te=km(K.column||""),ie=km(e.name);return te.endsWith(`.${ie}`)||te===ie}):void 0,b=!!g,x=t==="inline-filter"&&(s==null?void 0:s.some(K=>K.column===e.qualifiedFieldName||K.column===e.name)),y=b||x,v=g&&a?u==null?void 0:u.find(K=>K.id===g.id):void 0,C=v&&(v.applyToSheetIds&&v.applyToSheetIds.length>1||v.excludeSheetIds&&v.excludeSheetIds.length>0||!v.applyToSheetIds&&!v.excludeSheetIds&&!v.sheetId);a&&y&&console.log("[SourceField Debug]",{fieldName:e.name,hasActiveFilter:y,activeFilterOnSheet:g?{id:g.id,title:g.title,column:g.column,applyToSheetIds:g.applyToSheetIds,excludeSheetIds:g.excludeSheetIds}:null,activeFilterForField:v?{id:v.id,title:v.title,column:v.column,applyToSheetIds:v.applyToSheetIds,excludeSheetIds:v.excludeSheetIds}:null,isMultiSheetFilter:C,selectedSheetId:d});const[N,S]=w.useState(!1),[j,k]=w.useState(null),{attributes:_,listeners:E,setNodeRef:M,transform:T,transition:P,isDragging:F}=Py({id:e.id,disabled:l}),[A,$]=w.useState(!1),q=Le(K=>K.card),{handleFieldClick:W}=Bte(q),{handleDevModeFieldClick:z,isNumberField:I}=Hte(),L=()=>{v&&(console.log("[SourceField] Removing multi-sheet filter:",v.id),h(v.id),f(v.id)),k(null),S(!1)},O=()=>{if(t==="inline-filter"&&r){r(e);return}t==="filter"?y&&C?(k(e),S(!0)):m(e,"sheet"):i?z(e):W(e)},R={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},H={transform:wi.Transform.toString(T),transition:P},V=()=>{if(!n||a)return{};const te={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[n.state]||{};return n.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",...te},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...te},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...te}}[n.state]||te};function Y(K){return K==="domain"?{label:"Domain",Icon:Ix,className:"border-border bg-muted text-foreground"}:K==="dashboard"?{label:"Dashboard",Icon:gM,className:"border-border bg-muted/70 text-foreground"}:{label:"Card",Icon:e9,className:"border-border bg-muted/40 text-foreground"}}const U=V(),B=e.fieldScope,G=B?Y(B):null,Z=Ww(e),Q=Z&&ic(e);return c.jsxs("div",{ref:M,style:H,...l?{}:_,...l?{}:E,className:X("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",F&&"scale-95 opacity-50",!F&&"border",U.borderColor||"border-transparent",U.bgColor||"",U.hoverBorderColor,U.hoverBgColor||"hover:bg-muted",U.opacity,U.cursor,b&&"border-accent-foreground/20 bg-accent",x&&"border-primary/20 bg-primary/10",{"cursor-pointer":i||a,"cursor-grab active:cursor-grabbing":!l&&!i&&!a}),title:n==null?void 0:n.tooltip,children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:O,children:[c.jsxs("div",{className:"relative shrink-0",children:[Rm(e.dataType),Z&&c.jsx("span",{className:X("absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 text-[7px] font-semibold uppercase italic leading-none shadow-sm",Q?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),c.jsx(Ln,{children:c.jsxs(ln,{children:[c.jsx(cn,{asChild:!0,children:c.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:c.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${A?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),c.jsx(dn,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:c.jsx(mJe,{field:e,fieldState:n})})]})}),t==="editor"&&G&&c.jsx("span",{title:G.label,className:X("shrink-0 rounded-full border p-1",G.className),children:c.jsx(G.Icon,{className:"h-3.5 w-3.5"})}),i&&!a&&I(e)&&c.jsx("div",{onClick:K=>K.stopPropagation(),children:c.jsx(hJe,{column:R})}),o&&c.jsx("div",{className:"ml-auto flex items-center",onClick:K=>K.stopPropagation(),onPointerDown:K=>K.stopPropagation(),children:o})]}),A&&c.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:c.jsx(Uo,{className:"",children:c.jsxs(ea,{className:"space-y-2 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(t9,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.label||e.name})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Jie,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.name})]}),c.jsx(qe,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),c.jsx(Zm,{open:N,onOpenChange:S,children:c.jsxs(Sf,{children:[c.jsxs(Nf,{children:[c.jsx(kf,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(Ef,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(jf,{children:[c.jsx(Tf,{children:"Cancel"}),c.jsx(_f,{onClick:L,children:"Remove Filter"})]})]})})]})}var ha="Accordion",pJe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[bP,gJe,bJe]=Px(ha),[mN]=Lr(ha,[bJe,YW]),xP=YW(),Gte=w.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(bP.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(wJe,{...o,ref:t}):c.jsx(vJe,{...s,ref:t})})});Gte.displayName=ha;var[Kte,xJe]=mN(ha),[Zte,yJe]=mN(ha,{collapsible:!1}),vJe=w.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,l]=os({prop:n,defaultProp:r??"",onChange:s,caller:ha});return c.jsx(Kte,{scope:e.__scopeAccordion,value:w.useMemo(()=>a?[a]:[],[a]),onItemOpen:l,onItemClose:w.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(Zte,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(Xte,{...i,ref:t})})})}),wJe=w.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i,a]=os({prop:n,defaultProp:r??[],onChange:s,caller:ha}),l=w.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=w.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return c.jsx(Kte,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(Zte,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(Xte,{...o,ref:t})})})}),[CJe,pN]=mN(ha),Xte=w.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=w.useRef(null),l=ut(a,t),u=gJe(n),f=bu(s)==="ltr",h=$e(e.onKeyDown,m=>{var k;if(!pJe.includes(m.key))return;const p=m.target,g=u().filter(_=>{var E;return!((E=_.ref.current)!=null&&E.disabled)}),b=g.findIndex(_=>_.ref.current===p),x=g.length;if(b===-1)return;m.preventDefault();let y=b;const v=0,C=x-1,N=()=>{y=b+1,y>C&&(y=v)},S=()=>{y=b-1,y<v&&(y=C)};switch(m.key){case"Home":y=v;break;case"End":y=C;break;case"ArrowRight":o==="horizontal"&&(f?N():S());break;case"ArrowDown":o==="vertical"&&N();break;case"ArrowLeft":o==="horizontal"&&(f?S():N());break;case"ArrowUp":o==="vertical"&&S();break}const j=y%x;(k=g[j].ref.current)==null||k.focus()});return c.jsx(CJe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(bP.Slot,{scope:n,children:c.jsx(Ze.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),H1="AccordionItem",[SJe,yP]=mN(H1),Qte=w.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=pN(H1,n),i=xJe(H1,n),a=xP(n),l=yr(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(SJe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(ZW,{"data-orientation":o.orientation,"data-state":sne(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});Qte.displayName=H1;var Jte="AccordionHeader",ene=w.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=pN(ha,n),o=yP(Jte,n);return c.jsx(Ze.h3,{"data-orientation":s.orientation,"data-state":sne(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});ene.displayName=Jte;var kT="AccordionTrigger",tne=w.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=pN(ha,n),o=yP(kT,n),i=yJe(kT,n),a=xP(n);return c.jsx(bP.ItemSlot,{scope:n,children:c.jsx(JSe,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});tne.displayName=kT;var nne="AccordionContent",rne=w.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=pN(ha,n),o=yP(nne,n),i=xP(n);return c.jsx(eNe,{role:"region","aria-labelledby":o.triggerId,"data-orientation":s.orientation,...i,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...e.style}})});rne.displayName=nne;function sne(e){return e?"open":"closed"}var NJe=Gte,jJe=Qte,kJe=ene,one=tne,ine=rne;const vP=NJe,fx=D.forwardRef(({className:e,...t},n)=>c.jsx(jJe,{ref:n,className:X("border-b",e),...t}));fx.displayName="AccordionItem";const hx=D.forwardRef(({className:e,children:t,...n},r)=>c.jsx(kJe,{className:"flex",children:c.jsxs(one,{ref:r,className:X("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,c.jsx(cr,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));hx.displayName=one.displayName;const mx=D.forwardRef(({className:e,children:t,...n},r)=>c.jsx(ine,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:c.jsx("div",{className:X("pb-4 pt-0",e),children:t})}));mx.displayName=ine.displayName;let ane=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,n)=>(n&=63,n<36?t+=n.toString(36):n<62?t+=(n-26).toString(36).toUpperCase():n>62?t+="-":t+="_",t),"");const px=[{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}],fl=e=>e.trim().toLowerCase().replace(/\s+/g,"_"),jl=e=>e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e;function J6(e,t,n,r,s,o,i,a,l,u){const d=px.find(x=>x.id===t);if(!d)throw new Error(`Unknown operation: ${t}`);let f,h=[],m;if(t==="custom"){if(!(a!=null&&a.trim()))throw new Error("Custom expression is required");f=a.trim(),h=u||[]}else if(t==="scale"){if(!n)throw new Error("Metric A is required for scale operation");if(l===void 0||Number.isNaN(l))throw new Error("Constant factor is required for scale operation");f=d.template().replace("{constant}",String(l)),h=[n],m=l}else{if(!n||!r)throw new Error("Metrics A and B are required for standard operations");f=d.template(),h=[n,r]}const p={operation:t,inputFields:h,...m!==void 0&&{constant:m}},g=fl(e);return{id:i||`calc_${ane(10)}`,name:g,label:e,alias:g,qualifiedFieldName:g,dataType:"number",role:"metric",aggregate:"SUM",expression:f,calculatedFormula:p,entityId:o,entityName:ec,entityType:"table",description:`Calculated field: ${e}`}}function EJe(e){var r,s;const t=px.find(o=>o.id===e.operation);if(!t)return"Unknown operation";if(e.operation==="custom")return"Custom expression";if(e.operation==="scale"){const o=((r=e.inputFields[0])==null?void 0:r.label)||((s=e.inputFields[0])==null?void 0:s.name)||"A",i=e.constant??1;return`${o} × ${i}`}return e.inputFields.map(o=>o.label||o.name).join(` ${t.symbol} `)}function _Je(e,t,n,r,s,o){const i=fl(e);return{id:o||`calc_dim_${ane(10)}`,name:i,label:e.trim(),alias:i,qualifiedFieldName:i,dataType:r,role:"groupby",expression:t.trim(),calculatedFormula:{operation:"custom",inputFields:n.map(a=>a.role==="metric"?{...a,role:"metric"}:{...a,role:"groupby"})},entityId:s,entityName:ec,entityType:"table",description:`Calculated field: ${e.trim()}`}}function TJe(){const{domainCalculatedFields:e}=mP(),t=w.useMemo(()=>e.filter(r=>r.role==="metric"),[e]),n=w.useMemo(()=>e.filter(r=>r.role==="groupby"),[e]);return{fields:e,metrics:t,dimensions:n}}function MJe({value:e,onChange:t,disabled:n,options:r=["dimension","metric"]}){const s=r.length>0?r:["dimension","metric"],o=["dimension","metric"].filter(l=>s.includes(l)),i=n||o.length<=1,a=o.includes(e)?e:o[0];return c.jsx(Ls,{value:a,onValueChange:l=>t(l),className:"w-full",children:c.jsx(Cs,{className:"grid h-9 w-full",style:{gridTemplateColumns:`repeat(${o.length}, minmax(0, 1fr))`},children:o.map(l=>c.jsx(rn,{value:l,disabled:i,className:"text-xs",children:l==="metric"?"Calculated Metric":"Calculated Dimension"},l))})})}function DJe({groups:e,searchTerm:t,onSearchTermChange:n,onFieldClick:r,selectedFieldIds:s,disabled:o}){const i=new Set(s||[]),a=e.length>0||t.length>0,l=e.map(f=>f.id),u=(f,h)=>{if(!h)return f;const m=f.toLowerCase(),p=h.toLowerCase();return m.startsWith(`${p}.`)?f.slice(h.length+1):f},d=(f,h)=>{const p=(f.name||f.baseLabel||f.label||f.tokenLabel||"").trim(),g=[h,f.qualifiedEntityName,f.entityName].filter(Boolean);for(const b of g){const x=u(p,b);if(x!==p)return x}return p.includes(".")&&p.split(".").pop()||p};return c.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3 border-r border-border pr-4",children:[a&&c.jsxs("div",{className:"relative",children:[c.jsx(Zo,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),c.jsx(jn,{value:t,onChange:f=>n(f.target.value),placeholder:"Search fields...",className:"pl-10 pr-10"}),t&&c.jsx("button",{type:"button",onClick:()=>n(""),className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",children:c.jsx(St,{className:"size-3.5"})})]}),c.jsx(nl,{className:"min-h-0 flex-1",children:e.length===0?c.jsx("div",{className:"rounded-md border border-dashed border-muted px-3 py-6 text-center text-xs text-muted-foreground",children:"No fields match your search."}):c.jsx(vP,{type:"multiple",defaultValue:l,className:"space-y-2",children:e.map(f=>c.jsxs(fx,{value:f.id,className:"border-none",children:[c.jsx(hx,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:f.label}),c.jsx(qe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:f.fields.length})]})}),c.jsx(mx,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:f.fields.map(h=>{const m=i.has(h.id),p=!h.isCompatible||o,g=h.isCalculated&&h.role==="metric",b=d(h,f.label);return c.jsxs("button",{type:"button",onClick:()=>h.isCompatible&&!o&&r(h),className:X("group/container flex w-full items-center gap-3 rounded-lg border border-transparent px-2 py-2 text-left transition-all",p?"cursor-not-allowed opacity-50":"hover:bg-muted",m&&"border-border bg-muted"),disabled:p,children:[c.jsxs("div",{className:"relative shrink-0",children:[Rm(h.dataType),h.isCalculated&&c.jsx("span",{className:X("absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 text-[7px] font-semibold uppercase italic leading-none shadow-sm",g?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),c.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:c.jsx("span",{className:X("block truncate text-sm text-foreground/80",!p&&"group-hover/container:text-foreground"),children:b})}),m&&c.jsx(qe,{variant:"secondary",className:"shrink-0 text-[10px]",children:"Selected"})]},h.id)})})})]},f.id))})})]})}function IJe({value:e,onChange:t,allowCustom:n,disabled:r}){const s=px.filter(l=>n?!0:l.id!=="custom"),i=!s.some(l=>l.id==="custom")&&e==="custom"?[...s,px.find(l=>l.id==="custom")]:s,a=i.find(l=>l.id===e);return c.jsxs("div",{className:"space-y-2",children:[c.jsxs(it,{value:e,onValueChange:l=>t(l),disabled:r,children:[c.jsx(rt,{children:c.jsx(at,{})}),c.jsx(st,{children:c.jsxs(gI,{children:[c.jsx(oS,{children:"OPERATIONS"}),i.map(l=>c.jsx(we,{value:l.id,children:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"font-mono text-sm",children:l.symbol}),c.jsx("span",{children:l.label})]})},l.id))]})})]}),a&&c.jsx("p",{className:"text-xs text-muted-foreground",children:a.description})]})}const RJe={COUNT:"Count",DISTINCT:"Count Distinct",SUM:"Sum",AVG:"Average",MIN:"Minimum",MAX:"Maximum",MEDIAN:"Median"};function AJe({value:e,onChange:t,disabled:n,fieldDataType:r,allowMedian:s}){const i=(r?vr(r):"number")==="number",a=["SUM","AVG","COUNT","DISTINCT","MIN","MAX"],l=i?s?[...a,"MEDIAN"]:a:["COUNT","DISTINCT"];return c.jsxs(it,{value:e,onValueChange:u=>t(u),disabled:n,children:[c.jsx(rt,{className:"h-9",children:c.jsx(at,{})}),c.jsx(st,{children:l.map(u=>c.jsx(we,{value:u,children:RJe[u]},u))})]})}const PJe=e=>{const n=(e.name||e.baseLabel||e.label||e.tokenLabel||"").trim();return n.includes(".")&&n.split(".").pop()||n};function ez({label:e,input:t,availableFields:n,excludeFieldIds:r,onFieldSelect:s,onAggregateChange:o,onRemove:i,onActivate:a,allowMedian:l,disabled:u}){const d=(t==null?void 0:t.field.id)||"",f=r!=null&&r.length?n.filter(h=>!r.includes(h.id)):n;return c.jsxs("div",{className:X("flex items-center gap-2 rounded-md border border-border px-2 py-2",a&&!u&&"cursor-pointer",u&&"opacity-60"),onClick:u?void 0:a,children:[c.jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded bg-muted font-mono text-xs font-semibold",children:e}),c.jsxs("div",{className:"flex flex-1 gap-2",children:[c.jsxs(it,{value:d,onValueChange:h=>{const m=f.find(p=>p.id===h);m&&s(m)},disabled:u,children:[c.jsx(rt,{className:"h-9 flex-1",children:c.jsx(at,{placeholder:"Select field"})}),c.jsx(st,{children:f.map(h=>c.jsx(we,{value:h.id,children:PJe(h)},h.id))})]}),c.jsx("div",{className:"w-36",children:c.jsx(AJe,{value:(t==null?void 0:t.aggregate)||"SUM",onChange:o,disabled:u||(t==null?void 0:t.isCalculatedField),fieldDataType:t==null?void 0:t.field.dataType,allowMedian:l})})]}),t&&c.jsx(oe,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:h=>{h.stopPropagation(),i()},disabled:u,children:c.jsx(St,{className:"h-3.5 w-3.5"})})]})}const tz=w.forwardRef(function({value:t,onChange:n,onGenerate:r,showGenerate:s,disabled:o},i){return c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("span",{className:"text-sm font-medium",children:"Expression"}),s&&c.jsxs(oe,{type:"button",size:"sm",variant:"outline",onClick:r,disabled:o,className:"h-7 gap-2 text-xs",children:[c.jsx(lC,{className:"h-3.5 w-3.5"}),"Generate with AI"]})]}),c.jsx(nx,{ref:i,value:t,onChange:a=>n(a.target.value),disabled:o,placeholder:"CASE WHEN {Amount} > 100 THEN 'Large' ELSE 'Small' END",className:"min-h-[140px] font-mono text-xs"})]})});function FJe({result:e}){const t=e.errors.length>0;return c.jsxs("div",{className:X("rounded-md border px-3 py-2 text-xs",t?"border-destructive/40 bg-destructive/10 text-destructive":"border-emerald-500/30 bg-emerald-500/10 text-emerald-700"),children:[c.jsx("div",{className:"font-medium",children:t?"Validation Failed":"Validation Passed"}),e.tokens.length>0&&c.jsxs("div",{className:"mt-2 space-y-1",children:[c.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Tokens Found"}),e.tokens.map(n=>c.jsx("div",{children:n.field?`{${n.token}} -> ${n.field.qualifiedFieldName||n.field.name}`:`{${n.token}}`},n.token))]}),e.errors.length>0&&c.jsxs("div",{className:"mt-2 space-y-1",children:[c.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Errors"}),e.errors.map((n,r)=>c.jsxs("div",{children:[n.message,n.suggestion?` (${n.suggestion})`:""]},`${n.code}-${r}`))]}),e.warnings.length>0&&c.jsxs("div",{className:"mt-2 space-y-1",children:[c.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Warnings"}),e.warnings.map((n,r)=>c.jsxs("div",{children:[n.message," ",n.suggestion]},`${n.code}-${r}`))]}),e.inferredDataType&&c.jsxs("div",{className:"mt-2 text-[11px] text-muted-foreground",children:["Inferred Output Type: ",e.inferredDataType]})]})}function nz({onValidate:e,isValidating:t,validationResult:n,fallbackResult:r,error:s,showFallback:o,disabled:i}){return c.jsxs("div",{className:"space-y-2",children:[c.jsx(oe,{type:"button",variant:"outline",onClick:e,disabled:t||i,className:"h-8",children:t?"Validating...":"Validate Expression"}),s&&c.jsx("div",{className:"text-xs text-destructive",children:s}),(n||o)&&c.jsx(FJe,{result:n||r})]})}function OJe({scope:e,onChange:t,showDashboardScope:n,showDomainScope:r,error:s,disabled:o}){return c.jsxs("div",{className:"space-y-3 border-t border-border pt-4",children:[c.jsx(fe,{children:"Availability"}),c.jsxs(so,{value:e,onValueChange:i=>t(i),className:"space-y-2",disabled:o,children:[c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(xn,{id:"scope-card",value:"card"}),c.jsx(fe,{htmlFor:"scope-card",className:"text-sm font-normal",children:"This card only"})]}),n&&c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(xn,{id:"scope-dashboard",value:"dashboard"}),c.jsx(fe,{htmlFor:"scope-dashboard",className:"text-sm font-normal",children:"All cards in this dashboard"})]}),r&&c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(xn,{id:"scope-domain",value:"domain"}),c.jsx(fe,{htmlFor:"scope-domain",className:"text-sm font-normal",children:"Save to domain"})]})]}),s&&c.jsx("p",{className:"text-xs text-red-500",children:s})]})}function $Je({description:e,tags:t,onDescriptionChange:n,onTagsChange:r,descriptionError:s,disabled:o}){return c.jsxs("div",{className:"space-y-3 rounded-md border border-muted bg-muted/30 p-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{htmlFor:"domain-description",children:"Description"}),c.jsx(vu,{id:"domain-description",value:e,onChange:i=>n(i.target.value),placeholder:"Explain what this metric represents",className:X("text-sm",s&&"border-red-500"),rows:3,disabled:o}),s&&c.jsx("p",{className:"text-xs text-red-500",children:s})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{htmlFor:"domain-tags",children:"Tags (optional)"}),c.jsx(pn,{id:"domain-tags",value:t,onChange:i=>r(i.target.value),placeholder:"profitability, kpi",disabled:o})]}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"This field will be visible to all dashboards using this domain."})]})}function LJe({endpoint:e,availableFields:t,fieldType:n,dialect:r}){const{authToken:s}=Xe(),[o,i]=w.useState(!1),[a,l]=w.useState(null);return{generateExpression:w.useCallback(async d=>{var f;if(!e)return l("AI generation is not available"),null;if(!d.trim())return l("Describe what you want to calculate"),null;i(!0),l(null);try{const h={type:"calculated-field-expression",context:{userQuery:d,availableFields:t.map(p=>({name:p.tokenLabel,dataType:p.dataType})),fieldType:n},options:{dialect:r}},m=await Yr(e,(s==null?void 0:s.accessToken)||"",h);if(!m.success||!((f=m.result)!=null&&f.generated))throw new Error(m.error||"No expression generated");return m.result.generated}catch(h){return l((h==null?void 0:h.error)||(h==null?void 0:h.message)||"AI generation failed"),null}finally{i(!1)}},[e,t,n,r,s==null?void 0:s.accessToken]),isGenerating:o,error:a}}function zJe({open:e,onOpenChange:t,availableFields:n,fieldType:r,onExpressionGenerated:s,endpoint:o,dialect:i}){const[a,l]=w.useState(""),[u,d]=w.useState(""),[f,h]=w.useState(""),{generateExpression:m,isGenerating:p,error:g}=LJe({endpoint:o,availableFields:n,fieldType:r,dialect:i}),b=w.useMemo(()=>{const S=f.trim().toLowerCase();return S?n.filter(j=>[j.label,j.baseLabel,j.name,j.tokenLabel,j.entityName,j.qualifiedEntityName].filter(Boolean).join(" ").toLowerCase().includes(S)):n},[n,f]),x=S=>{const k=(S.name||S.baseLabel||S.label||S.tokenLabel||"").trim();return k.includes(".")&&k.split(".").pop()||k},y=S=>{const j=S.entityName||S.qualifiedEntityName||"";return j?j==="SEMAPHOR_CALCULATED_FIELD"?"Calculated":j.includes(".")&&j.split(".").pop()||j:"—"},v=async()=>{const S=await m(a.trim());S&&d(S)},C=()=>{u.trim()&&(s(u.trim()),l(""),d(""),t(!1))},N=()=>{l(""),d(""),h(""),t(!1)};return c.jsx(Kr,{open:e,onOpenChange:S=>{S?t(!0):N()},children:c.jsxs(zr,{className:"max-w-3xl",children:[c.jsxs(Br,{children:[c.jsx(Vr,{children:"Generate Expression with AI"}),c.jsx(as,{children:"Describe what you want to calculate and we will draft a SQL expression."})]}),c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{htmlFor:"ai-prompt",children:"Describe what you want to calculate"}),c.jsx(nx,{id:"ai-prompt",value:a,onChange:S=>l(S.target.value),placeholder:"Create a bucket that categorizes orders as 'Large' when amount is greater than 1000",rows:2})]}),c.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs text-muted-foreground",children:[c.jsx("span",{children:"Be specific about conditions, buckets, or math you want to apply."}),c.jsx(oe,{size:"sm",onClick:v,disabled:p||!a.trim(),children:p?"Generating...":u?"Regenerate":"Generate"})]}),g&&c.jsx("p",{className:"text-xs text-destructive",children:g})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{children:"Available fields"}),c.jsxs("div",{className:"relative",children:[c.jsx(Zo,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),c.jsx(pn,{value:f,onChange:S=>h(S.target.value),placeholder:"Search fields...",className:"pl-9"})]}),c.jsx("div",{className:"overflow-hidden rounded-lg border border-border",children:c.jsx("div",{className:"max-h-48 overflow-y-auto",children:c.jsxs("table",{className:"w-full text-sm",children:[c.jsx("thead",{className:"sticky top-0 z-10 border-b bg-muted",children:c.jsxs("tr",{children:[c.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Field"}),c.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Type"}),c.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Category"})]})}),c.jsx("tbody",{className:"divide-y",children:b.length===0?c.jsx("tr",{children:c.jsx("td",{colSpan:3,className:"py-6 text-center text-xs text-muted-foreground",children:"No fields match your search."})}):b.map(S=>c.jsxs("tr",{className:"hover:bg-muted/30",children:[c.jsx("td",{className:"px-3 py-1.5 font-mono text-xs",children:x(S)}),c.jsx("td",{className:"px-3 py-1.5",children:c.jsx(qe,{variant:"secondary",className:"px-1.5 py-0 text-[11px]",children:S.dataType})}),c.jsx("td",{className:"px-3 py-1.5 text-sm text-muted-foreground",children:y(S)})]},S.id))})]})})})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{children:"Generated expression"}),c.jsx(nx,{value:u,readOnly:!0,rows:2,className:"font-mono text-sm"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Review the generated expression before using it."})]})]}),c.jsxs(is,{className:"gap-2",children:[c.jsx(oe,{variant:"ghost",onClick:N,children:"Cancel"}),c.jsx(oe,{onClick:C,disabled:!u.trim(),children:"Use Expression"})]})]})})}const BJe=/\{([^}]+)\}/g;function gN(e){return e.trim().toLowerCase()}function U1(e){return Array.from(e.matchAll(BJe)).map(t=>t[1]).filter(Boolean)}function VJe(e){const t=new Set,n=[];return e.forEach(r=>{const s=gN(r);t.has(s)||(t.add(s),n.push(r))}),n}function wP(e){const t=new Map,n=(r,s)=>{const o=gN(r),i=t.get(o)||[];i.some(a=>a.id===s.id)||t.set(o,[...i,s])};return e.forEach(r=>{n(r.tokenLabel,r),r.name&&r.name!==r.tokenLabel&&n(r.name,r),r.baseLabel&&r.baseLabel!==r.tokenLabel&&n(r.baseLabel,r)}),t}function ig(e,t){const n=U1(e),r=VJe(n),s=wP(t),o=r.map(a=>{const l=s.get(gN(a))||[];return l.length===1?l[0]:null}),i=r.filter((a,l)=>!o[l]);return{orderedTokens:r,orderedFields:o,unresolvedTokens:i}}function rz(e,t){return t.reduce((n,r,s)=>{const o=new RegExp(`\\{${HJe(r)}\\}`,"gi");return n.replace(o,`{field_${s}}`)},e)}function HJe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const UJe=e=>e.entityName===rm||e.entityName===ec?"Calculated Fields":e.qualifiedEntityName?pb(e.entityName||e.qualifiedEntityName):pb(e.entityName||"Other"),WJe=e=>vr(e.dataType||"")==="number";function qJe(e,t,n){const r=new Set((n||[]).map(s=>jl(s)));return e.filter(s=>{const o=jl(s.id);return o&&r.has(o)?!1:t==="dimension"?s.role!=="metric":!0})}function YJe(e){const t=new Map,n=new Map;return e.forEach(r=>{let o=r.entityName&&r.entityName!==ec?`${r.entityName}.${r.name}`:r.name;const i=o.toLowerCase(),a=n.get(i)||0;a>0&&(o=`${o} ${a+1}`),n.set(i,a+1),t.set(r.id,o)}),t}function GJe(e,t,n,r){if(t!=="metric")return e.map(o=>({...o,isCompatible:!0}));if(!n)return e.map(o=>({...o,isCompatible:!0}));const s=n==="COUNT"||n==="DISTINCT";return e.map(o=>{const i=s||WJe(o);return{...o,isCompatible:i}}).filter(o=>r)}function KJe(e,t){if(!t)return e;const n=t.toLowerCase();return e.filter(r=>r.name.toLowerCase().includes(n)||r.baseLabel.toLowerCase().includes(n)||r.tokenLabel.toLowerCase().includes(n)||r.dataType.toLowerCase().includes(n)||(r.qualifiedEntityName||r.entityName||"").toLowerCase().includes(n))}function ZJe(e){const t=new Map;return e.forEach(n=>{var s;const r=n.qualifiedEntityName||n.entityName||"Other";t.has(r)||t.set(r,{id:r,label:UJe(n),fields:[]}),(s=t.get(r))==null||s.fields.push(n)}),Array.from(t.values())}function XJe({fields:e,mode:t,searchTerm:n,excludeFieldIds:r,selectedAggregate:s,showIncompatible:o}){const i=w.useMemo(()=>qJe(e,t,r),[e,t,r]),a=w.useMemo(()=>YJe(i),[i]),l=w.useMemo(()=>i.map(m=>{const p=m.label||m.name,g=m.role==="metric"&&ic(m)||m.role==="groupby"&&Qx(m);return{...m,baseLabel:p,tokenLabel:a.get(m.id)||p,isCalculated:g,isCompatible:!0}}),[i,a]),u=w.useMemo(()=>wP(l),[l]),d=w.useMemo(()=>GJe(l,t,s,o),[l,t,s,o]),f=w.useMemo(()=>KJe(d,n),[d,n]),h=w.useMemo(()=>ZJe(f),[f]);return{allFields:l,filteredFields:f,groups:h,tokenCandidates:u}}const QJe=e=>{let t=0;for(const n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0},JJe=(e,t)=>{const n=e.toLowerCase(),r=t.toLowerCase();if(n===r)return 0;if(!n.length)return r.length;if(!r.length)return n.length;const s=[];for(let o=0;o<=r.length;o+=1)s[o]=[o];for(let o=0;o<=n.length;o+=1)s[0][o]=o;for(let o=1;o<=r.length;o+=1)for(let i=1;i<=n.length;i+=1)r.charAt(o-1)===n.charAt(i-1)?s[o][i]=s[o-1][i-1]:s[o][i]=Math.min(s[o-1][i-1]+1,s[o][i-1]+1,s[o-1][i]+1);return s[r.length][n.length]},eet=(e,t)=>t.map(r=>({candidate:r,distance:JJe(e,r)})).filter(r=>r.distance>0&&r.distance<=3).sort((r,s)=>r.distance-s.distance).slice(0,3).map(r=>r.candidate),tet=(e,t)=>{var r;const n=e.trim();if(n){if(/\bDATE_TRUNC\b/i.test(n))return"date";if(/\bTIMESTAMP\b/i.test(n))return"datetime";if(/\bDATE\b/i.test(n)&&!/\bUPDATE\b/i.test(n))return"date";if(/['"]/.test(n))return"string";if(/[+\-*/]/.test(n))return"number";if(t.length===1){const s=((r=t[0])==null?void 0:r.dataType)||"";if(/date|timestamp/i.test(s))return"date";if(/int|decimal|float|double|num|real/i.test(s))return"number";if(/boolean/i.test(s))return"boolean"}return"string"}},net=e=>e.map(t=>({id:t.id,name:t.name,label:t.tokenLabel,dataType:t.dataType,entityName:t.entityName,role:t.role}));function ret({expression:e,availableFields:t,excludeFieldIds:n,validationEndpoint:r,connectionId:s,dialect:o}){const{authToken:i}=Xe(),[a,l]=w.useState(null),[u,d]=w.useState(!1),[f,h]=w.useState(null),m=w.useMemo(()=>wP(t),[t]),p=w.useMemo(()=>{const x=[],y=[],v=e.trim();v||x.push({code:"SYNTAX_ERROR",message:"Expression is required"}),v&&!QJe(v)&&x.push({code:"SYNTAX_ERROR",message:"Unbalanced parentheses in expression"});const N=U1(e).map(j=>{const k=m.get(gN(j))||[];if(!k.length){const M=Array.from(m.keys()),T=eet(j,M),P=T.length?`Did you mean {${T[0]}}?`:void 0;return x.push({code:"UNKNOWN_TOKEN",message:`Unknown field token: {${j}}`,suggestion:P}),{token:j,field:null,error:"Unknown token"}}if(k.length>1)return x.push({code:"UNKNOWN_TOKEN",message:`Token {${j}} matches multiple fields. Use a disambiguated label.`}),{token:j,field:null,error:"Ambiguous token"};const _=k[0];return(n||[]).map(jl).includes(jl(_.id))?(x.push({code:"SELF_REFERENCE",message:"Cannot reference the field being edited"}),{token:j,field:null,error:"Self reference"}):{token:j,field:_}});/\bCASE\b/i.test(e)&&!/\bELSE\b/i.test(e)&&y.push({code:"MISSING_ELSE",message:"CASE expression missing ELSE clause",suggestion:"Add an ELSE branch to handle default values."}),/\//.test(e)&&!/NULLIF\s*\(/i.test(e)&&y.push({code:"DIVISION_BY_ZERO",message:"Division may result in divide-by-zero errors",suggestion:"Wrap the denominator in NULLIF(..., 0)."});const S=N.map(j=>j.field).filter(Boolean);return{isValid:x.length===0,tokens:N,errors:x,warnings:y,inferredDataType:tet(e,S)}},[e,n,m]),g=w.useCallback(async()=>{var v;if(h(null),!r||!p.isValid)return l(p),p;const x=r,y={type:"calculated-field-expression",value:e,context:{availableFields:net(t),connectionId:s,excludeFieldIds:n,dialect:o}};d(!0);try{const C=await Yr(x,(i==null?void 0:i.accessToken)||"",y),N=C.errors||[],S=C.warnings||[],j={...p,isValid:C.valid&&N.length===0,errors:N,warnings:S,inferredDataType:((v=C.metadata)==null?void 0:v.inferredType)||p.inferredDataType};return l(j),j}catch(C){return h((C==null?void 0:C.error)||"Validation failed"),l(p),p}finally{d(!1)}},[r,p,e,t,s,n,o,i==null?void 0:i.accessToken]),b=w.useCallback(()=>{l(null),h(null)},[]);return{clientResult:p,validationResult:a,isValidating:u,serverError:f,validateExpression:g,resetValidation:b}}const sz=[{value:"string",label:"String"},{value:"number",label:"Number"},{value:"boolean",label:"Boolean"},{value:"date",label:"Date"},{value:"datetime",label:"Datetime"},{value:"json",label:"JSON"},{value:"geo",label:"Geo"}],hk=e=>{if(!e)return"";const t=e.field.tokenLabel||e.field.label||e.field.name,n=e.aggregate;return n==="DISTINCT"?`COUNT(DISTINCT ${t})`:n==="COUNT"?`COUNT(${t})`:`${n}(${t})`},lne=e=>vr(e.dataType||"")==="number",hh=e=>lne(e)?"SUM":"COUNT",mk=(e,t)=>lne(e)||t==="COUNT"||t==="DISTINCT"?t:hh(e);function pk(e,t){if(e.role==="metric"){const n=e;return ic(n)?n:{...n,aggregate:t}}return{...e,id:`${e.id}_${t.toLowerCase()}`,role:"metric",aggregate:t,alias:`${(e.alias||e.name).toLowerCase()}_${t.toLowerCase()}`,entityName:e.entityName,entityId:e.entityId,qualifiedEntityName:e.qualifiedEntityName}}function ih(e,t){const n=e.role==="metric"&&ic(e);return{field:e,aggregate:n&&e.aggregate||t,isCalculatedField:n}}function cne({open:e,onOpenChange:t,availableFields:n,existingField:r,existingFieldScope:s,onSave:o,onSaveToDashboard:i,onPromoteMetricToDomain:a,onPromoteDimensionToDomain:l,cardId:u,domainId:d,initialFieldType:f="metric",allowedFieldTypes:h}){var Hf;const{tokenProps:m}=Xe(),{selectedConnection:p}=sW(),g=(p==null?void 0:p.dialect)==="bigquery"||(p==null?void 0:p.dialect)==="snowflake",[b,x]=w.useState(f),[y,v]=w.useState(""),[C,N]=w.useState("ratio"),[S,j]=w.useState(null),[k,_]=w.useState(null),[E,M]=w.useState(1),[T,P]=w.useState(""),[F,A]=w.useState(null),[$,q]=w.useState("card"),[W,z]=w.useState(""),[I,L]=w.useState(""),[O,R]=w.useState({}),[H,V]=w.useState("A"),[Y,U]=w.useState(""),[B,G]=w.useState(!1),[Z,Q]=w.useState(null),[K,te]=w.useState(!1),[ie,ue]=w.useState(!1),[he,je]=w.useState(!1),be=w.useRef(null),Me=w.useRef(!1),le=w.useRef(null),{userContext:ae}=$s(),{metrics:xe,dimensions:de}=TJe(),Se=(ae==null?void 0:ae.type)==="organization",ge=!Se,se=!!d&&Se,me=se&&!!a,Oe=se&&!!l,Pe=!!(i||me||Oe),Re=!!i,He=b==="metric"?me:Oe,Ke=(Hf=m==null?void 0:m.apiServiceUrl)==null?void 0:Hf.replace(/\/$/,""),tt=Ke?`${Ke}/v1/validate`:"/v1/validate",mt=Ke?`${Ke}/v1/ai/generate`:"/v1/ai/generate",gt=w.useMemo(()=>{var Mt;const Ee=[...n];return(((Mt=r==null?void 0:r.calculatedFormula)==null?void 0:Mt.inputFields)||[]).forEach(wn=>{Ee.some(Yn=>Yn.id===wn.id||Yn.qualifiedFieldName===wn.qualifiedFieldName||Yn.name===wn.name)||Ee.push(wn)}),Ee},[n,r]),dt=H==="A"?S:k,Ht=b==="metric"&&C!=="custom"?dt==null?void 0:dt.aggregate:void 0,{allFields:Ge,groups:Nt}=XJe({fields:gt,mode:b,searchTerm:Y,excludeFieldIds:r?[r.id]:void 0,selectedAggregate:Ht,showIncompatible:!0}),ce=Ge,{clientResult:Ae,validationResult:Te,validateExpression:Ie,isValidating:Ue,serverError:ke,resetValidation:ye}=ret({expression:T,availableFields:ce,excludeFieldIds:r?[r.id]:void 0,validationEndpoint:tt,connectionId:p==null?void 0:p.id,dialect:p==null?void 0:p.dialect}),ne=(Te==null?void 0:Te.inferredDataType)||Ae.inferredDataType,Ce=F||ne||"string",Fe=px.find(Ee=>Ee.id===C),Qe=w.useMemo(()=>{if(!y.trim())return!1;const Ee=fl(y),lt=s==="domain"&&(r!=null&&r.name)?fl(r.name):null;return(b==="metric"?xe:de).some(wn=>{const Jt=fl(wn.name);return lt&&Jt===lt?!1:Jt===Ee})},[de,xe,r,s,b,y]),Ot=w.useMemo(()=>{if(b==="metric"&&C==="custom"){const{orderedFields:lt}=ig(T,ce);return lt.filter(Mt=>!!Mt).map(Mt=>Mt.id)}const Ee=[];return S!=null&&S.field.id&&Ee.push(S.field.id),k!=null&&k.field.id&&Ee.push(k.field.id),Ee},[ce,T,b,S,k,C]),Xt=Ee=>{ge||(x(Ee),Ee==="dimension"&&$==="domain"&&!Oe&&q("card"),Ee==="metric"&&$==="domain"&&!me&&q("card"))},Dn=Ee=>{ge||(N(Ee),Ee==="scale"&&_(null),Ee==="custom"&&(j(null),_(null)))},Zr=()=>{v(""),N("ratio"),j(null),_(null),M(1),P(""),A(null),q("card"),z(""),L(""),R({}),U(""),G(!1),Q(null),te(!1),je(!1),ye(),t(!1)},Hr=w.useCallback(Ee=>gt.find(lt=>lt.qualifiedFieldName===Ee.qualifiedFieldName||lt.name===Ee.name)||Ee,[gt]),Hs=w.useCallback(Ee=>{if(!Ee.calculatedFormula)return;const lt=Ee.calculatedFormula;if(N(lt.operation),P(""),lt.operation==="scale"){const Jt=lt.inputFields[0];Jt&&j(ih(Hr(Jt),Jt.aggregate||"SUM")),M(lt.constant===void 0?1:lt.constant);return}if(lt.operation==="custom"){P(Ei(Ee.expression||"",lt.inputFields||[])),j(null),_(null);return}const[Mt,wn]=lt.inputFields;Mt&&j(ih(Hr(Mt),Mt.aggregate||"SUM")),wn&&_(ih(Hr(wn),wn.aggregate||"SUM"))},[Hr]),Ei=w.useCallback((Ee,lt)=>Ee.replace(/\{field_(\d+)\}/g,(Mt,wn)=>{var Nr;const Jt=lt[Number(wn)];return Jt?`{${((Nr=ce.find(_i=>_i.id===Jt.id))==null?void 0:Nr.tokenLabel)||Jt.label||Jt.name}}`:Mt}),[ce]);w.useEffect(()=>{var Mt;if(!e){Me.current=!1,le.current=null;return}const Ee=r?`${r.role}-${r.id||r.name}`:"new";if(Me.current&&le.current===Ee)return;if(Me.current=!0,le.current=Ee,R({}),U(""),je(!1),ye(),r){const wn=r.tags||[];if(r.role==="metric"){x("metric"),v(r.label||r.name),q(s||"card"),z(r.description||""),L(wn.join(", ")),Hs(r);return}x("dimension");const Jt=r;v(Jt.label||Jt.name),q(s||"card"),P(Ei(Jt.expression||"",((Mt=Jt.calculatedFormula)==null?void 0:Mt.inputFields)||[]));const Yn=sz.some(Nr=>Nr.value===Jt.dataType)?Jt.dataType:"string";A(Yn),z(Jt.description||""),L(wn.join(", "));return}const lt=h&&h.length>0?h.includes(f)?f:h[0]:f;x(lt),v(""),N("ratio"),j(null),_(null),M(1),P(""),A(null),q("card"),z(""),L("")},[e,r,s,f,h,Hs,Ei,ye]);const Ou=Ee=>{const lt=`{${Ee}}`,Mt=be.current;if(!Mt){P(Nr=>Nr+lt);return}const wn=Mt.selectionStart||0,Jt=Mt.selectionEnd||0,Yn=`${T.slice(0,wn)}${lt}${T.slice(Jt)}`;P(Yn),requestAnimationFrame(()=>{Mt.focus();const Nr=wn+lt.length;Mt.setSelectionRange(Nr,Nr)})},yN=Ee=>{if(ge)return;if(b==="dimension"||C==="custom"){Ou(Ee.tokenLabel||Ee.label||Ee.name);return}const lt=mk(Ee,H==="A"?(S==null?void 0:S.aggregate)||hh(Ee):(k==null?void 0:k.aggregate)||hh(Ee)),Mt=ih(Ee,lt);if(H==="A"){j(Mt),k||V("B");return}_(Mt),S||V("A")},Uy=(Ee,lt)=>{if(!ge){if(Ee==="A"&&S){j({...S,aggregate:lt});return}Ee==="B"&&k&&_({...k,aggregate:lt})}},fc=async()=>{const Ee={};if(y.trim()||(Ee.name="Name is required"),C==="custom")T.trim()||(Ee.expression="Expression is required"),U1(T).length===0&&(Ee.expression=Ee.expression||"Expression must include field tokens"),ig(T,ce).unresolvedTokens.length>0&&(Ee.expression=Ee.expression||"Expression contains unknown or ambiguous tokens"),Ee.expression||(await Ie()).isValid||(Ee.expression="Fix validation errors before saving");else if(C==="scale")S||(Ee.inputA="Please select a metric for input A"),Number.isNaN(E)&&(Ee.constant="Please enter a valid multiplication factor");else{if(S||(Ee.inputA="Please select a metric for input A"),k||(Ee.inputB="Please select a metric for input B"),S&&k){const lt=S.field.id===k.field.id,Mt=S.aggregate===k.aggregate;lt&&Mt&&(Ee.inputs="Inputs A and B must be different metrics")}if(r&&r.role==="metric"){const lt=jl(r.id);(jl(S==null?void 0:S.field.id)===lt||jl(k==null?void 0:k.field.id)===lt)&&(Ee.inputs="Cannot reference the field being edited")}}return Pe&&($==="domain"&&!me&&(Ee.scope="You do not have permission to save to domain"),$==="domain"&&!W.trim()&&(Ee.description="Description is required for domain fields"),$==="domain"&&Qe&&(Ee.name="A domain field with this name already exists")),R(Ee),Object.keys(Ee).length===0},vN=async()=>{const Ee={};return y.trim()||(Ee.name="Name is required"),T.trim()||(Ee.expression="Expression is required"),U1(T).length===0&&(Ee.expression=Ee.expression||"Expression must include field tokens"),ig(T,ce).unresolvedTokens.length>0&&(Ee.expression=Ee.expression||"Expression contains unknown or ambiguous tokens"),Ee.expression||(await Ie()).isValid||(Ee.expression="Fix validation errors before saving"),Pe&&($==="domain"&&!Oe&&(Ee.scope="You do not have permission to save to domain"),$==="domain"&&!W.trim()&&(Ee.description="Description is required for domain fields"),$==="domain"&&Qe&&(Ee.name="A domain field with this name already exists")),R(Ee),Object.keys(Ee).length===0},wN=()=>{const{orderedTokens:Ee,orderedFields:lt}=ig(T,ce),Mt=lt.filter(Yn=>!!Yn),wn=rz(T,Ee),Jt=_Je(y,wn,Mt,Ce,u,r==null?void 0:r.id);return r&&r.role==="groupby"?{...r,...Jt}:Jt},CN=()=>{var wn;if(C==="custom"){const{orderedTokens:Jt,orderedFields:Yn}=ig(T,ce),Nr=Yn.filter($t=>!!$t),_i=(r==null?void 0:r.role)==="metric"?((wn=r.calculatedFormula)==null?void 0:wn.inputFields)||[]:[],jo=new Map;_i.forEach($t=>{const dr=jl($t.id);dr&&jo.set(dr,$t),$t.qualifiedFieldName&&jo.set($t.qualifiedFieldName,$t),$t.name&&jo.set($t.name,$t)});const hc=Nr.map($t=>{const dr=jl($t.id),Ti=dr&&jo.get(dr)||$t.qualifiedFieldName&&jo.get($t.qualifiedFieldName)||jo.get($t.name),jN=((Ti==null?void 0:Ti.role)==="metric"?Ti.aggregate:void 0)||($t.role==="metric"?$t.aggregate:void 0)||hh($t);return pk($t,jN)}),er=rz(T,Jt),sn=J6(y,C,null,null,{},u,r==null?void 0:r.id,er,void 0,hc);return r&&r.role==="metric"?{...r,...sn}:sn}const Ee=S?pk(S.field,S.aggregate):null,lt=k?pk(k.field,k.aggregate):null,Mt=J6(y,C,Ee,lt,{},u,r==null?void 0:r.id,void 0,C==="scale"?E:void 0);return r&&r.role==="metric"?{...r,...Mt}:Mt},Wy=async Ee=>{var Mt,wn,Jt;if(b==="dimension"){const Yn=wN();if(Ee==="dashboard"){if(!i){R(Nr=>({...Nr,scope:"Dashboard scope is not available"}));return}i(Yn),Zr();return}if(Ee==="domain"){if(!l){R(sn=>({...sn,scope:"Domain scope is not available"}));return}const Nr=((Mt=Yn.calculatedFormula)==null?void 0:Mt.inputFields)||[],_i=new Map,jo=Nr.map(sn=>{const $t=fl(sn.label||sn.name),dr=_i.get($t)||0;return _i.set($t,dr+1),dr===0?$t:`${$t}_${dr+1}`}),hc=((wn=Yn.expression)==null?void 0:wn.replace(/\{field_(\d+)\}/g,(sn,$t)=>`{${jo[Number($t)]||$t}}`))||"",er=jo.reduce((sn,$t,dr)=>{const Ti=Nr[dr];return Qx(Ti)?sn[$t]={dimension:Ti.name}:sn[$t]={dataset:Ti.entityName,field:Ti.name},sn},{});try{await l({name:fl(y),label:y.trim(),description:W.trim(),expression:hc,inputs:er,dataType:Ce,tags:I.split(",").map(sn=>sn.trim()).filter(Boolean),overwrite:s==="domain",previousName:s==="domain"?r==null?void 0:r.name:void 0})}catch(sn){R($t=>({...$t,scope:(sn==null?void 0:sn.message)||"Failed to save to domain"}));return}Zr();return}o(Yn),Zr();return}const lt=CN();if(Ee==="dashboard"){if(!i){R(Yn=>({...Yn,scope:"Dashboard scope is not available"}));return}i(lt),Zr();return}if(Ee==="domain"){if(!a){R(er=>({...er,scope:"Domain scope is not available"}));return}if(!lt.calculatedFormula){R(er=>({...er,scope:"Calculated formula missing"}));return}const Yn=lt.calculatedFormula.inputFields,Nr=new Map,_i=Yn.map(er=>{const sn=fl(er.label||er.name),$t=Nr.get(sn)||0;return Nr.set(sn,$t+1),$t===0?sn:`${sn}_${$t+1}`}),jo=((Jt=lt.expression)==null?void 0:Jt.replace(/\{field_(\d+)\}/g,(er,sn)=>`{${_i[Number(sn)]||sn}}`))||"",hc=_i.reduce((er,sn,$t)=>{const dr=Yn[$t];return dr.role==="metric"?ic(dr)?er[sn]={metric:dr.name}:er[sn]={dataset:dr.entityName,field:dr.name,aggregate:dr.aggregate}:er[sn]={dataset:dr.entityName,field:dr.name},er},{});try{await a({name:fl(y),label:y.trim(),description:W.trim(),expression:jo,inputs:hc,tags:I.split(",").map(er=>er.trim()).filter(Boolean),overwrite:s==="domain",previousName:s==="domain"?r==null?void 0:r.name:void 0})}catch(er){R(sn=>({...sn,scope:(er==null?void 0:er.message)||"Failed to save to domain"}));return}Zr();return}o(lt),Zr()},SN=async()=>{if(ge)return;if(R({}),b==="metric"){if(!await fc())return}else if(!await vN())return;const Ee=Pe?$:s||"card";if(b==="metric"&&Ee!=="domain"&&Qe&&!r){Q(Ee),te(!0);return}ue(!0);try{await Wy(Ee)}finally{ue(!1)}},NN=w.useMemo(()=>{if(!Fe||C==="custom")return"";if(C==="scale"){const Ee=Number.isFinite(E)?E:1;return`${hk(S)} x ${Ee}`}return`${hk(S)||"A"} ${Fe.symbol} ${hk(k)||"B"}`},[Fe,C,S,k,E]);return c.jsxs(c.Fragment,{children:[c.jsxs(Kr,{modal:!1,open:e,onOpenChange:Ee=>{Ee?t(!0):Zr()},children:[e&&c.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),c.jsxs(zr,{className:"max-w-5xl max-h-[90vh] overflow-hidden",onInteractOutside:Ee=>{Ee.preventDefault()},children:[c.jsxs(Br,{children:[c.jsxs(Vr,{children:[r?"Edit":"Create"," Calculated Field"]}),c.jsx(as,{children:"Build calculated metrics and dimensions using expressions."})]}),c.jsxs("div",{className:"grid h-[70vh] min-h-0 grid-cols-[320px_1fr] gap-6",children:[c.jsx(DJe,{groups:Nt,searchTerm:Y,onSearchTermChange:U,onFieldClick:yN,selectedFieldIds:Ot,disabled:ge}),c.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-4 overflow-y-auto pr-2",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{children:"Field Type"}),c.jsx(MJe,{value:b,onChange:Xt,disabled:ge||!!r,options:h||["metric","dimension"]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{htmlFor:"calculated-name",children:"Name"}),c.jsx(pn,{id:"calculated-name",value:y,onChange:Ee=>v(Ee.target.value),placeholder:"e.g., Profit Margin",className:O.name?"border-red-500":"",disabled:ge}),O.name&&c.jsx("p",{className:"text-xs text-red-500",children:O.name})]}),b==="metric"&&c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{children:"Operation"}),c.jsx(IJe,{value:C,onChange:Dn,allowCustom:!0,disabled:ge}),O.operation&&c.jsx("p",{className:"text-xs text-red-500",children:O.operation})]}),C==="custom"?c.jsxs("div",{className:"space-y-4",children:[c.jsx(tz,{ref:be,value:T,onChange:Ee=>{P(Ee),je(!1)},onGenerate:()=>G(!0),showGenerate:!!mt&&!ge,disabled:ge}),c.jsx(nz,{onValidate:async()=>{je(!0),await Ie()},isValidating:Ue,validationResult:Te,fallbackResult:Ae,error:ke,showFallback:he,disabled:ge}),O.expression&&c.jsx("p",{className:"text-xs text-red-500",children:O.expression})]}):c.jsxs("div",{className:"space-y-3",children:[c.jsx(fe,{children:"Inputs"}),c.jsx(ez,{label:"A",input:S,availableFields:ce,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:Ee=>{const lt=mk(Ee,(S==null?void 0:S.aggregate)||hh(Ee));j(ih(Ee,lt))},onAggregateChange:Ee=>Uy("A",Ee),onRemove:()=>j(null),onActivate:()=>V("A"),allowMedian:g,disabled:ge}),O.inputA&&c.jsx("p",{className:"text-xs text-red-500",children:O.inputA}),C!=="scale"&&c.jsxs(c.Fragment,{children:[c.jsx(ez,{label:"B",input:k,availableFields:ce,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:Ee=>{const lt=mk(Ee,(k==null?void 0:k.aggregate)||hh(Ee));_(ih(Ee,lt))},onAggregateChange:Ee=>Uy("B",Ee),onRemove:()=>_(null),onActivate:()=>V("B"),allowMedian:g,disabled:ge}),O.inputB&&c.jsx("p",{className:"text-xs text-red-500",children:O.inputB})]}),C==="scale"&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{htmlFor:"constantFactor",children:"Multiplication Factor"}),c.jsx(pn,{id:"constantFactor",type:"number",step:"any",value:Number.isNaN(E)?"":E,onChange:Ee=>M(Ee.target.value===""?Number.NaN:Number(Ee.target.value)),className:O.constant?"border-red-500":"",placeholder:"e.g., 0.15",disabled:ge}),O.constant&&c.jsx("p",{className:"text-xs text-red-500",children:O.constant})]}),c.jsx("div",{className:"rounded-md border border-border bg-muted/40 p-3 text-sm font-mono",children:NN||"Select inputs to preview formula"}),O.inputs&&c.jsxs(SS,{variant:"destructive",children:[c.jsx(Yl,{className:"h-4 w-4"}),c.jsx(NS,{children:O.inputs})]})]})]}),b==="dimension"&&c.jsxs("div",{className:"space-y-4",children:[c.jsx(tz,{ref:be,value:T,onChange:Ee=>{P(Ee),je(!1)},onGenerate:()=>G(!0),showGenerate:!!mt&&!ge,disabled:ge}),c.jsx(nz,{onValidate:async()=>{je(!0),await Ie()},isValidating:Ue,validationResult:Te,fallbackResult:Ae,error:ke,showFallback:he,disabled:ge}),O.expression&&c.jsx("p",{className:"text-xs text-red-500",children:O.expression}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(fe,{children:"Output Type"}),c.jsxs(it,{value:Ce,onValueChange:Ee=>A(Ee),disabled:ge,children:[c.jsx(rt,{className:"h-9 w-full",children:c.jsx(at,{placeholder:"Select output type"})}),c.jsx(st,{children:sz.map(Ee=>c.jsx(we,{value:Ee.value,children:Ee.label},Ee.value))})]}),ne&&!F&&c.jsxs("p",{className:"text-xs text-muted-foreground",children:["Suggested type: ",ne]})]})]}),Pe&&(Re||He)&&c.jsxs("div",{className:"space-y-3",children:[c.jsx(OJe,{scope:$,onChange:q,showDashboardScope:Re,showDomainScope:He,error:O.scope,disabled:ge}),$==="domain"&&c.jsx($Je,{description:W,tags:I,onDescriptionChange:z,onTagsChange:L,descriptionError:O.description,disabled:ge})]})]})]}),c.jsxs(is,{children:[c.jsx(oe,{variant:"outline",onClick:Zr,children:"Cancel"}),c.jsxs(oe,{onClick:SN,disabled:ie||ge,children:[r?"Update":"Create"," ",b==="metric"?"Metric":"Dimension"]})]})]})]}),c.jsx(zJe,{open:B,onOpenChange:G,availableFields:ce,fieldType:b,onExpressionGenerated:async Ee=>{P(Ee),je(!1),ye()},endpoint:mt,dialect:p==null?void 0:p.dialect}),c.jsx(Zm,{open:K,onOpenChange:te,children:c.jsxs(Sf,{children:[c.jsxs(Nf,{children:[c.jsx(kf,{children:"Name Conflict"}),c.jsxs(Ef,{children:['A domain metric named "',y.trim(),'" already exists. Your local version will override it in this'," ",Z==="dashboard"?"dashboard":"card",". Continue?"]})]}),c.jsxs(jf,{children:[c.jsx(Tf,{onClick:()=>{Q(null)},children:"Choose Different Name"}),c.jsx(_f,{onClick:async()=>{if(Z){te(!1),ue(!0);try{await Wy(Z)}finally{ue(!1),Q(null)}}},children:"Continue"})]})]})})]})}function une({domainId:e}){const{authToken:t,tokenProps:n}=Xe(),[r,s]=w.useState(!1),[o,i]=w.useState(null),a=w.useMemo(()=>{var m;if(!e)return null;const f=(m=n==null?void 0:n.apiServiceUrl)==null?void 0:m.replace(/\/$/,""),h=`/v1/domains/${e}/calculated-metrics`;return f?`${f}${h}`:h},[e,n==null?void 0:n.apiServiceUrl]),l=w.useMemo(()=>{var m;if(!e)return null;const f=(m=n==null?void 0:n.apiServiceUrl)==null?void 0:m.replace(/\/$/,""),h=`/v1/domains/${e}/calculated-dimensions`;return f?`${f}${h}`:h},[e,n==null?void 0:n.apiServiceUrl]),u=w.useCallback(async f=>{if(!a){const h="Domain promotion is not available";throw i(h),new Error(h)}if(!(t!=null&&t.accessToken)){const h="Missing authentication token";throw i(h),new Error(h)}s(!0),i(null);try{return await Yr(a,t.accessToken,f)}catch(h){const m=(h==null?void 0:h.error)||(h==null?void 0:h.message)||"Failed to save to domain";throw i(m),new Error(m)}finally{s(!1)}},[a,t==null?void 0:t.accessToken]),d=w.useCallback(async f=>{if(!l){const h="Domain promotion is not available";throw i(h),new Error(h)}if(!(t!=null&&t.accessToken)){const h="Missing authentication token";throw i(h),new Error(h)}s(!0),i(null);try{return await Yr(l,t.accessToken,f)}catch(h){const m=(h==null?void 0:h.error)||(h==null?void 0:h.message)||"Failed to save to domain";throw i(m),new Error(m)}finally{s(!1)}},[l,t==null?void 0:t.accessToken]);return{promoteMetric:u,promoteDimension:d,isPromoting:r,error:o}}const dne=w.memo(function({context:t="editor",onFieldSelect:n,inlineFilters:r}={}){var Ie,Ue,ke,ye;const[s,o]=w.useState(""),[i,a]=w.useState("all"),[l,u]=w.useState(!1),[d,f]=w.useState(null),[h,m]=w.useState("card"),[p,g]=w.useState("metric");Le(ne=>ne.isDevMode);const b=Le(ne=>ne.card.dataSource),x=Le(ne=>ne.card.config),y=Le(ne=>ne.card),v=Le(ne=>ne.frame),C=Le(ne=>ne.actions.updateCardConfig),N=Le(ne=>ne.actions.updateFrame),{userContext:S}=$s(),{autoJoinMetadata:j}=Wa(y),{columns:k,rawColumnGroups:_,scopedFields:E,dashboardCalculatedFields:M,cardCalculatedFields:T,isLoading:P,error:F,refetch:A}=mP(),$=(b==null?void 0:b.mode)==="semanticDomain"?b.semanticDomainId:void 0,{data:q}=pP($),{promoteMetric:W,promoteDimension:z}=une({domainId:$}),I=w.useMemo(()=>[...(x==null?void 0:x.groupByColumns)||[],...(x==null?void 0:x.metricColumns)||[],...(x==null?void 0:x.detailColumns)||[]],[x==null?void 0:x.groupByColumns,x==null?void 0:x.metricColumns,x==null?void 0:x.detailColumns]);(Ue=(Ie=x==null?void 0:x.joinPlan)==null?void 0:Ie.baseEntity)==null||Ue.name,(ye=(ke=j==null?void 0:j.resolvedJoinPlan)==null?void 0:ke.baseEntity)==null||ye.name,Hte();const L=t==="editor",O=(S==null?void 0:S.type)==="organization",R=L?E:k,H=_,V=s.toLowerCase(),Y=(x==null?void 0:x.metricColumns)||[],U=(x==null?void 0:x.groupByColumns)||[],B=w.useCallback(async ne=>{await W(ne),A()},[W,A]),G=w.useCallback(async ne=>{await z(ne),A()},[z,A]),Z=ne=>ne.name.toLowerCase().includes(V)||ne.dataType.toLowerCase().includes(V)||ne.label&&ne.label.toLowerCase().includes(V)||ne.qualifiedEntityName&&ne.qualifiedEntityName.toLowerCase().includes(V),Q=R.filter(Z),K=ne=>{if(ne.role==="metric"&&ic(ne)||ne.role==="groupby"&&ne.expression)return"calculated";if(ne.dataType==="number"||ne.dataType==="integer"||ne.dataType==="float"||ne.dataType==="decimal"||ne.dataType==="currency")return"metrics";const Ce=vr(ne.dataType);return["date","string","boolean"].includes(Ce)?"dimensions":Ce==="number"?"metrics":"dimensions"},te=ne=>{const Ce=ne.filter(Z);return i==="all"?Ce:Ce.filter(Fe=>K(Fe)===i)},ie=i==="all"?Q:Q.filter(ne=>K(ne)===i),ue=L?[...M,...T]:[],he=L?te(ue):[],be=te(k).reduce((ne,Ce)=>{const Fe=Ce.qualifiedEntityName||"Other Fields";return ne[Fe]||(ne[Fe]={label:pb(Ce.entityName),fields:[]}),ne[Fe].fields.push(Ce),ne},{}),Me=ne=>ne.id||`${ne.entityName}-${ne.qualifiedEntityName}-${ne.name}-${ne.role||"field"}`,le=w.useMemo(()=>{const ne=new Map;return(L?E:k).forEach(Fe=>{ne.set(Me(Fe),QD(Fe,{joinabilityMap:(q==null?void 0:q.joinabilityMap)||null,selectedFields:I,cardConfig:x,autoJoinMetadata:j}))}),ne},[L,E,k,q==null?void 0:q.joinabilityMap,I,x,j]),ae=L?[{key:"scope-calculated",label:"Calculated Fields",fields:he}].filter(ne=>ne.fields.length>0):[],de=[...ae.map(ne=>ne.key),...Object.keys(be)],Se=Q.filter(ne=>K(ne)==="dimensions").length,ge=Q.filter(ne=>K(ne)==="metrics").length,se=Q.filter(ne=>K(ne)==="calculated").length,me=Q.length>0&&t!=="inline-filter",Oe=t==="inline-filter"?"w-full":"w-[290px]";if(P)return c.jsx("div",{className:X("flex h-full flex-col items-center justify-center py-8",Oe),children:c.jsx(tc,{size:"md",color:"muted","aria-label":"Loading data"})});if(F)return c.jsxs("div",{className:X("flex h-full flex-col items-center justify-center py-8",Oe),children:[c.jsx($l,{className:"mb-4 h-12 w-12 text-red-300"}),c.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),c.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:F.message||"Failed to load column data"})]});if(!b||!b.selectedEntities||b.selectedEntities.length===0)return c.jsxs("div",{className:X("flex flex-col items-center justify-center py-8 text-center",Oe),children:[c.jsx($l,{className:"mb-4 h-12 w-12 text-gray-300"}),c.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),c.jsx("p",{className:"px-4 text-xs text-gray-400",children:t==="filter"||t==="inline-filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]});const Pe=t==="inline-filter"?"px-3 pb-3":"px-6 pb-6",Re=t==="inline-filter"?"overflow-hidden":"",He=ne=>ne!=null&&ne.startsWith("card-source-")?ne.replace("card-source-",""):ne,Ke=(ne,Ce,Fe)=>{const Qe=He(ne.id),Ot=He(Ce.id);return Qe&&Ot&&Qe===Ot?!0:!Qe||!Ot||Fe!=null&&Fe.allowNameFallback?ne.name===Ce.name&&ne.role===Ce.role:!1},tt=(ne,Ce,Fe)=>ne.findIndex(Qe=>Ke(Qe,Ce,Fe)),mt=ne=>{if(!v)return ne;const Ce=v.calculatedFields||[],Fe=tt(Ce,ne),Qe=Fe>=0&&Ce[Fe].id!==ne.id?{...ne,id:Ce[Fe].id}:ne,Ot=Fe>=0?Ce.map((Xt,Dn)=>Dn===Fe?Qe:Xt):[...Ce,Qe];return N({calculatedFields:Ot}),Qe},gt=(ne,Ce,Fe,Qe)=>{var Xt;const Ot=tt(ne,Fe||Ce,Qe);if(Ot>=0){const Dn=(Xt=ne[Ot])==null?void 0:Xt.id,Zr=Dn&&Dn!==Ce.id?{...Ce,id:Dn}:Ce;return ne.map((Hr,Hs)=>Hs===Ot?Zr:Hr)}return[...ne,Ce]},dt=ne=>{if(ne.role==="metric")return Y.find(Ce=>Ke(Ce,ne));if(ne.role==="groupby")return U.find(Ce=>Ke(Ce,ne))},Ht=ne=>{var Ce;return(Ce=v==null?void 0:v.calculatedFields)==null?void 0:Ce.find(Fe=>Ke(Fe,ne))},Ge=ne=>{if(ne.role==="metric"){C(y.id,{metricColumns:Y.filter(Ce=>!Ke(Ce,ne,{allowNameFallback:ne.fieldScope==="dashboard"}))});return}ne.role==="groupby"&&C(y.id,{groupByColumns:U.filter(Ce=>!Ke(Ce,ne,{allowNameFallback:ne.fieldScope==="dashboard"}))})},Nt=ne=>{if(!v)return;const Ce=(v.calculatedFields||[]).filter(Fe=>!Ke(Fe,ne));N({calculatedFields:Ce})},ce=ne=>{if(!O)return;if(ne.fieldScope==="domain"){f(ne),m("domain"),g(ne.role==="metric"?"metric":"dimension"),u(!0);return}if(ne.fieldScope==="dashboard"){const Fe=Ht(ne);if(!Fe)return;f(Fe),m("dashboard"),g(Fe.role==="metric"?"metric":"dimension"),u(!0);return}const Ce=dt(ne);Ce&&(f(Ce),m("card"),g(Ce.role==="metric"?"metric":"dimension"),u(!0))},Ae=ne=>{if(O&&ne.fieldScope!=="domain"){if(ne.fieldScope==="dashboard"){Nt(ne),Ge(ne);return}Ge(ne)}},Te=ne=>{if(!O)return null;const Ce=ne.fieldScope==="domain";return c.jsxs(wf,{children:[c.jsx(Cf,{asChild:!0,children:c.jsx(oe,{variant:"ghost",size:"icon",className:"h-6 w-6","aria-label":"Calculated field actions",children:c.jsx(U8,{className:"h-4 w-4"})})}),c.jsxs(yu,{align:"end",className:"w-40",children:[c.jsx(xo,{onClick:()=>ce(ne),children:"Edit"}),c.jsx(xo,{disabled:Ce,onClick:()=>Ae(ne),children:"Delete"})]})]})};return c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:X("mt-2 flex h-full w-full grow flex-col gap-2",Pe,Re),children:[c.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[R.length>0&&c.jsxs("div",{className:"relative",children:[c.jsx(Zo,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),c.jsx(jn,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:s,onChange:ne=>o(ne.target.value)}),s&&c.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>o(""),type:"button",children:c.jsx(St,{className:"size-3.5"})})]}),me&&c.jsx(Ls,{defaultValue:"all",value:i,onValueChange:ne=>a(ne),className:"mb-4",children:c.jsxs(Cs,{className:"grid h-9 w-full grid-cols-4",children:[c.jsxs(rn,{value:"all",className:"text-xs",children:["All",c.jsx("span",{className:"ml-2 text-xs font-semibold",children:Q.length})]}),c.jsxs(rn,{value:"dimensions",className:"text-xs",children:[c.jsx(iC,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:Se})]}),c.jsxs(rn,{value:"metrics",className:"text-xs",children:[c.jsx(Lm,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:ge})]}),c.jsxs(rn,{value:"calculated",className:"text-xs",children:[c.jsx(iM,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:se})]})]})}),t==="editor"&&i==="calculated"&&O&&c.jsx("div",{className:"flex items-center justify-end gap-2",children:c.jsxs(oe,{size:"sm",variant:"outline",className:"w-full",onClick:()=>{f(null),m("card"),g("dimension"),u(!0)},children:[c.jsx(Mr,{className:"mr-2 h-3.5 w-3.5"}),"Add calculated field"]})})]}),c.jsxs(nl,{className:"min-h-0 flex-1",children:[c.jsxs(vP,{type:"multiple",defaultValue:de,className:"space-y-2",children:[ae.map(ne=>c.jsxs(fx,{value:ne.key,className:"border-none",children:[c.jsx(hx,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:ne.label}),c.jsx(qe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:ne.fields.length})]})}),c.jsx(mx,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:ne.fields.map(Ce=>{const Fe=le.get(Me(Ce)),Qe=t==="editor"&&i==="calculated";return c.jsx(Q6,{field:Ce,context:t,fieldState:Fe,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0,actions:Qe?Te(Ce):void 0},Ce.id)})})})]},ne.key)),Object.entries(be).map(([ne,Ce])=>{const Fe=H.find(Ot=>Ot.entityName===ne)||{entityName:ne,label:Ce.label},Qe=ne===rm?"Domain Calculated Fields":Fe.label||Fe.entityName;return c.jsxs(fx,{value:ne,className:"border-none",children:[c.jsx(hx,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{title:Qe,className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:Qe}),c.jsx(qe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:Ce.fields.length})]})}),c.jsx(mx,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:Ce.fields.map(Ot=>{const Xt=le.get(Me(Ot));return c.jsx(Q6,{field:Ot,context:t,fieldState:Xt,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0},Ot.id)})})})]},ne)})]}),R.length===0&&c.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[c.jsx("p",{children:"No fields found for selected data source"}),c.jsx("p",{className:"mt-1 text-xs text-gray-400",children:t==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),R.length>0&&ie.length===0&&c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),c.jsx(yi,{orientation:"horizontal"}),c.jsx(yi,{orientation:"vertical"})]})]}),c.jsx(cne,{open:l,onOpenChange:ne=>{u(ne),ne||(f(null),m("card"))},availableFields:E,existingField:d??void 0,existingFieldScope:h,initialFieldType:p,onSave:ne=>{if(ne.role==="metric"){if(d&&h==="card"){C(y.id,{metricColumns:gt(Y,ne,d)});return}C(y.id,{metricColumns:gt(Y,ne)});return}if(d&&h==="card"){C(y.id,{groupByColumns:gt(U,ne,d)});return}C(y.id,{groupByColumns:gt(U,ne)})},onSaveToDashboard:ne=>{const Ce=!!(d&&h==="dashboard"),Fe=Ce?d:void 0;if(ne.role==="metric"){const Ot=mt(ne);C(y.id,{metricColumns:gt(Y,Ot,Fe,{allowNameFallback:Ce})});return}const Qe=mt(ne);C(y.id,{groupByColumns:gt(U,Qe,Fe,{allowNameFallback:Ce})})},cardId:y.id,onPromoteMetricToDomain:$?B:void 0,onPromoteDimensionToDomain:$?G:void 0,domainId:$})]})}),fne=w.memo(function({context:t="editor"}={}){return c.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",c.jsx(dne,{context:t})," "]})});function hne(){const e=Le(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=Cr();w.useEffect(()=>{var m;if(!e)return;const{tableName:i,schemaName:a,databaseName:l,connectionId:u}=gP(e),d=(m=e.selectedEntities)==null?void 0:m[0],h=(d==null?void 0:d.type)==="model"&&"id"in d?d.id:"";t(u||""),n(l||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function set(){hne();const e=J(l=>l.selectedSheetId),t=J(l=>l.selectedFrameId),n=J(l=>l.dashboard),r=J(l=>l.actions.getSelectedFrame),{setSelectedFrameId:s}=Bt(),{setCard:o}=Cr(),i=Le(l=>l.card.dataSource);return w.useEffect(()=>{var u,d;let l=r();if(!l){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(m=>m.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),l=h)}if(l){const f=l.cards.find(h=>h.id===l.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function oet(){const e=J(o=>o.dashboard.filterLayout),{setFilterLayout:t}=Bt(),n=(e==null?void 0:e.displayMode)||"canvas",r=(e==null?void 0:e.toolbarWrap)??!1,s=(e==null?void 0:e.showDownloadButton)??!1;return c.jsxs(gs,{children:[c.jsx(bs,{asChild:!0,children:c.jsx(oe,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0","aria-label":"Filter display settings",children:c.jsx(Ll,{className:"h-4 w-4"})})}),c.jsx(xs,{className:"w-[280px]",align:"end",children:c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{children:[c.jsx("h4",{className:"mb-3 text-sm font-medium",children:"Filter Display"}),c.jsxs(so,{value:n,onValueChange:o=>t({displayMode:o}),className:"space-y-2",children:[c.jsxs("div",{className:"flex items-start space-x-3",children:[c.jsx(xn,{value:"canvas",id:"canvas",className:"mt-0.5"}),c.jsxs("div",{className:"grid gap-0.5",children:[c.jsx(fe,{htmlFor:"canvas",className:"cursor-pointer font-normal",children:"Canvas Cards"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Filters as draggable, resizable cards on the dashboard"})]})]}),c.jsxs("div",{className:"flex items-start space-x-3",children:[c.jsx(xn,{value:"toolbar",id:"toolbar",className:"mt-0.5"}),c.jsxs("div",{className:"grid gap-0.5",children:[c.jsx(fe,{htmlFor:"toolbar",className:"cursor-pointer font-normal",children:"Toolbar"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Compact horizontal toolbar below dashboard controls"})]})]})]})]}),n==="toolbar"&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-center space-x-2 border-t pt-4",children:[c.jsx(un,{id:"wrap",checked:r,onCheckedChange:o=>t({toolbarWrap:o===!0})}),c.jsx(fe,{htmlFor:"wrap",className:"cursor-pointer text-sm font-normal",children:"Wrap filters to multiple lines"})]}),c.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[c.jsx(un,{id:"download",checked:s,onCheckedChange:o=>t({showDownloadButton:o===!0})}),c.jsx(fe,{htmlFor:"download",className:"cursor-pointer text-sm font-normal",children:"Show download button"})]})]}),c.jsx("p",{className:"border-t pt-3 text-xs text-muted-foreground",children:"Individual filters can override this setting in their configuration."})]})})]})}function iet(){const e=J(n=>n.actions.setShowFilters),{hasEntities:t}=set();return c.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col overflow-hidden border-l",children:[c.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[c.jsx(fe,{className:"px-2 text-base",children:"Dashboard Filters"}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(oet,{}),c.jsx(oe,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:c.jsx(WX,{})})]})]}),!t&&c.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[c.jsx($l,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),c.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&c.jsx("div",{className:"flex grow overflow-y-auto",children:c.jsx(Ry,{collisionDetection:My,children:c.jsx(Ay,{items:[],strategy:NA,children:c.jsx(fne,{context:"filter"})})})})]})}function aet(){const e=J(r=>r.dashboard.filters),t=J(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?c.jsx("div",{className:X("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>c.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[c.jsx(bA,{filter:r}),c.jsx(Ep,{filter:r})]},r.id))}):null}function cet(){const e=J(r=>r.showFilters),t=J(r=>r.isVisualEditing),n=J(r=>r.isDashboardEditing);return c.jsxs("div",{role:"dashboard-plus-main",className:X("",{"max-h-0 overflow-hidden":t,"flex grow overflow-hidden":!t}),children:[c.jsxs("section",{className:"flex grow flex-col overflow-y-auto",children:[n&&c.jsx(aet,{}),c.jsx(Fte,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:c.jsx(iet,{})})]})}const uet=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-dHxXj3lu.js"))),det=w.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-4m9e0fE3.js"))),fet=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-D_ssqHMn.js"))),het=w.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-Bcm1QBik.js")).then(e=>({default:e.ResourceManagementPanel})));function met({showControls:e=!1,showFooter:t=!0,...n}){const r=J(l=>l.isDashboardPanelOpen),s=J(l=>l.isVisualEditing),o=J(l=>l.showDashboardJSON),i=J(l=>l.actions.setIsDashboardPanelOpen),{preferences:a}=n;return c.jsx(sa,{FallbackComponent:FS,children:c.jsxs(oM,{dashboardProps:n,children:[c.jsx(Gde,{}),c.jsx(hP,{componentType:"surfboard",componentId:n.id}),c.jsx(fP,{children:c.jsxs(Ote,{preferences:a,children:[o&&c.jsx(w.Suspense,{fallback:null,children:c.jsx(fet,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&c.jsx(w.Suspense,{fallback:null,children:c.jsx(uet,{})}),c.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&c.jsx(w.Suspense,{fallback:null,children:c.jsx(het,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),c.jsx("div",{className:"flex min-w-0 flex-1",children:c.jsxs(NI,{...n,type:"dashboard",children:[s&&c.jsx(w.Suspense,{fallback:null,children:c.jsx(det,{})}),c.jsx(cet,{})]})})]})]})]})})]})})}const mne=D.forwardRef(({className:e,...t},n)=>c.jsx(Fy,{className:X("peer inline-flex h-[22px] w-[36px] shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:n,children:c.jsx(kA,{className:X("pointer-events-none block size-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));mne.displayName=Fy.displayName;var pet=Object.defineProperty,get=(e,t,n)=>t in e?pet(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,wv=(e,t,n)=>get(e,typeof t!="symbol"?t+"":t,n);const bet={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},xet={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{if(typeof window<"u"&&e in window)return window[e];if(typeof global<"u"&&e in global)return global[e]})();return typeof r=="function"?r.bind(n):void 0}},yet={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function vet(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function pne(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const wet={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=pne(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},Cet={stringify:e=>`${e}`,parse:e=>parseFloat(e)},Net={stringify:e=>e,parse:e=>e},gk={string:Net,number:Cet,boolean:bet,function:xet,method:wet,json:yet},ag=Symbol.for("r2wc.render"),Cv=Symbol.for("r2wc.connected"),Ku=Symbol.for("r2wc.context"),To=Symbol.for("r2wc.props");function jet(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),l={},u={},d={},f={};for(const m of i){l[m]=Array.isArray(t.props)?"string":t.props[m];const p=vet(m);d[m]=p,f[p]=m}for(const m of a)u[m]=Array.isArray(t.events)?{}:t.events[m];class h extends HTMLElement{constructor(){super(),wv(this,o,!0),wv(this,s),wv(this,r,{}),wv(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[To].container=this.container;for(const p of i){const g=d[p],b=this.getAttribute(g),x=l[p],y=x?gk[x]:null;if(x==="method"){const v=pne(g);Object.defineProperty(this[To].container,v,{enumerable:!0,configurable:!0,get(){return this[To][v]},set(C){this[To][v]=C,this[ag]()}}),this[To][p]=y.parse(b,g,this)}y!=null&&y.parse&&b&&(this[To][p]=y.parse(b,g,this))}for(const p of a)this[To][p]=g=>{const b=p.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[p]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[Cv]=!0,this[ag]()}disconnectedCallback(){this[Cv]=!1,this[Ku]&&n.unmount(this[Ku]),delete this[Ku]}attributeChangedCallback(p,g,b){const x=f[p],y=l[x],v=y?gk[y]:null;x in l&&v!=null&&v.parse&&b&&(this[To][x]=v.parse(b,p,this),this[ag]())}[(o=Cv,s=Ku,r=To,ag)](){this[Cv]&&(this[Ku]?n.update(this[Ku],this[To]):this[Ku]=n.mount(this.container,e,this[To]))}}for(const m of i){const p=d[m],g=l[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[To][m]},set(b){this[To][m]=b;const x=g?gk[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,p,this);this.getAttribute(p)!==y&&this.setAttribute(p,y)}else this[ag]()}})}return h}function ket(e,t,n){const r=fre.createRoot(e),s=w.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function Eet({root:e,ReactComponent:t},n){const r=w.createElement(t,n);e.render(r)}function _et({root:e}){e.unmount()}function Tet(e,t={}){return jet(e,t,{mount:ket,update:Eet,unmount:_et})}const Met={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",currentTheme:"string",customCards:"json",customStyle:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},Det=Tet($te,{props:Met});function oz(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Iet(e){if(Array.isArray(e))return e}function Ret(e,t,n){return(t=zet(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Aet(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,s,o,i,a=[],l=!0,u=!1;try{if(o=(n=n.call(e)).next,t!==0)for(;!(l=(r=o.call(n)).done)&&(a.push(r.value),a.length!==t);l=!0);}catch(d){u=!0,s=d}finally{try{if(!l&&n.return!=null&&(i=n.return(),Object(i)!==i))return}finally{if(u)throw s}}return a}}function Pet(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1078
1078
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function iz(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function az(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?iz(Object(n),!0).forEach(function(r){Ret(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):iz(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function Fet(e,t){if(e==null)return{};var n,r,s=Oet(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function Oet(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function $et(e,t){return Iet(e)||Aet(e,t)||Bet(e,t)||Pet()}function Let(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function zet(e){var t=Let(e,"string");return typeof t=="symbol"?t:t+""}function Bet(e,t){if(e){if(typeof e=="string")return oz(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?oz(e,t):void 0}}function Vet(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function lz(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function cz(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?lz(Object(n),!0).forEach(function(r){Vet(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):lz(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function Het(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(r){return t.reduceRight(function(s,o){return o(s)},r)}}function Pg(e){return function t(){for(var n=this,r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return s.length>=e.length?e.apply(this,s):function(){for(var i=arguments.length,a=new Array(i),l=0;l<i;l++)a[l]=arguments[l];return t.apply(n,[].concat(s,a))}}}function W1(e){return{}.toString.call(e).includes("Object")}function Uet(e){return!Object.keys(e).length}function gx(e){return typeof e=="function"}function Wet(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function qet(e,t){return W1(t)||nu("changeType"),Object.keys(t).some(function(n){return!Wet(e,n)})&&nu("changeField"),t}function Yet(e){gx(e)||nu("selectorType")}function Get(e){gx(e)||W1(e)||nu("handlerType"),W1(e)&&Object.values(e).some(function(t){return!gx(t)})&&nu("handlersType")}function Ket(e){e||nu("initialIsRequired"),W1(e)||nu("initialType"),Uet(e)&&nu("initialContent")}function Zet(e,t){throw new Error(e[t]||e.default)}var Xet={initialIsRequired:"initial state is required",initialType:"initial state should be an object",initialContent:"initial state shouldn't be an empty object",handlerType:"handler should be an object or a function",handlersType:"all handlers should be a functions",selectorType:"selector should be a function",changeType:"provided value of changes should be an object",changeField:'it seams you want to change a field in the state which is not specified in the "initial" state',default:"an unknown error accured in `state-local` package"},nu=Pg(Zet)(Xet),Sv={changes:qet,selector:Yet,handler:Get,initial:Ket};function Qet(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Sv.initial(e),Sv.handler(t);var n={current:e},r=Pg(ttt)(n,t),s=Pg(ett)(n),o=Pg(Sv.changes)(e),i=Pg(Jet)(n);function a(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(d){return d};return Sv.selector(u),u(n.current)}function l(u){Het(r,s,o,i)(u)}return[a,l]}function Jet(e,t){return gx(t)?t(e.current):t}function ett(e,t){return e.current=cz(cz({},e.current),t),t}function ttt(e,t,n){return gx(t)?t(e.current):Object.keys(n).forEach(function(r){var s;return(s=t[r])===null||s===void 0?void 0:s.call(t,e.current[r])}),n}var ntt={create:Qet},rtt={paths:{vs:"https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs"}};function stt(e){return function t(){for(var n=this,r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return s.length>=e.length?e.apply(this,s):function(){for(var i=arguments.length,a=new Array(i),l=0;l<i;l++)a[l]=arguments[l];return t.apply(n,[].concat(s,a))}}}function ott(e){return{}.toString.call(e).includes("Object")}function itt(e){return e||uz("configIsRequired"),ott(e)||uz("configType"),e.urls?(att(),{paths:{vs:e.urls.monacoBase}}):e}function att(){console.warn(gne.deprecation)}function ltt(e,t){throw new Error(e[t]||e.default)}var gne={configIsRequired:"the configuration object is required",configType:"the configuration object should be an object",default:"an unknown error accured in `@monaco-editor/loader` package",deprecation:`Deprecation warning!
1079
1079
  You are using deprecated way of configuration.
1080
1080