react-semaphor 0.1.287 → 0.1.288
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.
- package/dist/chunks/{dashboard-controls-B8xnCPTZ.js → dashboard-controls-BiW05-mC.js} +4 -4
- package/dist/chunks/{dashboard-controls-C25JMBLV.js → dashboard-controls-Zmrx1YI2.js} +1 -1
- package/dist/chunks/{dashboard-filter-controls-button-D-o6ofi2.js → dashboard-filter-controls-button-7f-bvHT_.js} +3 -3
- package/dist/chunks/{dashboard-filter-controls-button-BOJUiKGk.js → dashboard-filter-controls-button-BRd93sFp.js} +1 -1
- package/dist/chunks/{dashboard-json-DFuRB4cG.js → dashboard-json-B98ND-fr.js} +1 -1
- package/dist/chunks/{dashboard-json-BYCWtm_z.js → dashboard-json-Co1UgUNw.js} +1 -1
- package/dist/chunks/{dashboard-summary-settings-dialog-CFTJNcmp.js → dashboard-summary-settings-dialog-CcNH2IIt.js} +1 -1
- package/dist/chunks/{dashboard-summary-settings-dialog-CsnHeIhi.js → dashboard-summary-settings-dialog-XvwdRn2n.js} +1 -1
- package/dist/chunks/edit-dashboard-visual-DBvH4PxE.js +193 -0
- package/dist/chunks/{edit-dashboard-visual-YmESbDUP.js → edit-dashboard-visual-DcTqSs2k.js} +4316 -4253
- package/dist/chunks/{index-BDE8cMG8.js → index-COoAiuFD.js} +1 -1
- package/dist/chunks/{index-Bz0-3JKw.js → index-J8IvoGB3.js} +4 -4
- package/dist/chunks/{resource-management-panel-Lxjcn4i0.js → resource-management-panel-B1q16xjI.js} +2 -2
- package/dist/chunks/{resource-management-panel-C6qnO0ID.js → resource-management-panel-C37Ddk0o.js} +1 -1
- package/dist/chunks/{use-create-flow-overlay-state-AXNDXDqV.js → use-create-flow-overlay-state-DkquwAuI.js} +1 -1
- package/dist/chunks/{use-create-flow-overlay-state-CJiyn4FY.js → use-create-flow-overlay-state-sPNLNhJR.js} +2 -2
- package/dist/chunks/use-visual-utils-CzoNgtEf.js +334 -0
- package/dist/chunks/use-visual-utils-DMRRNJY1.js +1 -0
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +5 -5
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +2 -2
- package/package.json +1 -1
- package/dist/chunks/edit-dashboard-visual-DU3NzdD5.js +0 -193
- package/dist/chunks/use-visual-utils-BygqTxyR.js +0 -1
- package/dist/chunks/use-visual-utils-CWVz-eYg.js +0 -353
|
@@ -1390,7 +1390,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
1390
1390
|
`)},flush(e){e.enqueue(`data: [DONE]
|
|
1391
1391
|
|
|
1392
1392
|
`)}})}});var Zut=Uct(()=>lle(Zi([jr({type:sn("text-start"),id:kt(),providerMetadata:Gr.optional()}),jr({type:sn("text-delta"),id:kt(),delta:kt(),providerMetadata:Gr.optional()}),jr({type:sn("text-end"),id:kt(),providerMetadata:Gr.optional()}),jr({type:sn("error"),errorText:kt()}),jr({type:sn("tool-input-start"),toolCallId:kt(),toolName:kt(),providerExecuted:Wo().optional(),dynamic:Wo().optional()}),jr({type:sn("tool-input-delta"),toolCallId:kt(),inputTextDelta:kt()}),jr({type:sn("tool-input-available"),toolCallId:kt(),toolName:kt(),input:nl(),providerExecuted:Wo().optional(),providerMetadata:Gr.optional(),dynamic:Wo().optional()}),jr({type:sn("tool-input-error"),toolCallId:kt(),toolName:kt(),input:nl(),providerExecuted:Wo().optional(),providerMetadata:Gr.optional(),dynamic:Wo().optional(),errorText:kt()}),jr({type:sn("tool-output-available"),toolCallId:kt(),output:nl(),providerExecuted:Wo().optional(),dynamic:Wo().optional(),preliminary:Wo().optional()}),jr({type:sn("tool-output-error"),toolCallId:kt(),errorText:kt(),providerExecuted:Wo().optional(),dynamic:Wo().optional()}),jr({type:sn("reasoning-start"),id:kt(),providerMetadata:Gr.optional()}),jr({type:sn("reasoning-delta"),id:kt(),delta:kt(),providerMetadata:Gr.optional()}),jr({type:sn("reasoning-end"),id:kt(),providerMetadata:Gr.optional()}),jr({type:sn("source-url"),sourceId:kt(),url:kt(),title:kt().optional(),providerMetadata:Gr.optional()}),jr({type:sn("source-document"),sourceId:kt(),mediaType:kt(),title:kt(),filename:kt().optional(),providerMetadata:Gr.optional()}),jr({type:sn("file"),url:kt(),mediaType:kt(),providerMetadata:Gr.optional()}),jr({type:rle(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:kt().optional(),data:nl(),transient:Wo().optional()}),jr({type:sn("start-step")}),jr({type:sn("finish-step")}),jr({type:sn("start"),messageId:kt().optional(),messageMetadata:nl().optional()}),jr({type:sn("finish"),finishReason:ele(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:nl().optional()}),jr({type:sn("abort")}),jr({type:sn("message-metadata"),messageMetadata:nl()})])));function Xut(e){return e.type.startsWith("data-")}function gle(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]=gle(o,s):n[r]=s}return n}function Qut(e){const t=["ROOT"];let n=-1,r=null;function s(c,u,d){switch(c){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(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let c=0;c<e.length;c++){const u=e[c];switch(t[t.length-1]){case"ROOT":s(u,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=c,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,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,c);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=c;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=c}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=c,t.pop();break}default:{n=c,s(u,c,"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=c,t.pop();break}default:{n=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=c;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=c;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,c+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,c):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c)):n=c;break}}}let a=e.slice(0,n+1);for(let c=t.length-1;c>=0;c--)switch(t[c]){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 xle(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await VS({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await VS({text:Qut(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function V1(e){return e.type.startsWith("tool-")}function Jut(e){return e.type==="dynamic-tool"}function CM(e){return V1(e)||Jut(e)}function uB(e){return e.type.split("-").slice(1).join("-")}function edt({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 tdt({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,c){await r(async({state:u,write:d})=>{var f,h,m,p;function g(w){const N=u.message.parts.filter(V1).find(j=>j.toolCallId===w);if(N==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return N}function x(w){const N=u.message.parts.filter(j=>j.type==="dynamic-tool").find(j=>j.toolCallId===w);if(N==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return N}function b(w){var S;const N=u.message.parts.find(T=>V1(T)&&T.toolCallId===w.toolCallId),j=w,k=N;N!=null?(N.state=w.state,k.input=j.input,k.output=j.output,k.errorText=j.errorText,k.rawInput=j.rawInput,k.preliminary=j.preliminary,k.providerExecuted=(S=j.providerExecuted)!=null?S:N.providerExecuted,j.providerMetadata!=null&&N.state==="input-available"&&(N.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.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(w){var S,N;const j=u.message.parts.find(E=>E.type==="dynamic-tool"&&E.toolCallId===w.toolCallId),k=w,T=j;j!=null?(j.state=w.state,T.toolName=w.toolName,T.input=k.input,T.output=k.output,T.errorText=k.errorText,T.rawInput=(S=k.rawInput)!=null?S:T.rawInput,T.preliminary=k.preliminary,T.providerExecuted=(N=k.providerExecuted)!=null?N:j.providerExecuted,k.providerMetadata!=null&&j.state==="input-available"&&(j.callProviderMetadata=k.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:w.toolName,toolCallId:w.toolCallId,state:w.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(w){if(w!=null){const S=u.message.metadata!=null?gle(u.message.metadata,w):w;t!=null&&await oB({value:S,schema:t}),u.message.metadata=S}}switch(a.type){case"text-start":{const w={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=w,u.message.parts.push(w),d();break}case"text-delta":{const w=u.activeTextParts[a.id];w.text+=a.delta,w.providerMetadata=(f=a.providerMetadata)!=null?f:w.providerMetadata,d();break}case"text-end":{const w=u.activeTextParts[a.id];w.state="done",w.providerMetadata=(h=a.providerMetadata)!=null?h:w.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const w={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=w,u.message.parts.push(w),d();break}case"reasoning-delta":{const w=u.activeReasoningParts[a.id];w.text+=a.delta,w.providerMetadata=(m=a.providerMetadata)!=null?m:w.providerMetadata,d();break}case"reasoning-end":{const w=u.activeReasoningParts[a.id];w.providerMetadata=(p=a.providerMetadata)!=null?p:w.providerMetadata,w.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 w=u.message.parts.filter(V1);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:w.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}):b({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const w=u.partialToolCalls[a.toolCallId];w.text+=a.inputTextDelta;const{value:S}=await xle(w.text);w.dynamic?y({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:S}):b({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:S}),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}):b({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}):b({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 w=x(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-available",input:w.input,output:a.output,preliminary:a.preliminary})}else{const w=g(a.toolCallId);b({toolCallId:a.toolCallId,toolName:uB(w),state:"output-available",input:w.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const w=x(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-error",input:w.input,errorText:a.errorText,providerExecuted:a.providerExecuted})}else{const w=g(a.toolCallId);b({toolCallId:a.toolCallId,toolName:uB(w),state:"output-error",input:w.input,rawInput:w.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(Xut(a)){(n==null?void 0:n[a.type])!=null&&await oB({value:a.data,schema:n[a.type]});const w=a;if(w.transient){i==null||i(w);break}const S=w.id!=null?u.message.parts.find(N=>w.type===N.type&&w.id===N.id):void 0;S!=null?S.data=w.data:u.message.parts.push(w),i==null||i(w),d()}}c.enqueue(a)})}}))}async function ndt({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()}}Tv({prefix:"aitxt",size:24});Tv({prefix:"aiobj",size:24});var rdt=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()})}};Tv({prefix:"aiobj",size:24});var sdt={};zut(sdt,{object:()=>idt,text:()=>odt});var odt=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),idt=({schema:e})=>{const t=Lut(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await xle(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 VS({text:n});if(!s.success)throw new lB({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 W5({value:s.value,schema:t});if(!o.success)throw new lB({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 adt(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=c=>{var u;o((u=c.target)==null?void 0:u.result)},a.onerror=c=>i(c),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var ldt=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 um(this.body),c=await um(this.headers),u=await um(this.credentials),d={...Xd(c),...Xd(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?Xd(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,b=await((o=this.fetch)!=null?o:globalThis.fetch)(h,{method:"POST",headers:rB({"Content-Type":"application/json",...m},`ai-sdk/${cB}`,nB()),body:JSON.stringify(p),credentials:g,signal:e});if(!b.ok)throw new Error((i=await b.text())!=null?i:"Failed to fetch the chat response.");if(!b.body)throw new Error("The response body is empty.");return this.processResponseStream(b.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await um(this.body),a=await um(this.headers),c=await um(this.credentials),u={...Xd(a),...Xd(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:c,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?Xd(d.headers):u,m=(r=d==null?void 0:d.credentials)!=null?r:c,g=await((s=this.fetch)!=null?s:globalThis.fetch)(f,{method:"GET",headers:rB(h,`ai-sdk/${cB}`,nB()),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)}},G5=class extends ldt{constructor(e={}){super(e)}processResponseStream(e){return qct({stream:e,schema:Zut}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},cdt=class{constructor({generateId:e=Pct,id:t=e(),transport:n=new G5,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:c,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new rdt,this.sendMessage=async(f,h)=>{var m,p,g,x;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(m=this.lastMessage)==null?void 0:m.id,...h});return}let b;if("text"in f||"files"in f?b={parts:[...Array.isArray(f.files)?f.files:await adt(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:b=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,{...b,id:f.messageId,role:(p=b.role)!=null?p:"user",metadata:f.metadata})}else this.state.pushMessage({...b,id:(g=b.id)!=null?g:this.generateId(),role:(x=b.role)!=null?x:"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 x,b;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(w=>CM(w)&&w.toolCallId===m?{...w,state:f,output:p,errorText:g}:w)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(w=>CM(w)&&w.toolCallId===m?{...w,state:f,output:p,errorText:g}:w)),this.status!=="streaming"&&this.status!=="submitted"&&((x=this.sendAutomaticallyWhen)!=null&&x.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(b=this.lastMessage)==null?void 0:b.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=c,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,c;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;let d=!1,f=!1,h=!1;try{const m={state:edt({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 x=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(x==null){this.setStatus({status:"ready"});return}p=x}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=x=>this.jobExecutor.run(()=>x({state:m.state,write:()=>{var b;this.setStatus({status:"streaming"}),m.state.message.id===((b=this.lastMessage)==null?void 0:b.id)?this.state.replaceMessage(this.state.messages.length-1,m.state.message):this.state.pushMessage(m.state.message)}}));await ndt({stream:tdt({stream:p,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:g,onError:x=>{throw x}}),onError:x=>{throw x}}),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:(c=this.lastMessage)==null?void 0:c.id,metadata:t,headers:n,body:r})}};function ble({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(CM).filter(s=>!s.providerExecuted);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function udt(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,c=t-a;c<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},c)}}var ddt=udt;const fdt=md(ddt);var yle=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},dr=(e,t,n)=>(yle(e,t,"read from private field"),n?n.call(e):t.get(e)),Za=(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)},fu=(e,t,n,r)=>(yle(e,t,"write to private field"),t.set(e,n),n);function hdt(e,t){return t!=null?fdt(e,t):e}var Mi,B1,U1,lb,cb,ub,bm,SM,NM,mdt=class{constructor(e=[]){Za(this,Mi,void 0),Za(this,B1,"ready"),Za(this,U1,void 0),Za(this,lb,new Set),Za(this,cb,new Set),Za(this,ub,new Set),this.pushMessage=t=>{fu(this,Mi,dr(this,Mi).concat(t)),dr(this,bm).call(this)},this.popMessage=()=>{fu(this,Mi,dr(this,Mi).slice(0,-1)),dr(this,bm).call(this)},this.replaceMessage=(t,n)=>{fu(this,Mi,[...dr(this,Mi).slice(0,t),this.snapshot(n),...dr(this,Mi).slice(t+1)]),dr(this,bm).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?hdt(t,n):t;return dr(this,lb).add(r),()=>{dr(this,lb).delete(r)}},this["~registerStatusCallback"]=t=>(dr(this,cb).add(t),()=>{dr(this,cb).delete(t)}),this["~registerErrorCallback"]=t=>(dr(this,ub).add(t),()=>{dr(this,ub).delete(t)}),Za(this,bm,()=>{dr(this,lb).forEach(t=>t())}),Za(this,SM,()=>{dr(this,cb).forEach(t=>t())}),Za(this,NM,()=>{dr(this,ub).forEach(t=>t())}),fu(this,Mi,e)}get status(){return dr(this,B1)}set status(e){fu(this,B1,e),dr(this,SM).call(this)}get error(){return dr(this,U1)}set error(e){fu(this,U1,e),dr(this,NM).call(this)}get messages(){return dr(this,Mi)}set messages(e){fu(this,Mi,[...e]),dr(this,bm).call(this)}};Mi=new WeakMap;B1=new WeakMap;U1=new WeakMap;lb=new WeakMap;cb=new WeakMap;ub=new WeakMap;bm=new WeakMap;SM=new WeakMap;NM=new WeakMap;var ym,dB=class extends cdt{constructor({messages:e,...t}){const n=new mdt(e);super({...t,state:n}),Za(this,ym,void 0),this["~registerMessagesCallback"]=(r,s)=>dr(this,ym)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>dr(this,ym)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>dr(this,ym)["~registerErrorCallback"](r),fu(this,ym,n)}};ym=new WeakMap;function vle({experimental_throttle:e,resume:t=!1,...n}={}){const r=C.useRef("chat"in n?n.chat:new dB(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new dB(n));const o="id"in n?n.id:null,i=C.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=C.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),c=C.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=C.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=C.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return C.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:c,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput}}function pdt(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function gdt(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function xdt(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function bdt(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function wle(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:bdt(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function Cle(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 AE(e,t){var n;if((n=e.sheets)!=null&&n.length)return t&&e.sheets.find(r=>r.id===t)||e.sheets[0]}function Sle(e,t,n){const r=AE(e,t);if(!r)return[];const s=o=>{var i;return{sourceCard:o,visibleCard:((i=n==null?void 0:n[o.id])==null?void 0:i.visibleCard)||o,...n!=null&&n[o.id]?{replacedCard:n[o.id]}:{}}};return(r.frames||[]).map(o=>rj(o)).filter(o=>o!==void 0).map(s)}function Nle(e){var n;return(((n=e.dataSource)==null?void 0:n.selectedEntities)||[]).map(r=>({name:r.name,type:r.type,connectionId:r.connectionId,...r.label?{label:r.label}:{}}))}function ydt(e){return{id:(e==null?void 0:e.id)||"",name:(e==null?void 0:e.name)||"",label:(e==null?void 0:e.label)||(e==null?void 0:e.name)||"",...e!=null&&e.dataType?{dataType:e.dataType}:{},...e!=null&&e.aggregate?{aggregate:e.aggregate}:{},...e!=null&&e.granularity?{granularity:e.granularity}:{},...e!=null&&e.direction?{direction:e.direction}:{}}}function Am(e){return(e||[]).map(ydt)}function jle(e){return Am([...(e==null?void 0:e.groupByColumns)||[],...(e==null?void 0:e.pivotByColumns)||[],...(e==null?void 0:e.detailColumns)||[]])}function Y5(e){const t={operation:e.operation};return"value"in e&&e.value!==void 0&&(t.value=e.value),"values"in e&&Array.isArray(e.values)&&(t.values=e.values),t}function vdt(e,t,n){const r=new Map((e||[]).map(s=>[s.id,s]));return(t||[]).map(s=>{const o=r.get(s.filterId);return{filterId:s.filterId,label:(o==null?void 0:o.title)||s.label||s.name||s.filterId,...o!=null&&o.type?{type:o.type}:{},...o!=null&&o.column||s.name?{column:(o==null?void 0:o.column)||s.name}:{},...o!=null&&o.dataType?{dataType:o.dataType}:{},origin:n,...Y5(s)}})}function wdt(e){return(e||[]).map(t=>({filterId:t.filterId,label:t.label||t.name||t.filterId,...t.name?{column:t.name}:{},origin:"inline",...Y5(t)}))}function Ele(e,t){var n,r,s,o,i,a,c;return{filterId:t,label:((n=e.field)==null?void 0:n.label)||((r=e.field)==null?void 0:r.name)||t,...(s=e.field)!=null&&s.qualifiedFieldName||(o=e.field)!=null&&o.name?{column:((i=e.field)==null?void 0:i.qualifiedFieldName)||((a=e.field)==null?void 0:a.name)}:{},...(c=e.field)!=null&&c.dataType?{dataType:e.field.dataType}:{},origin:"interaction",operation:e.operator,...e.value!==void 0?{value:e.value}:{}}}function qT(e,t){return(e||[]).flatMap((n,r)=>(n.filters||[]).map((s,o)=>Ele(s,`${t}:${r}:${o}`)))}function Cdt(e){return!!e&&typeof e=="object"&&"field"in e&&"operator"in e}function Sdt(e){return!!e&&typeof e=="object"&&"filterId"in e&&"operation"in e}function Ndt(e){if(!e)return{dashboardFilterValues:[],interactionFilterValues:[]};const t=e.filter(Sdt).map(r=>({filterId:r.filterId,label:r.label||r.name||r.filterId,...r.name?{column:r.name}:{},origin:"dashboard",...Y5(r)})),n=e.filter(Cdt).map((r,s)=>Ele(r,`replaced-insight:${s}`));return{dashboardFilterValues:t,interactionFilterValues:n}}function jdt({card:e,interactionStates:t,currentDashboardId:n}){var c;if(!t)return[];const r=GM(e.id,t),s=t[pa],i=(s==null?void 0:s.targetDashboardId)===n&&(s==null?void 0:s.contextMode)!=="none"?(s==null?void 0:s.appliedClickFilters)||[]:[],a=((c=t[e.id])==null?void 0:c.breadcrumbs)??[];return[...r.flatMap((u,d)=>qT(u.filterGroups,`interaction:${u.sourceCardId||e.id}:${d}`)),...i.flatMap((u,d)=>qT(u.filterGroups,`global-interaction:${u.sourceCardId||e.id}:${d}`)),...a.flatMap((u,d)=>qT(u.sourceFilterGroups,`breadcrumb:${e.id}:${d}`))]}function kle(e){return e?{logicalOperator:e.logicalOperator,negate:e.negate,conditions:(e.conditions||[]).map(t=>{var n,r;return{field:((n=t.field)==null?void 0:n.label)||((r=t.field)==null?void 0:r.name)||"",operator:t.operator,value:t.value}}),groups:(e.groups||[]).map(t=>kle(t)).filter(Boolean)}:null}function Tle(e){var n;const t=(n=e.python)==null?void 0:n.trim();return!!t&&t!==ZM.trim()}function Edt(e){var t;return(t=e.sql)!=null&&t.trim()?"custom-sql":Tle(e)?"custom-python":"config"}function Ile({sourceCard:e,card:t,replacedCard:n,dashboard:r,viewState:s,runtimeFilterValues:o,interactionStates:i,inlineFilterValuesMap:a}){const c=AE(r,s.selectedSheetId),u=(c==null?void 0:c.id)||s.selectedSheetId,{finalConfig:d}=_0({card:t,interactionStates:i,currentDashboardId:r.id,filters:r.filters,filterValues:o??s.activeFilters,selectedSheetId:u,inlineFilterValuesMap:a}),f=I0({card:e||t,interactionStates:i,currentDashboardId:r.id,filters:r.filters,filterValues:o??s.activeFilters,selectedSheetId:u}),h=Ndt(n==null?void 0:n.filters),m=!!n&&n.filters!==void 0;return{selectedSheetId:u,finalConfig:d,dashboardFilterValues:m?h.dashboardFilterValues:vdt(f.cardFilters,f.cardFilterValues,"dashboard"),inlineFilterValues:wdt(a==null?void 0:a[t.id]),interactionFilterValues:m?h.interactionFilterValues:jdt({card:t,interactionStates:i,currentDashboardId:r.id})}}function kdt({sourceCard:e,visibleCard:t,dashboard:n,viewState:r,interactionStates:s,inlineFilterValuesMap:o,replacedCard:i,renderOrder:a}){const{finalConfig:c}=Ile({sourceCard:e,card:t,replacedCard:i,dashboard:n,viewState:r,interactionStates:s,inlineFilterValuesMap:o});return{cardId:e.id,...e.id!==t.id?{visibleCardId:t.id}:{},...i!=null&&i.insightId?{replacementInsightId:i.insightId}:{},title:t.title||"Untitled Card",type:t.type,renderOrder:a,metrics:Am(c.metricColumns),dimensions:jle(c),selectedEntities:Nle(t)}}function Tdt({activeFilters:e}){return Array.from(new Set((e||[]).map(t=>t.filterId)))}function fB({dashboard:e,selectedSheetId:t,activeFilters:n}){var s;const r=((s=AE(e,t??null))==null?void 0:s.id)||t||null;return{selectedSheetId:r,activeFilters:vy(e.filters,n,r)}}function Idt({dashboard:e,viewState:t,interactionStates:n,inlineFilterValuesMap:r,replacedCards:s}){const o=AE(e,t.selectedSheetId),i=(o==null?void 0:o.id)||t.selectedSheetId,a=Sle(e,t.selectedSheetId,s),c=Xl(e.filters,i);return{dashboardId:e.id,dashboardTitle:e.title||"Untitled Dashboard",selectedSheetId:i,sheetTitle:(o==null?void 0:o.title)||"Untitled Sheet",cards:a.map(({sourceCard:u,visibleCard:d,replacedCard:f},h)=>kdt({sourceCard:u,visibleCard:d,dashboard:e,viewState:t,interactionStates:n,inlineFilterValuesMap:r,replacedCard:f,renderOrder:h})),availableFilters:c.map(u=>{var d,f;return{filterId:u.id,label:u.title,...u.type?{type:u.type}:{},scope:(d=u.applyToCardIds)!=null&&d.length||(f=u.excludeCardIds)!=null&&f.length?"card":"sheet"}}),activeFilterIds:Tdt({activeFilters:t.activeFilters})}}function _dt({dashboard:e,viewState:t,cardId:n,runtimeFilterValues:r,interactionStates:s,inlineFilterValuesMap:o,replacedCards:i}){var v,w;const c=Sle(e,t.selectedSheetId,i).find(({sourceCard:S,visibleCard:N})=>S.id===n||N.id===n);if(!c)return{found:!1,cardId:n,selectedEntities:[],metrics:[],dimensions:[],comparison:null,cardFilters:null,effectiveDashboardFilters:[],activeInlineFilters:[],activeInteractionFilters:[],sortingOrGroupingSummary:{groupBy:[],pivotBy:[],sortBy:[]},notes:["Card not found in the current selected sheet."]};const{sourceCard:u,visibleCard:d,replacedCard:f}=c,{finalConfig:h,dashboardFilterValues:m,inlineFilterValues:p,interactionFilterValues:g}=Ile({sourceCard:u,card:d,replacedCard:f,interactionStates:s,dashboard:e,viewState:t,runtimeFilterValues:r,inlineFilterValuesMap:o}),{comparisonType:x,targetValue:b}=wre(h,d.type),y=Edt(d);return{found:!0,cardId:u.id,...u.id!==d.id?{visibleCardId:d.id}:{},...f!=null&&f.insightId?{replacementInsightId:f.insightId}:{},title:d.title,type:d.type,queryMode:y,...(v=d.sql)!=null&&v.trim()?{sql:d.sql.trim()}:{},...Tle(d)?{python:(w=d.python)==null?void 0:w.trim()}:{},selectedEntities:Nle(d),metrics:Am(h.metricColumns),dimensions:jle(h),comparison:x!=="none"?{type:x,...b!==void 0?{targetValue:b}:{}}:null,cardFilters:kle(h.filters),effectiveDashboardFilters:m,activeInlineFilters:p,activeInteractionFilters:g,sortingOrGroupingSummary:{groupBy:Am(h.groupByColumns),pivotBy:Am(h.pivotByColumns),sortBy:Am(h.sortByColumns)},notes:[...f?["This frame is currently showing a linked insight replacement."]:[],...y==="custom-sql"?["This card runs custom SQL."]:y==="custom-python"?["This card runs custom Python."]:[]]}}function vm(){return crypto.randomUUID()}function _le(){return crypto.randomUUID()}function jM(e){return typeof(e==null?void 0:e.then)=="function"}async function Ddt({replacedCards:e,apiServiceUrl:t,accessToken:n,queryClient:r}){const s=Object.entries(e);if(s.length===0||!n)return{};const o=await Promise.all(s.map(async([i,a])=>{const c=["resource-by-id",Qr.VISUAL,a.insightId];let u=r.getQueryData(c);if(!u)try{u=await r.fetchQuery({queryKey:c,queryFn:()=>or(`${t}/management/v1/visuals/${a.insightId}`,n)})}catch{return null}const d=AZ(u);return d?[i,{insightId:a.insightId,visibleCard:d,filters:a.filters,contextMode:a.contextMode}]:null}));return Object.fromEntries(o.filter(i=>i!==null))}function Mdt({dynamicVisualMode:e="auto"}={}){var _;const{authToken:t,tokenProps:n}=nt(),r=ds(),s=te(P=>P.dashboard.aiScopeTables),o=(_=oN().data)==null?void 0:_.assistantProfileId,i=C.useRef(null),a=C.useRef(vm()),c=C.useRef(!1),u=C.useRef(!1),d=C.useRef(e);d.current=e;function f(){const P=bs.getState(),M=te.getState(),R=FZ({overrides:P.dashboardEntitySelectionOverrides,dashboardId:M.dashboard.id,draftScopeKey:M.dashboardAssistantDraftScopeKey});return hA(oDe({currentAIContext:P.currentAIContext,manualSelectedEntities:R.selectedEntities,hasManualOverride:R.hasManualOverride,dashboardAIContext:M.dashboard.aiContext,derivedSelectedSheetEntities:RZ(M.dashboard,M.selectedSheetId)}))}function h(){const P=te.getState();return{aiContext:f(),dashboardViewState:fB({dashboard:P.dashboard,selectedSheetId:P.selectedSheetId,activeFilters:P.filterValues})}}const{sendMessage:m,messages:p,setMessages:g,regenerate:x,status:b,addToolResult:y,error:v,stop:w,clearError:S}=vle({transport:new G5({api:`${n.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${t==null?void 0:t.accessToken}`}),body:()=>{const P=bs.getState();i.current||(i.current=h());const{aiContext:M,dashboardViewState:R}=i.current;return{assistantId:"dashboard-assistant",assistantProfileId:o,conversationId:a.current,assistantRequestId:_le(),aiContext:M,dashboardViewState:R,dynamicVisualMode:d.current,dynamicVisualTheme:OO(),reasoningEffort:P.reasoningEffort,showReasoning:P.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:P,body:M})=>({body:{...M,messages:V7(P)}})}),onToolCall:T,sendAutomaticallyWhen:ble,onFinish({message:P,isAbort:M,isDisconnect:R,isError:L}){var O;u.current=!1,P!=null&&P.id&&((O=i.current)!=null&&O.aiContext)&&bs.getState().actions.setAssistantMessageContext(P.id,i.current.aiContext),console.log(M?"[Dashboard Assistant] Stream aborted by user":R?"[Dashboard Assistant] Stream disconnected (network error)":L?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully"),i.current=null,c.current&&(c.current=!1,a.current=vm(),g([]))},onError(P){var M;if(u.current=!1,P.name==="AbortError"||(M=P.message)!=null&&M.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)"),i.current=null,c.current&&(c.current=!1,a.current=vm(),g([]));return}console.error("[Dashboard Assistant] Stream error:",P),i.current=null,c.current&&(c.current=!1,a.current=vm(),g([]))}}),N=C.useCallback((...P)=>{u.current=!0;try{const M=m(...P);return jM(M)?M.catch(R=>{throw u.current=!1,R}):M}catch(M){throw u.current=!1,M}},[m]),j=C.useCallback((...P)=>{u.current=!0;try{const M=x(...P);return jM(M)?M.catch(R=>{throw u.current=!1,R}):M}catch(M){throw u.current=!1,M}},[x]),k=P=>{let M=!1;g(R=>{const L=typeof P=="function"?P(R):P;if(L.length===0){if(u.current)return c.current=!0,M=!0,R;c.current=!1,a.current=vm()}return L}),M&&w()};async function T({toolCall:P}){var A,W;if(P.toolName==="getCurrentTableScope"){y({tool:P.toolName,toolCallId:P.toolCallId,output:{tables:wle(s||[])}});return}const M=te.getState().dashboard,R=te.getState().inlineFilterValuesMap,L=Vt.getState(),O=L.interactionStates,U=await Ddt({replacedCards:L.replacedCards,apiServiceUrl:n.apiServiceUrl,accessToken:(t==null?void 0:t.accessToken)||"",queryClient:r}),z=fB({dashboard:M,selectedSheetId:te.getState().selectedSheetId,activeFilters:te.getState().filterValues});if(P.toolName==="getDashboardSynopsis"){y({tool:P.toolName,toolCallId:P.toolCallId,output:Idt({dashboard:M,viewState:z,interactionStates:O,inlineFilterValuesMap:R,replacedCards:U})});return}if(P.toolName==="getCardContext"){const $=((A=P.input)==null?void 0:A.cardId)||((W=P.args)==null?void 0:W.cardId)||"";y({tool:P.toolName,toolCallId:P.toolCallId,output:_dt({dashboard:M,viewState:z,cardId:$,runtimeFilterValues:te.getState().filterValues,interactionStates:O,inlineFilterValuesMap:R,replacedCards:U})})}}const E=!["ready","error"].includes(b),I=Cle(v);return{sendMessage:N,regenerate:j,isLoading:E,messages:p,setMessages:k,status:b,stop:w,errorMessage:I,clearError:S}}function Dle(){var u;const{authToken:e,tokenProps:t}=nt(),n=(u=oN().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=qt({queryKey:["assistant-profile",n],queryFn:()=>or(`${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 Mle({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:l.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[l.jsxs("div",{className:"mb-3 flex items-center",children:[l.jsx(BU,{className:"mr-2 h-4 w-4 text-muted-foreground"}),l.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),l.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>l.jsx(se,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function Adt({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=C.useRef(null),o=async a=>{const c=Array.from(a.target.files||[]);if(c.length===0)return;const u=dc-n;if(c.length>u){qe.error(`You can only attach ${dc} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=dae(c);if(f.forEach(({file:h,error:m})=>{qe.error(`${h.name}: ${m}`)}),d.length>0)try{const h=await Promise.all(d.map(m=>O5(m)));e(h)}catch(h){console.error("Failed to process files:",h),qe.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return l.jsxs(l.Fragment,{children:[l.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>=dc}),l.jsx(se,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=dc,title:n>=dc?`Maximum ${dc} files allowed`:"Attach files",children:l.jsx(WA,{className:"h-4 w-4 text-muted-foreground"})})]})}function Rdt({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=C.useState(!1),a=C.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),c=C.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=C.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=C.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=dc-r;if(h.length>m){qe.error(`You can only attach ${dc} files per message. You have ${m} slot(s) remaining.`);return}const{valid:p,errors:g}=dae(h);if(g.forEach(({file:x,error:b})=>{qe.error(`${x.name}: ${b}`)}),p.length>0)try{const x=await Promise.all(p.map(b=>O5(b)));t(x),qe.success(`${x.length} file(s) attached successfully`)}catch(x){console.error("Failed to process files:",x),qe.error("Failed to process one or more files")}},[n,r,t]);return l.jsxs("div",{className:J("relative",s),onDragEnter:a,onDragLeave:c,onDragOver:u,onDrop:d,children:[e,o&&!n&&l.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:l.jsxs("div",{className:"flex flex-col items-center gap-2",children:[l.jsx(eR,{className:"h-8 w-8 text-primary"}),l.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),l.jsxs("p",{className:"text-xs text-muted-foreground",children:[dc-r," slot(s) available"]})]})})]})}function Ale(e){return e.type==="dataset"&&e.label||e.name}function Fdt(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 Pdt({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:l.jsxs("div",{className:"mb-4 space-y-2",children:[l.jsxs(xe,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),l.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:l.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>l.jsxs(Xe,{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:[l.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),Ale(n),l.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:l.jsx(Dt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function Odt(e){const{tokenProps:t}=nt(),n=te(c=>c.authToken)||e;Ve(c=>c.selectedConnectionId),Ve(c=>{var u,d;return(d=(u=c==null?void 0:c.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=qt({queryKey:["semantic-domains"],queryFn:()=>or(`${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 Ldt(e,t){const{tokenProps:n}=nt(),r=te(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:c}=qt({queryKey:["datasets",e],queryFn:()=>or(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:o,error:c,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:c,refetchDatasets:s}}function $dt(e){var g,x;const{tokenProps:t}=nt(),n=te(b=>b.authToken)||e,{connections:r}=Ti(e),s=Ve(b=>{var y,v;return(v=(y=b==null?void 0:b.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(b=>b.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,c=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(b){var y;return!s||!b?!1:!!((y=o==null?void 0:o.capabilities)!=null&&y.path.includes("database"))}const{data:d,isPending:f,error:h,refetch:m}=qt({queryKey:["databases",s],queryFn:()=>or(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),p=(x=d==null?void 0:d.databases)==null?void 0:x.map(b=>({id:b.database_name,name:b.database_name}));return{isPending:f,error:h,databases:p||[],refetch:m,label:c}}function zdt(e){var g;const{tokenProps:t}=nt(),n=te(x=>x.authToken)||e,{connections:r}=Ti(e),s=Ve(x=>{var b,y;return(y=(b=x==null?void 0:x.card)==null?void 0:b.dataSource)==null?void 0:y.connectionId}),o=Ve(x=>{var b,y,v;return(v=(y=(b=x==null?void 0:x.card)==null?void 0:b.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(x=>x.id===s),a=i==null?void 0:i.capabilities,c=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){var x;return!(!s||!((x=i==null?void 0:i.capabilities)!=null&&x.path.includes("schema"))||!o)}const{data:d,isPending:f,error:h,refetch:m}=qt({queryKey:["schemas",s,o],queryFn:()=>or(`${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(x=>({id:x.schema_name,name:x.schema_name}));return{isPending:f,error:h,schemas:p||[],refetch:m,label:c}}function Rle(e){const{tokenProps:t}=nt(),n=te(h=>h.authToken)||e,{connections:r}=Ti(e),s=Ve(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:c,error:u,refetch:d}=qt({queryKey:["dataModels",s],queryFn:()=>or(`${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:c,error:u,dataModels:f||[],refetch:d}}function Vdt(){var S,N,j;const e=Ve(k=>k.card.dataSource);Ve(k=>k.actions.updateDirectSource);const t=Ve(k=>k.actions.updateDataSource),[n,r]=C.useState(""),{selectedConnection:s,error:o}=Ti(),{databases:i,isPending:a,error:c,label:u}=$dt(),{schemas:d,isPending:f,error:h,label:m}=zdt(),{error:p}=Rle(),g=s==null?void 0:s.capabilities.path.includes("schema"),x=s==null?void 0:s.capabilities.path.includes("database"),b=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)||[]})},w=k=>{var E;if(!((E=e==null?void 0:e.dbSelection)!=null&&E.database))return;const T=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{...T,schema:k},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return l.jsxs(l.Fragment,{children:[(o||c||h||p)&&l.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[l.jsx("div",{className:"flex items-center",children:l.jsxs("div",{className:"text-sm text-red-800",children:[l.jsx("strong",{children:"Error loading data:"}),l.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&l.jsxs("li",{children:["Connections: ",o]}),c&&l.jsxs("li",{children:[u,": ",c.message]}),h&&l.jsxs("li",{children:[m,": ",h.message]}),p&&l.jsxs("li",{children:["Data Models: ",p.message]})]})]})}),l.jsx(se,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),l.jsxs("div",{className:"space-y-4",children:[x&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(xe,{className:"text-sm font-medium",children:u}),l.jsxs(mt,{value:((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)||"",onValueChange:v,disabled:a,children:[l.jsx(ft,{className:"w-full",children:l.jsxs("div",{className:"flex items-center gap-2",children:[a&&l.jsx(Mn,{className:"h-4 w-4 animate-spin"}),l.jsx(gt,{placeholder:c?`Error loading ${b}`:a?`Loading ${b}...`:`Select ${b}...`})]})}),l.jsx(ht,{children:i.map(k=>l.jsx(De,{className:"hover:bg-muted",value:k.id,children:k.name},k.id))})]})]}),((N=e==null?void 0:e.dbSelection)==null?void 0:N.database)&&g&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(xe,{className:"text-sm font-medium",children:m}),l.jsxs(mt,{value:((j=e==null?void 0:e.dbSelection)==null?void 0:j.schema)||"",onValueChange:w,disabled:f,children:[l.jsx(ft,{className:"w-full",children:l.jsxs("div",{className:"flex items-center gap-2",children:[f&&l.jsx(Mn,{className:"h-4 w-4 animate-spin"}),l.jsx(gt,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),l.jsx(ht,{children:d.map(k=>l.jsx(De,{className:"hover:bg-muted",value:k.id,children:k.name},k.id))})]})]})]})]})}function Bdt(){const e=Ve(c=>c.card.dataSource),t=Ve(c=>c.actions.updateDataSource),[n,r]=C.useState(!1),s=c=>{if(!c||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(c).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=c=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==c);t({...e,selectedEntities:u})},i=c=>{if(c===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(c)/Math.log(u));return Number.parseFloat((c/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(xe,{className:"text-sm font-medium",children:"Upload Files"}),l.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:c=>{c.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:c=>{c.preventDefault(),r(!1),s(c.dataTransfer.files)},children:[l.jsx(eR,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),l.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),l.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:c=>s(c.target.files),accept:".csv,.json,.xlsx,.xls"}),l.jsx(se,{variant:"outline",size:"sm",onClick:()=>{var c;return(c=document.getElementById("file-upload"))==null?void 0:c.click()},children:"Select Files"}),l.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs(xe,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(c=>l.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(_a,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),l.jsxs("div",{className:"min-w-0",children:[l.jsx("p",{className:"truncate text-sm text-gray-700",children:c.originalName}),l.jsx("p",{className:"text-xs text-gray-500",children:c.file?i(c.file.size):""})]})]}),l.jsx(se,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(c.id),children:l.jsx(Dt,{className:"h-3 w-3"})})]},c.id))})]})]})}function Udt(){const e=Ve(f=>f.card.dataSource),t=Ve(f=>f.actions.updateDataSource),[n,r]=C.useState(""),[s,o]=C.useState(""),[i,a]=C.useState("api"),c=()=>{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 l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(xe,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),l.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(xe,{className:"text-xs text-gray-600",children:"Source Name"}),l.jsx(at,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(xe,{className:"text-xs text-gray-600",children:"URL"}),l.jsx(at,{placeholder:"https://api.example.com/data",value:s,onChange:f=>o(f.target.value),className:"h-8 text-sm"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(xe,{className:"text-xs text-gray-600",children:"Type"}),l.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:[l.jsx("option",{value:"api",children:"API Endpoint"}),l.jsx("option",{value:"csv",children:"CSV File"}),l.jsx("option",{value:"json",children:"JSON File"})]})]}),l.jsxs(se,{onClick:c,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[l.jsx(Br,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs(xe,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>l.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(uN,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),l.jsxs("div",{className:"min-w-0",children:[l.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),l.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),l.jsx(se,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:l.jsx(Dt,{className:"h-3 w-3"})})]},f.id))})]})]})}function Hdt(e,t){var y,v;const{tokenProps:n}=nt(),r=te(w=>w.authToken)||t,{connections:s}=Ti(t),o=Ve(w=>{var S,N;return(N=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:N.connectionId}),i=Ve(w=>{var S,N,j;return(j=(N=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:N.dbSelection)==null?void 0:j.database}),a=Ve(w=>{var S,N,j;return(j=(N=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:N.dbSelection)==null?void 0:j.schema}),c=s==null?void 0:s.find(w=>w.id===o),u=c==null?void 0:c.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){if(!o)return!1;const w=(u==null?void 0:u.path)||[];return!(w.includes("database")&&!i||w.includes("schema")&&!a)}const{data:h,isPending:m,isLoading:p,error:g,refetch:x}=qt({queryKey:[e,o,i,a],queryFn:()=>or(`${n.apiServiceUrl}/v1/${e}s`,(r==null?void 0:r.accessToken)||"",{connection_id:o,database_name:i,schema_name:a}),enabled:f()}),b=(v=h==null?void 0:h[`${e}s`])==null?void 0:v.map(w=>{var S;return{connectionId:c==null?void 0:c.id,connectionType:c==null?void 0:c.type,dialect:c==null?void 0:c.dialect,type:e,dbObjectType:(S=w==null?void 0:w.table_type)==null?void 0:S.toLowerCase(),id:w[`${e}_name`],database:i,schema:a,name:w[`${e}_name`]}});return{isPending:m,isLoading:p,error:g,entities:b||[],refetch:x,label:d}}function BS({title:e,message:t}){return l.jsx("div",{className:"rounded-xl border border-destructive/40 bg-destructive/10 p-4 text-destructive shadow-sm",children:l.jsxs("div",{className:"flex items-start gap-4",children:[l.jsx(zc,{className:"h-6 w-6 flex-shrink-0"}),l.jsxs("div",{className:"flex-1",children:[l.jsx("h4",{className:"text-base font-semibold",children:e}),t&&l.jsx("p",{className:"mt-1 text-sm text-destructive/90",children:t})]})]})})}function Wdt({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=Ti(),[i,a]=C.useState(""),[c,u]=C.useState(""),[d,f]=C.useState("tables"),{updateDataSource:h,setSelectedConnectionId:m}=lr(),{entities:p,isLoading:g,error:x}=Hdt("table"),{dataModels:b,isPending:y,error:v}=Rle(),w=E=>{const I=s.find(P=>P.id===E);if(!I)return;const _=I.type==="upload"?"upload":I.type==="url"?"url":"database";h({...e,connectionId:E,connectionType:I.type,mode:_,dbSelection:{database:"",schema:"",entityType:"table"}}),m(E)},S=E=>{var M,R;const I=n||[],_=I.some(L=>L.name===E.name&&L.type===E.type);let P;if(_)P=I.filter(L=>!(L.name===E.name&&L.type===E.type));else{const L={connectionId:e.connectionId,connectionType:e.connectionType,type:E.type,dbObjectType:E.dbObjectType,database:((M=e.dbSelection)==null?void 0:M.database)||"",schema:((R=e.dbSelection)==null?void 0:R.schema)||"",name:E.name,dialect:E.dialect};P=[...I,L]}t==null||t(P)},N=E=>{const I=n||[],_=I.some(M=>M.type==="model"&&M.name===E.name);let P;_?P=I.filter(M=>!(M.type==="model"&&M.name===E.name)):P=[...I,E],t==null||t(P)},j=p.filter(E=>E.name.toLowerCase().includes(i.toLowerCase())),k=b.filter(E=>E.name.toLowerCase().includes(c.toLowerCase())),T=C.useCallback(()=>{if(!t)return;const E=n||[];let I=[...E];if(d==="tables"){const P=j.filter(M=>!E.some(R=>R.name===M.name&&R.type==="table")).map(M=>{var R,L;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:M.dbObjectType,database:((R=e.dbSelection)==null?void 0:R.database)||"",schema:((L=e.dbSelection)==null?void 0:L.schema)||"",name:M.name,dialect:M.dialect}});I=[...E,...P]}else if(d==="datamodels"){const _=k.filter(P=>!E.some(M=>M.name===P.name&&M.type==="model"));I=[...E,..._]}t(I)},[d,j,k,n,e,t]);return C.useEffect(()=>{r&&r(T)},[r,T]),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(xe,{className:"font-medium= text-sm",children:"Connection"}),l.jsxs(mt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:w,disabled:o,children:[l.jsx(ft,{className:"w-full",children:l.jsx(gt,{placeholder:o?"Loading connections...":"Select connection..."})}),l.jsx(ht,{children:s.map(E=>l.jsx(De,{className:"hover:bg-muted",value:E.id,children:l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(yl,{className:"h-4 w-4 flex-shrink-0"}),l.jsx("span",{className:"truncate",children:E.name}),l.jsx(Xe,{variant:"secondary",className:"flex-shrink-0 text-xs",children:E.type})]})},E.id))})]})]}),(e==null?void 0:e.connectionId)&&l.jsxs(l.Fragment,{children:[e.connectionType==="upload"&&l.jsx(Bdt,{}),e.connectionType==="url"&&l.jsx(Udt,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&l.jsxs(l.Fragment,{children:[l.jsx(Vdt,{}),l.jsx("div",{className:"space-y-4",children:l.jsx("div",{className:"space-y-2",children:l.jsxs(Fs,{defaultValue:"tables",value:d,onValueChange:E=>f(E),className:"w-full",children:[l.jsxs(ws,{className:"grid w-full grid-cols-2",children:[l.jsxs(on,{value:"tables",children:["Tables & Views (",j.length,")"]}),l.jsxs(on,{value:"datamodels",children:["Data Models (",k.length,")"]})]}),l.jsxs(sr,{value:"tables",className:"space-y-2",children:[l.jsx(at,{placeholder:"Search tables and views...",value:i,onChange:E=>a(E.target.value),className:"h-8 text-sm",disabled:g}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?l.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):x?l.jsx(BS,{title:"Error loading tables",message:x.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):j.length===0?l.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):j.map(E=>{const I=n.some(_=>_.name===E.name&&_.type==="table");return l.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(E),children:[l.jsx(Gt,{id:`table-${E.name}`,checked:I,onCheckedChange:()=>S(E),onClick:_=>_.stopPropagation(),disabled:g}),l.jsxs(xe,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[E.name,E.dbObjectType==="view"&&l.jsx(Xe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),E.dbObjectType==="materialized view"&&l.jsx(Xe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},E.name)})})]}),l.jsxs(sr,{value:"datamodels",className:"space-y-2",children:[l.jsx(at,{placeholder:"Search data models...",value:c,onChange:E=>u(E.target.value),className:"h-8 text-sm",disabled:y}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?l.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?l.jsx(BS,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):k.length===0?l.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):k.map(E=>{const I=n.some(_=>_.name===E.name&&_.type==="model");return l.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>N(E),children:[l.jsx(Gt,{id:`dataModel-${E.name}`,checked:I,onCheckedChange:()=>N(E),onClick:_=>_.stopPropagation(),disabled:y}),l.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[l.jsx(xe,{className:"cursor-pointer",children:E.name}),l.jsx("span",{className:"text-xs text-muted-foreground",children:E.description})]})]},E.name)})})]})]})})})]})]})]})}function qdt({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,domainAccess:s=bl.DEFAULT_SEMANTIC_DOMAIN_ACCESS,autoSelectedDomainId:o,onRegisterSelectAll:i}){var w;const[a,c]=C.useState(""),u=C.useCallback(S=>{const N={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:S};t({...N})},[e,t]);C.useEffect(()=>{o&&!(e!=null&&e.semanticDomainId)&&u(o)},[o,e==null?void 0:e.semanticDomainId,u]);const{semanticDomains:d,isPending:f,error:h}=Odt(),m=d.filter(S=>{var N,j;switch(s.mode){case"all":return!0;case"none":return!1;case"include":return((N=s.domainIds)==null?void 0:N.includes(S.id))??!1;case"exclude":return!(((j=s.domainIds)==null?void 0:j.includes(S.id))??!1);default:return!0}}),{datasets:p,isPending:g,error:x}=Ldt(e==null?void 0:e.semanticDomainId),b=S=>{const N=r||[],j=N.some(T=>T.id===S.id&&T.type==="dataset");let k;if(j)k=N.filter(T=>!(T.id===S.id&&T.type==="dataset"));else{const T={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};k=[...N,T]}n==null||n(k)},y=p.filter(S=>S.name.toLowerCase().includes(a.toLowerCase())),v=C.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const S=r||[],j=y.filter(T=>!S.some(E=>E.id===T.id&&E.type==="dataset")).map(T=>({id:T.id,datasetType:T.type,name:T.name||T.table,label:T.label,domainId:T.domainId,description:T.description,database:T.database,schema:T.schema,type:"dataset",connectionId:T.connectionId,connectionType:T.connectionType,dialect:T.dialect,datamodelId:T.datamodelId,sql:T.sql})),k=[...S,...j];n(k)},[y,r,e==null?void 0:e.semanticDomainId,n]);return C.useEffect(()=>{i&&i(v)},[i,v]),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(xe,{className:"text-sm font-medium",children:"Semantic Domain"}),l.jsxs(mt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:u,disabled:f||s.mode==="none"||s.mode==="include"&&!!o,children:[l.jsx(ft,{className:"w-full",children:l.jsx(gt,{placeholder:f?"Loading semantic domains...":s.mode==="none"?"No semantic domains available for this token":s.mode==="include"&&o?"Loading domain...":"Select semantic domain...",children:((w=m.find(S=>S.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:w.label)||"Select semantic domain"})}),l.jsx(ht,{children:m.map(S=>l.jsx(De,{className:"hover:bg-muted",value:S.id,children:l.jsxs("div",{className:"flex flex-col items-start",children:[l.jsx("span",{className:"font-medium",children:S.label}),l.jsx("span",{className:"text-xs",children:S.description})]})},S.id))})]}),h&&l.jsx(BS,{title:"Error loading semantic models",message:h.message})]}),(e==null?void 0:e.semanticDomainId)&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(xe,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(at,{placeholder:"Search datasets...",value:a,onChange:S=>c(S.target.value),className:"h-8 text-sm",disabled:g}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):x?l.jsx(BS,{title:"Error loading datasets",message:x.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):y.length===0?l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:a?"No datasets match your search":"No datasets available"}):y.map(S=>{const N=r.some(j=>j.id===S.id&&j.type==="dataset");return l.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>b(S),children:[l.jsx(Gt,{id:`dataset-${S.id}`,checked:N,onCheckedChange:()=>b(S),onClick:j=>j.stopPropagation(),disabled:g}),l.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[l.jsx(xe,{className:"cursor-pointer font-medium",children:S.label||S.name}),l.jsx("span",{className:"text-xs text-gray-500",children:S.description})]})]},S.label||S.name)})})]})]})]})}function Gdt(e,t,n){switch(e){case"none":return!1;case"include":return n.includes(t);case"exclude":return!n.includes(t);case"all":default:return!0}}function Ydt({mode:e,currentDomainId:t,scopedDomainIds:n,hasSelectedEntities:r}){return e==="all"?!1:e==="none"?!!t||r:t?!Gdt(e,t,n):r}function Kdt(e){const t=new Set;for(const n of e||[])"domainId"in n&&typeof n.domainId=="string"&&t.add(n.domainId);if(t.size===1)return[...t][0]}function K5({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s,onSaveSelectedEntities:o,saveAsDashboardDefault:i=!1}){var W,$;const{tokenProps:a}=nt(),c=a.semanticDomainAccess||bl.DEFAULT_SEMANTIC_DOMAIN_ACCESS,[u,d]=C.useState([]),[f,h]=C.useState(void 0),{updateDataSource:m}=lr(),p=te(D=>D.isVisualEditing),g=te(D=>D.dashboard.aiContext),{setAiContext:x}=en(),b=C.useRef(null),[y,v]=C.useState(!1),w=c.mode,S=w==="include"||w==="exclude",N=w!=="all",j=!S,k=r==="aiContext"&&S?"semanticDomain":n.mode,T=w==="include"&&(((W=c.domainIds)==null?void 0:W.length)||0)===1?($=c.domainIds)==null?void 0:$[0]:void 0,E=C.useCallback(D=>{const q=D;m({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:q,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...q!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,m]),I=C.useCallback(D=>{m({...n,...D})},[n,m]),_=C.useCallback(D=>{if(r==="aiContext"){"semanticDomainId"in D&&h(D.semanticDomainId);return}I(D)},[r,I]),P=r==="aiContext"?f:n.semanticDomainId,M=r==="aiContext"?{...n,mode:k,semanticDomainId:f}:n;C.useEffect(()=>{if(!N||r==="aiContext"&&!e)return;if(S&&n.mode!=="semanticDomain"&&r==="dataSource"){E("semanticDomain");return}if(k!=="semanticDomain")return;const D=P,q=c.domainIds??[],Q=r==="aiContext"?u:n.selectedEntities,Y=((Q==null?void 0:Q.length)??0)>0,V=((u==null?void 0:u.length)??0)>0;Ydt({mode:w,currentDomainId:D,scopedDomainIds:q,hasSelectedEntities:Y})&&(r==="dataSource"?I({semanticDomainId:void 0,selectedEntities:[]}):h(void 0),V&&d([]))},[S,N,k,n.mode,P,n.selectedEntities,r,f,u,e,c.domainIds,w,I,E]),C.useEffect(()=>{T&&!P&&_({semanticDomainId:T})},[T,P,_]),C.useEffect(()=>{if(e){d(s||[]);const D=r==="aiContext"?Kdt(s):void 0;h(n.semanticDomainId||D)}else b.current=null,v(!1)},[e,n==null?void 0:n.selectedEntities,r,m,s,n]);const R=D=>{const q=u.filter(Q=>!pi(Q,D));d(q)},L=()=>{d([])},O=C.useCallback(D=>{d(D)},[]),U=C.useCallback(()=>{b.current&&b.current()},[]),z=C.useCallback(D=>{b.current=D,v(!0)},[]);function A(){var D,q;if(r==="aiContext"){if(p&&m(n),i){const Q={...g,selectedEntities:u,mode:u.length>0?"fixed":"auto"};x(Q)}o==null||o(u),t(!1)}else if(r==="dataSource"){if(n.mode==="semanticDomain"){const Q=(D=u==null?void 0:u[0])==null?void 0:D.connectionId,Y=(q=u==null?void 0:u[0])==null?void 0:q.connectionType;m({...n,connectionId:Q,connectionType:Y,selectedEntities:u})}else m({...n,selectedEntities:u});t(!1)}}return l.jsx(Ur,{open:e,onOpenChange:t,children:l.jsx(Tr,{className:"flex max-w-2xl flex-col",children:l.jsxs("div",{children:[l.jsxs(Ir,{className:"flex-shrink-0",children:[l.jsx(_r,{children:r==="aiContext"?"Data Context":"Select Data Source"}),l.jsx(is,{children:r==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),l.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:l.jsxs("div",{className:"space-y-4",children:[j&&l.jsx("div",{className:"space-y-2",children:l.jsx(Fs,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:E,className:"w-full",children:l.jsxs(ws,{className:"grid w-full grid-cols-2",children:[l.jsx(on,{value:"database",children:"Direct Source"}),l.jsx(on,{value:"semanticDomain",children:"Semantic Domain"})]})})}),k==="semanticDomain"&&l.jsx(qdt,{dataSource:M,onDataSourceUpdate:_,selectedEntities:u,onSelectionChange:O,domainAccess:c,autoSelectedDomainId:T,onRegisterSelectAll:z}),k==="database"&&j&&l.jsx(Wdt,{dataSource:n,onDataSourceUpdate:I,selectedEntities:u,onSelectionChange:O,onRegisterSelectAll:z})]})}),l.jsx(Pdt,{selectedEntities:u,onDeselectEntity:R}),l.jsx(Rs,{className:"flex-shrink-0",children:l.jsx("div",{className:"flex w-full justify-between",children:l.jsxs("div",{className:"flex grow justify-end gap-2",children:[l.jsx(se,{variant:"outline",onClick:U,disabled:!y,children:"Select All"}),l.jsx(se,{variant:"outline",onClick:L,disabled:u.length===0,children:"Clear All"}),l.jsxs(se,{variant:"outline",onClick:()=>t(!1),children:[l.jsx(Dt,{className:"mr-2 h-4 w-4"}),"Close"]}),l.jsxs(se,{onClick:A,children:[l.jsx(Zr,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function US(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return l.jsx(ZA,{className:r});case"view":return l.jsx(Ku,{className:r});case"materialized view":return l.jsx(_pe,{className:r});case"model":return l.jsx(fN,{className:r});case"file":return l.jsx(_a,{className:r});case"dataset":return l.jsx(yl,{className:r});case"upload":return l.jsx(eR,{className:r});case"url":return l.jsx(YU,{className:r});default:return l.jsx(uN,{className:r})}}const EM=e=>e.name||e.name,Zdt=e=>{const t=EM(e),n="description"in e?e.description:"",r=e.database||"",s=e.schema||"";return l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"font-medium",children:t}),n&&l.jsx("div",{className:"text-sm text-muted-foreground",children:n}),l.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,s&&` • Schema: ${s}`]})]})};function Xdt({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r,className:s}){const[o,i]=C.useState(!1),a=e.length>0;e.length,t.length,e.length<t.length;const c=e.length>=3?e.slice(0,2):e,u=e.length>=3?e.slice(2):[],d=u.length>0;return l.jsx(wr,{children:l.jsx("div",{className:s,children:a&&l.jsxs("div",{className:"flex flex-wrap gap-1",children:[c.map((f,h)=>{const m="id"in f?f.id:`${f.connectionId}-${f.name}`;return l.jsxs(Nn,{children:[l.jsx(jn,{asChild:!0,children:l.jsxs(Xe,{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:[US(f.type,{size:"h-3 w-3"}),l.jsx("span",{className:"max-w-24 truncate text-xs",children:EM(f)}),l.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(f),children:l.jsx(Dt,{className:"h-3 w-3"})})]})}),l.jsx(Dn,{side:"top",className:"max-w-xs",children:Zdt(f)})]},m)}),d&&l.jsxs(Nn,{open:o,onOpenChange:i,children:[l.jsx(jn,{asChild:!0,children:l.jsxs(Xe,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>i(!0),children:[l.jsx(WU,{className:"h-3 w-3"}),l.jsxs("span",{className:"text-xs",children:[u.length," more"]}),l.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(u),children:l.jsx(Dt,{className:"h-3 w-3"})})]})}),l.jsx(Dn,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),l.jsx("div",{className:"space-y-2",children:u.map(f=>{const h="id"in f?f.id:`${f.connectionId}-${f.name}`;return l.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:US(f.type,{size:"h-3 w-3"})}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-sm font-medium",children:EM(f)}),l.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[f.type," ",f.database?`• ${f.database}`:""]})]})]}),l.jsx(se,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(f),u.length===1&&i(!1)},children:l.jsx(Dt,{className:"h-3 w-3"})})]},h)})})]})})]})]})})})}const Fle=F.forwardRef(({className:e,...t},n)=>l.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[l.jsx(Gs,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),l.jsx(xo.Input,{ref:n,className:J("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})]}));Fle.displayName=xo.Input.displayName;const l1=e=>e.label||(e==null?void 0:e.name),hB=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function Qdt({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:c,onAddContext:u}){const{tokenProps:d}=nt(),f=(d==null?void 0:d.type)==="dashboard",[h,m]=C.useState(""),[p,g]=C.useState(""),x=s.filter(N=>{if(!h)return!0;const j=l1(N).toLowerCase(),k=hB(N).toLowerCase(),T=h.toLowerCase();return j.includes(T)||k.includes(T)});C.useEffect(()=>{e||(m(""),g(""))},[e]),C.useEffect(()=>{x.length>0&&!p&&g(l1(x[0]))},[x,p]);const b=()=>{if(!p)return;const N=x.find(j=>l1(j)===p);N&&(o.some(k=>"id"in N&&"id"in k?N.id===k.id:N.name===k.name&&N.connectionId===k.connectionId)||t(N),i(N),r())},y=N=>{(N.key==="Tab"||N.key==="Enter")&&(N.preventDefault(),b())};if(!e)return null;const v=N=>o.some(j=>"id"in N&&"id"in j?N.id===j.id:N.name===j.name&&N.connectionId===j.connectionId),w=o.length===s.length,S=o.length>0;return l.jsx(l.Fragment,{children:l.jsxs(jg,{shouldFilter:!1,value:p,onValueChange:g,onKeyDown:y,children:[s.length>0&&l.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[l.jsx(Fle,{placeholder:"Search entities...",value:h,onValueChange:m,className:"flex-1 border-0",autoFocus:!0}),!f&&l.jsxs(se,{onClick:N=>{N.preventDefault(),N.stopPropagation(),u==null||u()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[l.jsx(Br,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&l.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[l.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(se,{onClick:N=>{N.preventDefault(),N.stopPropagation(),a==null||a()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},disabled:w,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),S&&l.jsxs(se,{onClick:N=>{N.preventDefault(),N.stopPropagation(),c==null||c()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[l.jsx(Dt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),l.jsxs(Eg,{className:"min-h-60",children:[l.jsx(kg,{children:l.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[l.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&l.jsxs(se,{onClick:N=>{N.preventDefault(),N.stopPropagation(),u==null||u()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[l.jsx(Br,{className:"h-4 w-4"}),"Add Datasets"]})]})}),l.jsx(Tg,{children:x.map((N,j)=>{const k=v(N),T="id"in N?N.id:`${N.connectionId}-${N.name}`,E=l1(N);return l.jsxs(Ig,{value:E,onSelect:()=>{k?n==null||n(N):t(N)},onMouseDown:I=>{I.preventDefault(),I.stopPropagation()},className:J("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[l.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:US(N.type)}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate font-medium",children:E}),l.jsx("div",{className:"truncate text-xs text-muted-foreground",children:hB(N)})]}),k&&l.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:l.jsx(Zr,{className:"h-3 w-3 text-background"})})]},T)})})]})]})})}function kM({mode:e="full",compact:t=!1,inlineLayout:n=!1,inlineTriggerFirst:r=!1,syncOnOpen:s=!1,open:o,onOpenChange:i,onEntityMention:a,onEntityRemoved:c,onEntitiesRemoved:u,onSelectionChange:d,className:f,triggerClassName:h,triggerVariant:m="secondary",triggerLabel:p="Add entity",triggerIconOnly:g=!0,assistantType:x}){const[b,y]=C.useState(!1),[v,w]=C.useState(!1),S=o??b,N=o!==void 0,j=C.useRef(!1),T=Ve(B=>B.card.dataSource)??qy,{selectedEntities:E,availableEntities:I,syncWithGlobalContext:_,setSelectedEntities:P,applyDashboardDefaultEntities:M,isEntitySelected:R}=sj(x),L=e==="full"||e==="display",O=e==="full"||e==="trigger",U=C.useMemo(()=>g&&E.length>0?`Add entity (${E.length})`:p,[E.length,g,p]);C.useEffect(()=>{S&&!j.current&&s&&_(),j.current=S},[S,s,_]);const z=C.useCallback(B=>{N||y(B),i==null||i(B)},[N,i]),A=C.useCallback(B=>{const H=E.filter(G=>!pi(G,B));P(H),c==null||c(B),d==null||d(H)},[c,d,E,P]),W=C.useCallback(B=>{if(B.length===0)return;const H=E.filter(G=>!B.some(K=>pi(G,K)));P(H),u==null||u(B),d==null||d(H)},[u,d,E,P]),$=C.useCallback(B=>{const H=R(B)?E.filter(G=>!pi(G,B)):[...E,B];P(H),d==null||d(H)},[R,d,E,P]),D=C.useCallback(()=>{P(I),d==null||d(I)},[I,d,P]),q=C.useCallback(()=>{P([]),d==null||d([])},[d,P]),Q=C.useCallback(B=>{x==="dashboard"?M():P(B),d==null||d(B)},[M,x,d,P]),Y=C.useCallback(B=>{const H=E.some(G=>pi(G,B))?E:[...E,B];P(H),a==null||a(B),d==null||d(H),z(!1)},[a,d,E,z,P]),V=L?l.jsx(Xdt,{className:J(n?"contents":"space-y-2"),entities:E,availableEntities:I,onRemoveEntity:A,onRemoveEntities:W}):null,Z=O?l.jsxs(l.Fragment,{children:[l.jsxs(Lr,{open:S,onOpenChange:z,children:[l.jsx($r,{asChild:!0,children:l.jsxs(se,{variant:m,size:"sm",className:J(t?"h-7 gap-1.5 px-2 text-xs":"h-7 px-2",h),title:p,children:[l.jsx(jpe,{className:"h-4 w-4 text-muted-foreground"}),!g&&l.jsx("span",{children:U})]})}),l.jsx(zr,{className:J("w-80 p-0",t&&"w-72"),align:"start",side:"top",sideOffset:8,onOpenAutoFocus:B=>B.preventDefault(),children:l.jsx(Qdt,{isOpen:!0,onSelect:$,onDeselect:$,onClose:()=>z(!1),availableEntities:I,selectedEntities:E,onTabComplete:Y,onSelectAll:D,onRemoveAll:q,onAddContext:()=>{z(!1),w(!0)}})})]}),l.jsx(K5,{incomingSelectedEntities:E,open:v,onOpenChange:w,dataSource:T,dialogMode:"aiContext",onSaveSelectedEntities:Q,saveAsDashboardDefault:x==="dashboard"})]}):null;return l.jsx("div",{className:J(n?"flex flex-wrap items-center gap-1":"",!n&&L?"space-y-2":"",f),children:n&&r?l.jsxs(l.Fragment,{children:[Z,V]}):l.jsxs(l.Fragment,{children:[V,Z]})})}const Z5=C.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:c},u)=>{const[d,f]=C.useState(!1),h=C.useRef(null),{queueMessage:m}=Qp(),{addFileAttachment:p,removeFileAttachment:g,clearFileAttachments:x}=xA(),b=gA(c);C.useEffect(()=>{u&&"current"in u&&(u.current=h.current)},[u]);const y=C.useCallback(()=>{const E=h.current;if(E){if(!e||e.length===0){E.style.height="10px";return}E.style.height="auto";const I=Math.min(Math.max(E.scrollHeight,10),200);E.style.height=`${I}px`}},[e]);C.useEffect(()=>{y()},[y]),C.useEffect(()=>{const E=setTimeout(()=>{y()},0);return()=>clearTimeout(E)},[y]);const v=()=>{const E=e.trim();!E&&b.length===0||(a!=="ready"?(m(c,E,b),t(""),x(c)):r({preventDefault:()=>{}}))},w=E=>{E.key==="Enter"&&!E.shiftKey&&(E.preventDefault(),v()),E.key==="@"&&f(!0)},S=C.useCallback(E=>{const I=oot(E.nativeEvent);I.length>0&&(E.preventDefault(),I.forEach(async _=>{const P=await O5(_);p(c,P)}))},[p,c]),N=C.useCallback(E=>{E.forEach(I=>{p(c,I)})},[p,c]),j=C.useCallback(E=>{E.forEach(I=>{p(c,I)})},[p,c]),k=C.useCallback(E=>{g(c,E)},[g,c]),T=C.useCallback(E=>{const I=`@${E}`;e.includes(I)&&t(e.replace(I,"").replace(/\s{2,}/g," ").trim())},[e,t]);return l.jsxs(Rdt,{onFilesDropped:N,currentFileCount:b.length,disabled:s,className:"space-y-4",children:[l.jsx(kM,{mode:"display",assistantType:c,onEntityRemoved:E=>{const I="label"in E?E.label:E.name;T(I)},onEntitiesRemoved:E=>{let I=e;E.forEach(_=>{const P="label"in _?_.label:_.name;I=I.replace(`@${P}`,"")}),I!==e&&t(I.replace(/\s{2,}/g," ").trim())}}),b.length>0&&l.jsx(iot,{files:b,onRemove:k,showRemove:!s,className:"mb-2"}),l.jsxs("div",{className:"rounded-xl border border-border/60 bg-background shadow-sm transition-colors focus-within:border-border focus-within:ring-1 focus-within:ring-ring/20",children:[l.jsx("textarea",{ref:h,value:e,onChange:n,onKeyDown:w,onPaste:S,onFocus:()=>{y(),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 pt-3 pb-1 text-sm text-foreground placeholder:text-muted-foreground/40 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),l.jsxs("div",{className:"flex items-center justify-between px-2 pb-2",children:[l.jsxs("div",{className:"flex items-center gap-0.5",children:[l.jsx(kM,{mode:"trigger",assistantType:c,syncOnOpen:c==="dashboard",open:d,onOpenChange:f,onEntityMention:E=>{var _;const I="label"in E?E.label:E.name;t(`${e}@${I} `),(_=h.current)==null||_.focus()},triggerVariant:"secondary",triggerIconOnly:!0,triggerClassName:"h-7 px-2",triggerLabel:"Add entity"}),l.jsx(Adt,{onFilesSelected:j,disabled:s,currentFileCount:b.length})]}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[s&&l.jsx(se,{className:"h-8 w-8 rounded-full p-0",size:"sm",onClick:o,children:l.jsx(Bpe,{className:"size-3.5"})}),!s&&l.jsx(se,{disabled:!e.trim()&&b.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",className:"h-8 w-8 rounded-full p-0",onClick:v,title:a!=="ready"?"Message will be queued":void 0,children:l.jsx(YA,{className:"size-3.5"})})]})]})]})]})});Z5.displayName="ChatInputWithContext";function Ple({assistantType:e,className:t}){const n=B7(e),{removeFromQueue:r}=Qp();return n.length===0?null:l.jsxs("div",{className:J("space-y-2",t),children:[l.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[l.jsx(Yu,{className:"h-3 w-3"}),l.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),l.jsx("div",{className:"space-y-2",children:n.map(s=>l.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:l.jsxs("div",{className:"flex items-start justify-between gap-2",children:[l.jsx("div",{className:"flex-1 space-y-1",children:l.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),l.jsx(se,{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:l.jsx(Dt,{className:"h-3 w-3"})})]})},s.id))})]})}function Ole({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=B7(e),{dequeueMessage:o}=Qp();C.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 Jdt(e){return e?typeof e=="string"?e:typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:typeof e.value=="string"?e.value:"":""}function eft(e){if(!e)return"none";const t=(e==null?void 0:e.id)??(e==null?void 0:e.messageId)??(e==null?void 0:e.createdAt)??(e==null?void 0:e.timestamp)??"unknown";if(!Array.isArray(e.parts)){const r=typeof(e==null?void 0:e.content)=="string"?e.content:typeof(e==null?void 0:e.text)=="string"?e.text:"";return`${t}|${(e==null?void 0:e.role)??"unknown"}|${r.length}|${r.slice(-24)}`}const n=e.parts.map(r=>{const s=typeof(r==null?void 0:r.type)=="string"?r.type:"unknown",o=typeof(r==null?void 0:r.state)=="string"?r.state:"na",i=Jdt(r);return`${s}:${o}:${i.length}:${i.slice(-24)}`}).join("|");return`${t}|${(e==null?void 0:e.role)??"unknown"}|${e.parts.length}|${n}`}function Lle(e,t={}){const{threshold:n=40,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=C.useRef(null),a=C.useRef(null),[c,u]=C.useState(!0),[d,f]=C.useState(!0),[h,m]=C.useState(!1),[p,g]=C.useState(0),x=C.useRef(!0),b=C.useRef(!0),y=C.useRef(!1),v=C.useRef(!1),w=C.useRef(0),S=C.useRef({count:0,signature:"none"}),N=C.useCallback(()=>{if(i.current)return i.current;const R=a.current;if(!R)return null;const L=R.closest("[data-radix-scroll-area-viewport]");if(L)return i.current=L,L;const O=R.parentElement;return O?(i.current=O,O):null},[]),j=C.useCallback(()=>{const R=N();return R?R.scrollHeight-R.scrollTop-R.clientHeight:0},[N]),k=C.useCallback(()=>j()<=n,[j,n]),T=C.useCallback(R=>{x.current!==R&&(x.current=R,u(R))},[]),E=C.useCallback(R=>{b.current!==R&&(b.current=R,f(R))},[]),I=C.useCallback(()=>{m(R=>R&&!1),g(R=>R===0?R:0)},[]),_=C.useCallback((R={})=>{const L=N();if(!L)return;const{force:O=!1,instant:U=!1}=R;if(!O&&y.current)return;const z=U||r==="auto"||r==="instant"?"auto":r;v.current=!0,z==="smooth"&&"scrollTo"in L?L.scrollTo({top:L.scrollHeight,behavior:"smooth"}):L.scrollTop=L.scrollHeight,w.current=L.scrollTop,y.current=!1,T(!0),E(!0),I(),requestAnimationFrame(()=>{v.current=!1})},[r,I,N,T,E]),P=C.useCallback(()=>{g(0),m(!1)},[]),M=C.useCallback(()=>{const R=N();if(!R)return;const L=w.current,O=R.scrollTop,U=O-L;w.current=O;const z=k();if(v.current){E(z),z&&(y.current=!1,T(!0));return}if(U<-1&&!z){y.current=!0,T(!1),E(!1);return}if(z){y.current=!1,T(!0),E(!0),I();return}E(!1),y.current&&T(!1)},[I,N,k,T,E]);return C.useEffect(()=>{const R=N();if(!e||e.length===0){S.current={count:0,signature:"none"},R&&(w.current=R.scrollTop),I();return}const L=e[e.length-1],O=eft(L),U=S.current,z=e.length>U.count,A=O!==U.signature;S.current={count:e.length,signature:O};const W=o||s&&(L==null?void 0:L.role)==="assistant"&&A;if(!y.current){T(!0),R&&k()&&E(!0),(z||A||W)&&_({force:!1,instant:W});return}if(z){const $=e.length-U.count;$>0&&(m(!0),g(D=>D+$))}else A&&(m(!0),g($=>$>0?$:1))},[I,o,s,N,k,e,_,T,E]),C.useEffect(()=>{_({force:!0,instant:!0})},[_]),C.useEffect(()=>{if(typeof ResizeObserver>"u")return;const R=a.current;if(!R)return;const L=new ResizeObserver(()=>{y.current||_({force:!1,instant:!0})});return L.observe(R),()=>{L.disconnect()}},[_]),C.useEffect(()=>()=>{v.current=!1},[]),{scrollRef:i,contentRef:a,isAutoScrollEnabled:c,isAtBottom:d,hasNewMessages:h,newMessageCount:p,scrollToBottom:_,handleScroll:M,resetNewMessageCount:P}}function $le(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=C.useState(r),a=C.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),c=e.length>o,u=o>=e.length,d=C.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=C.useCallback(()=>{i(r)},[r]);return C.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:c,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}const mB={"tool-getTableColumns":{"input-streaming":"Fetching table columns...","input-available":"Reading column definitions..."},"tool-getChartDataFromSqlAndPython":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getChartDataFromCardConfig":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getForecastDataFromSqlAndPython":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getChartSQLSyntax":{"input-streaming":"Generating SQL syntax...","input-available":"SQL syntax generated"},"tool-validateCardConfigFormat":{"input-streaming":"Validating card config format...","input-available":"Card config format validated"},"tool-generateQueryConfig":{"input-streaming":"Generating query config...","input-available":"Sending query config..."},"tool-generateDynamicVisual":{"input-streaming":"Planning dynamic visual...","input-available":"Generating dynamic visual..."},"tool-generateDynamicVisualFromData":{"input-streaming":"Planning dynamic visual...","input-available":"Building visual..."},"tool-askForMoreInfo":{"input-streaming":"Asking for more information...","input-available":"More information requested"},"tool-createChartFromSql":{"input-streaming":"Creating chart...","input-available":"Chart created"},"tool-getUserSql":{"input-streaming":"Getting SQL...","input-available":"SQL retrieved"},"tool-inspectTableData":{"input-streaming":"Inspecting table data...","input-available":"Analyzing data..."},"tool-getDomainRelationships":{"input-streaming":"Getting domain relationships...","input-available":"Analyzing data..."}};function tft(e,t){var r;if((r=mB[e])!=null&&r[t])return mB[e][t];const n=e.replace("tool-","").replace(/([A-Z])/g," $1").toLowerCase().trim();return t==="input-streaming"?`Processing ${n}...`:`Preparing ${n} response...`}function zle(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:"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:tft(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const nft=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function rft({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=C.useState(!1),[a,c]=C.useState(XM),[u,d]=C.useState(!1),[f,h]=C.useState("auto"),[m,p]=C.useState(!1),[g,x]=C.useState(!1),b=n??g,{isLocalDev:y,isConsoleMode:v}=lg(),w=C.useRef(null);te(le=>le.dashboard.aiScopeTables),te(le=>le.isDashboardEditing);const S=te(le=>le.selectedSheetId),{setDataSource:N}=lr(),{addFrame:j,setSelectedFrameId:k,setIsDashboardEditing:T}=en(),{setReasoningEffort:E,setShowReasoning:I,clearAssistantMessageContexts:_}=tN(),{clearQueue:P}=Qp(),{clearFileAttachments:M,getFileAttachments:R}=xA(),L=gA("dashboard"),O=Ve(le=>le.card.dataSource),{assistantProfile:U}=Dle(),z=te(le=>le.handleOpenAssistantProfile),{selectedEntities:A,applyDashboardDefaultEntities:W}=sj("dashboard"),{sendMessage:$,isLoading:D,messages:q,setMessages:Q,status:Y,stop:V,errorMessage:Z,clearError:B}=Mdt({dynamicVisualMode:f}),H=C.useCallback(le=>{r==null||r(le),n===void 0&&x(le)},[n,r]),G=C.useCallback(()=>{H(!b)},[b,H]);C.useEffect(()=>{if(!b)return;function le(Oe){Oe.key==="Escape"&&H(!1)}return window.addEventListener("keydown",le),()=>{window.removeEventListener("keydown",le)}},[b,H]);const[K,X]=C.useState(""),ne=le=>{X(le.target.value)};function ce({sql:le,cardTitle:Oe,connectionId:ke,cardType:Ie,python:We,cardConfig:Te,dataSource:Ue,customVisualPreferences:et,visualizationMode:xt,dynamicCardPreferences:dt}){if(!S)return;const St=xt==="dynamic",Ot=Ea(Te),bt=ke||(Ue==null?void 0:Ue.connectionId)||"",an=Ue?{...Ue,connectionId:bt||Ue.connectionId,connectionType:Ue.connectionType||"",mode:Ue.mode||"database",selectedEntities:Ue.selectedEntities||[]}:bt?{connectionId:bt,connectionType:"",mode:"database",selectedEntities:[]}:qy,Tt=!Ot||!St||(dt==null?void 0:dt.provenance)!=="card-config",Ce=Tt?le:"",rt=Tt?We:"",ct={id:vr(),title:Oe||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Ie==="horizontalBar"?"y":"x"},...St&&{displayOptions:{showChrome:!1,allowScroll:!1}}},type:Ie,sql:Ce,python:rt,dataSource:an,config:Te,connectionId:bt,visualizationMode:xt,dynamicCardPreferences:dt,customCardPreferences:et?{url:et.url,componentName:et.componentName,pluginChartType:et.pluginChartType,settings:et.settings,type:"component"}:void 0},pn={id:vr(),cards:[ct],activeCardId:ct.id};T(!0),j(S,pn,"end"),k(pn.id)}const ee=le=>{le.preventDefault();const Oe=K.trim();if(!Oe&&L.length===0)return;const ke=[];Oe&&ke.push({type:"text",text:Oe}),L.forEach(Ie=>{Ie.data&&ke.push({type:"file",mediaType:Ie.type,filename:Ie.name,url:`data:${Ie.type};base64,${Ie.data}`})}),$({role:"user",parts:ke}),X(""),M("dashboard"),he({force:!0})};C.useEffect(()=>{var le;e&&((le=w.current)==null||le.focus())},[e]),Ole({assistantType:"dashboard",status:Y,isLoading:D,sendMessage:$});const{hasActiveTools:ie,activeToolText:re}=zle(q),{visibleMessages:de,hasMoreMessages:Me,totalMessageCount:Ne,loadMoreMessages:je,resetMessageWindow:fe}=$le(q,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:_e,contentRef:we,isAtBottom:oe,hasNewMessages:ge,newMessageCount:Ee,scrollToBottom:he,handleScroll:me,resetNewMessageCount:Pe}=Lle(de,{threshold:40,behavior:"smooth",isStreaming:D});function ye(le){const Oe={role:"user",parts:[{type:"text",text:le.title+" "+le.subtitle}]};$(Oe)}function ve(le){$({role:"user",parts:[{type:"text",text:le}]})}function Le(le){$({role:"user",parts:[{type:"text",text:le}]}),he({force:!0})}const $e=C.useCallback(async()=>{const le=JSON.stringify(q??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(le),qe.success("Conversation copied")}catch(Oe){console.error("Failed to copy conversation",Oe),qe.error("Unable to copy conversation")}},[q]),Ye=(K==null?void 0:K.length)===0&&(q==null?void 0:q.filter(le=>le.role==="user").length)===0;function Ke(){return l.jsx("div",{"data-role":"header",children:l.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function Ze(){return l.jsxs(xd,{children:[l.jsx(bd,{asChild:!0,children:l.jsx($u,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:l.jsx(_h,{className:"size-3.5"})})}),l.jsxs(Wc,{align:"end",children:[l.jsx(Rf,{children:"Options"}),l.jsx(Xu,{}),l.jsx(hu,{checked:o,onCheckedChange:i,children:"Token Usage"}),l.jsx(hu,{checked:a,onCheckedChange:c,children:"Tool Invocations"}),l.jsx(hu,{checked:u,onCheckedChange:d,children:"System Message"}),(y||v)&&l.jsxs(l.Fragment,{children:[l.jsx(Xu,{}),l.jsx(Rf,{children:"Dynamic Visuals"}),l.jsx(hu,{checked:f==="auto",onCheckedChange:()=>h("auto"),children:"Auto"}),l.jsx(hu,{checked:f==="force",onCheckedChange:()=>h("force"),children:"Force Dynamic"}),l.jsx(hu,{checked:f==="off",onCheckedChange:()=>h("off"),children:"Disable Dynamic"})]})]})]})}const st=l.jsxs("div",{"data-role":"dashboard-assistant",className:J("flex h-full grow flex-col justify-between break-words px-6 py-4",b&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[l.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Ke(),z&&l.jsx(se,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:z,children:(U==null?void 0:U.name)||"Default Profile"}),l.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[v&&Ze(),a&&l.jsx(se,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:$e,children:"Copy Conversation"}),l.jsx($u,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:b?"Exit Fullscreen":"Expand",onClick:G,children:b?l.jsx(HA,{className:"size-4"}):l.jsx(hN,{className:"size-4"})}),l.jsx($u,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{const le=q.filter(Oe=>Oe.role==="assistant").map(Oe=>Oe.id).filter(Oe=>!!Oe);Q([]),P("dashboard"),B(),_(le),fe()},children:l.jsx(pN,{className:"size-4"})}),l.jsx($u,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:l.jsx(Dt,{className:"size-4"})})]})]}),l.jsxs(Ua,{"data-role":"dashboard-assistant-scroll-area",ref:_e,className:"mt-4 flex min-w-0 flex-1 basis-0 flex-col justify-end pr-2",onScroll:me,children:[l.jsxs("div",{ref:we,className:"min-w-0 space-y-3 pb-4",children:[Me&&l.jsx("div",{className:"flex justify-center py-2",children:l.jsxs(se,{variant:"outline",size:"sm",onClick:je,className:"text-xs",children:["Load ",Math.min(5,Ne-de.length)," ","more messages (",Ne-de.length," ","hidden)"]})}),l.jsx(hae,{showTools:a,showSystemMessage:u,messages:de,onAddToDashboard:ce,onQuickReply:Le,disableQuickReplies:D}),l.jsx(fae,{status:Y,errorMessage:Z,activeToolText:D&&ie?re:void 0})]}),l.jsx(Fa,{orientation:"horizontal"})]}),e&&!oe&&l.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:l.jsxs(se,{onClick:()=>{he({force:!0}),Pe()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[l.jsx(pr,{className:"h-4 w-4"}),ge&&Ee>0&&l.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:Ee>9?"9+":Ee})]})}),l.jsxs("div",{className:"space-y-3",children:[!U&&Ye&&l.jsx(mae,{onClick:ye,placeholders:nft}),l.jsx("div",{children:Ye&&U&&l.jsx(Mle,{seedQuestions:U.seedQuestions||[],handleSeedQuestionClick:ve})}),l.jsx(Ple,{assistantType:"dashboard",className:"mb-3"}),l.jsx(Z5,{ref:w,setInput:X,stop:V,input:K,handleInputChange:ne,handleSubmit:le=>{ee(le),he({force:!0})},isLoading:D,status:Y,assistantType:"dashboard",onFocus:()=>{}})]}),l.jsx(K5,{incomingSelectedEntities:A,open:m,onOpenChange:p,dataSource:O||qy,dialogMode:"aiContext",saveAsDashboardDefault:!0,onSaveSelectedEntities:le=>W()})]});return b&&s?mr.createPortal(l.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:l.jsx("div",{className:"flex h-full w-full",children:st})}),s):st}function sft(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=en(),o=te(d=>d.dashboard.sheets),a=te(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),c=te(d=>d.isDashboardEditing),u=te(d=>d.isVisualEditing);C.useEffect(()=>{if(!c||u)return;async function d(m){const p=m.ctrlKey||m.metaKey;p&&m.key==="c"?(await f(),qe.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=kre(p),x=g.cards.findIndex(b=>b.id===g.activeCardId);x!==-1&&(g.cards[x].title=`${g.cards[x].title} (Copy)`),r(a,g),s(g.id),qe.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,c,u,t])}function oft(e,t){switch(e.interactionMode){case"drillToDetail":ift(e,t);break;case"drillThrough":aft(e,t);break;case"drillToURL":lft(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 ift(e,t){var c;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=((c=t.getCurrentFilters)==null?void 0:c.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 aft(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))||"",c=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:c,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:c,filters:i,contextMode:r})}function lft(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 cft({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return l.jsx(Ur,{open:e,onOpenChange:t,children:l.jsxs(Tr,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[l.jsxs(Ir,{children:[l.jsx(_r,{children:i||"Insight Detail"}),l.jsx(is,{children:a||"View detailed insight data with applied filters"})]}),l.jsx(tse,{filters:r,filterDefinitions:s,contextMode:o}),l.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?l.jsx(gse,{insightId:n,filters:r,contextMode:o}):l.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function uft(){const e=Vt(w=>w.interactionStates),t=Vt(w=>w.setInteractionState),n=Vt(w=>w.clearLastInteractionEvent),r=Vt(w=>w.replaceCardWithInsight),s=Vt(w=>w.setPendingDrillThrough),o=Vt(w=>w.pendingDrillThrough),i=Vt(w=>w.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:c}=en(),{selectDashboard:u}=eg(),d=te(w=>w.dashboard),f=te(w=>w.filterValues),{data:h,isLoading:m}=mq((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[p,g]=C.useState({open:!1,insightId:""}),x=xse(p.insightId,{enabled:p.open&&!!p.insightId}),b=C.useRef(new Set),y=C.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:w,filters:S,contextMode:N})=>{g({open:!0,insightId:w,filters:S,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:N})},replaceCardContent:({cardId:w,insightId:S,filters:N,contextMode:j})=>{r(w,S,N,j)},getCurrentFilters:()=>f||[],navigateWithDrill:c,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:w,contextMode:S,sourceDashboardId:N,sourceDashboardTitle:j,targetDashboardId:k})=>{const E={sourceCardId:pa,interactionMode:"clickFilter",filterGroups:[{filters:w}]},I={...Vi(),appliedClickFilters:[E],contextMode:S,sourceDashboardId:N,sourceDashboardTitle:j,targetDashboardId:k};t(pa,I)}}),[a,r,f,c,d,s,t]);C.useEffect(()=>{Object.entries(e).forEach(([w,S])=>{if(S!=null&&S.lastInteractionEvent){const N=S.lastInteractionEvent,j=`${w}-${N.interactionMode}-${N.sourceCardId}-${Date.now()}`;if(b.current.has(j))return;b.current.add(j);try{oft(N,y)}catch(k){console.error("Error executing interaction event:",k)}finally{n(w),setTimeout(()=>{b.current.delete(j)},5e3)}}})},[e,n,y]),C.useEffect(()=>{if(!(!o||!h||m))try{u(h),c(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(w){console.error("[DrillThrough] Error during automatic navigation:",w),i()}},[o,h,m,u,c,i]);const v=()=>{g({open:!1,insightId:""})};return l.jsxs(l.Fragment,{children:[l.jsx(cft,{open:p.open,onOpenChange:v,insightId:p.insightId,filters:p.filters,filterDefinitions:p.filterDefinitions,contextMode:p.contextMode,cardTitle:x.title,cardDescription:x.description}),o&&m&&l.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:l.jsxs("div",{className:"flex flex-col items-center gap-2.5 rounded-[6px] border border-border/60 bg-background px-4 py-3 shadow-sm",children:[l.jsx(Mn,{className:"h-5 w-5 animate-spin text-muted-foreground/60"}),l.jsx("div",{className:"text-[12px] text-muted-foreground",children:"Loading dashboard..."})]})})]})}function dft(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=fft(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function fft(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function hft(e){return e?`Back to ${e}`:"Back"}function mft(){var b,y,v,w,S;const e=Vt(N=>N.interactionStates[pa]),t=te(N=>N.actions.goBackFromDrill),n=te(N=>N.actions.clearDrillContext),{selectDashboard:r}=eg(),[s,o]=C.useState({x:16,y:16}),[i,a]=C.useState(!1),c=C.useRef({x:0,y:0});C.useEffect(()=>{if(!i)return;const N=k=>{o({x:k.clientX-c.current.x,y:k.clientY-c.current.y})},j=()=>{a(!1)};return document.addEventListener("mousemove",N),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",N),document.removeEventListener("mouseup",j)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((w=(v=(y=(b=e==null?void 0:e.appliedClickFilters)==null?void 0:b[0])==null?void 0:y.filterGroups)==null?void 0:v[0])==null?void 0:w.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||!((S=e.appliedClickFilters)!=null&&S.length))return null;const m=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(N){console.error("[DrillBack] Error during back navigation:",N)}},p=()=>{n()},g=N=>{N.target.closest("button")||(a(!0),c.current={x:N.clientX-s.x,y:N.clientY-s.y})};dft(f);const x=hft(d);return l.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:l.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:[l.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[l.jsxs("div",{className:"flex flex-col gap-2",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),l.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((N,j)=>{const k=N.field.label||N.field.name,T=String(N.value);return l.jsxs(Xe,{variant:"secondary",className:"pointer-events-none text-xs",children:[k," = ",T]},j)})})]}),l.jsx(se,{variant:"ghost",size:"sm",onClick:p,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:l.jsx(Dt,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:l.jsxs(se,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[l.jsx(PU,{className:"mr-2 h-4 w-4"}),x]})})]})})}function pft(e,t){return typeof e=="boolean"?e:typeof t=="boolean"?t:!1}function Vle(){var Ne,je;const{showAssistant:e,tokenProps:t}=nt(),n=pft((Ne=t.config)==null?void 0:Ne.showDashboardAssistant,e),{preferences:r,isConsoleMode:s}=lg(),o=((je=r==null?void 0:r.cardDisplay)==null?void 0:je.mode)==="print",i=C.useRef(null),a=C.useRef(null),[c,u]=C.useState(!1),{handleDragStart:d,isDraggingRef:f,getStyle:h,getPositionClasses:m}=ZZe({initialPosition:"bottom-right"}),p=zf(fe=>fe.setFullscreen),g=zf(fe=>fe.setPanelOpen),x=zf(fe=>fe.setContainer),b=tJ("dashboard"),y=nJ(),v=rJ("dashboard"),w=b.isOpen,S=y==="dashboard",N=te(fe=>fe.isVisualEditing),j=te(fe=>fe.themeStyle),k=te(fe=>{var _e;return(_e=fe.dashboard)==null?void 0:_e.sheets}),T=te(fe=>fe.showFilters),E=te(fe=>fe.isDashboardEditing),I=te(fe=>fe.selectedSheetId),_=te(fe=>{var _e,we;return((we=(_e=fe.dashboard)==null?void 0:_e.summary)==null?void 0:we.position)||"top"}),P=te(fe=>{var _e;return(_e=fe.dashboard)==null?void 0:_e.id}),M=te(fe=>fe.isDashboardPanelOpen),R=te(fe=>fe.actions.setIsDashboardPanelOpen),L=j==null?void 0:j.controlInputRadius,{getDefaultSheetId:O,setDefaultSheetId:U,clearDefaultSheetId:z}=DU(P),[A,W]=C.useState(null);IN(Qr.DASHBOARD);const{setSelectedSheetId:$,setSheetTitle:D,addSheet:q,setSheets:Q}=en();sft(a);const{setActiveAssistantType:Y}=tN();C.useEffect(()=>{if(P){const fe=O();W(fe)}},[P,O]),C.useEffect(()=>{w?Y("dashboard"):y==="dashboard"&&p(null)},[w,Y,y,p]),C.useEffect(()=>{var fe;w||(fe=i.current)==null||fe.resize(0)},[w]);function V(fe){var _e,we;fe?((_e=i.current)==null||_e.resize(40),g("dashboard",!0),p("dashboard"),Y("dashboard")):(g("dashboard",!1),p(null),(we=i.current)==null||we.resize(0),Y(null))}function Z(){const fe={id:vr(),title:"New Sheet"};q(fe),$(fe.id)}function B(fe,_e){if(!P)return;A===fe?(z(),W(null),qe.success("Default sheet cleared")):(U(fe),W(fe),qe.success(`"${_e}" set as default sheet`))}function H(fe){var _e;fe<1?(g("dashboard",!1),p(null),Y(null),(_e=i.current)==null||_e.resize(0)):(w||g("dashboard",!0),Y("dashboard"))}function G(){return(j==null?void 0:j.canvasTheme)==="muted"||!(j!=null&&j.canvasTheme)?"hsl(var(--semaphor-muted))":(j==null?void 0:j.canvasTheme)==="clear"?"":j==null?void 0:j.canvasTheme}const K=(fe,_e)=>{fe.dataTransfer.setData("tabIndex",_e.toString())},X=fe=>{fe.preventDefault()},ne=(fe,_e)=>{const we=fe.dataTransfer.getData("tabIndex");if(we===_e.toString())return;const oe=Array.from(k||[]),[ge]=oe.splice(parseInt(we),1);oe.splice(_e,0,ge),Q(oe)},ce=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail,ee=n===!0&&!o&&!w&&!N&&!T;function ie(){if(k&&k.length>1||E)return l.jsxs(ws,{role:"tab-list",className:"flex h-12 w-0 min-w-full items-center justify-start gap-2 overflow-x-auto rounded-none bg-transparent px-3",children:[s&&ce&&!M&&l.jsx(se,{style:{borderRadius:L},variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{R(!M)},className:"h-9 shrink-0 px-3",children:l.jsx(XU,{className:"h-4 w-4"})}),k==null?void 0:k.map((fe,_e)=>{const we=I===fe.id,oe=A===fe.id;return l.jsxs(on,{draggable:!0,onDragStart:ge=>K(ge,_e),onDragOver:X,onDrop:ge=>ne(ge,_e),style:{borderRadius:L},onClick:()=>$(fe.id),className:"flex h-9 shrink-0 items-center gap-1 bg-transparent px-3 py-1 text-muted-foreground transition-colors hover:bg-muted/50 hover:text-foreground data-[state=active]:bg-muted data-[state=active]:font-medium data-[state=active]:text-foreground",value:fe.id,children:[l.jsx(hS,{enabled:E&&we,text:fe.title,onSave:ge=>D(fe.id,ge),children:fe.title},fe.id),!E&&we&&l.jsx("div",{title:oe?"Clear default sheet":"Set as default sheet",children:l.jsx(KA,{className:J("ml-1 size-3 cursor-pointer transition-all",oe?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:ge=>{ge.stopPropagation(),B(fe.id,fe.title||"Sheet")}})}),E&&we&&k.length>1&&l.jsx(Dt,{className:"ml-1 size-3",onClick:()=>u(!0)})]},fe.id)}),E&&l.jsx(se,{style:{borderRadius:L},variant:"outline","aria-label":"Add sheet",className:"h-9 shrink-0 border-transparent bg-transparent px-3 text-muted-foreground hover:bg-muted/50 hover:text-foreground",onClick:Z,children:l.jsx(Br,{className:"size-4"})})]})}function re(){return l.jsx("div",{ref:a,style:{},className:"grow",children:k==null?void 0:k.map(fe=>l.jsx(sr,{style:{backgroundColor:G()},className:J("mt-0",{}),value:fe.id,children:l.jsx(vZe,{sheet:fe})},fe.id))})}function de(){var fe;return l.jsxs(Fs,{"data-role":"dashboard-tabs-container",className:J("relative flex h-full flex-col",j==null?void 0:j.dashboardTabsContainer),onValueChange:_e=>{$(_e)},value:I||((fe=k==null?void 0:k[0])==null?void 0:fe.id),children:[ie(),_==="top"&&l.jsx(FD,{}),l.jsx(Ua,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:re()}),_==="bottom"&&l.jsx(FD,{}),l.jsx(XZe,{open:c,setOpen:u})]})}const Me=C.useCallback(fe=>{x("dashboard",fe)},[x]);return k?l.jsxs(l.Fragment,{children:[l.jsx(uft,{}),l.jsx(mft,{}),l.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[l.jsxs(Koe,{className:J("flex-1 basis-0 overflow-y-auto transition-opacity",S&&"pointer-events-none opacity-0"),direction:"horizontal",children:[l.jsx(tM,{children:de()}),n===!0&&l.jsxs(l.Fragment,{children:[l.jsx(KZe,{open:w,onTabClick:V,withHandle:!0,disabled:!w}),l.jsx(tM,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:H,defaultSize:w?40:0,ref:i,children:l.jsx("div",{className:"grow overflow-y-auto",children:l.jsx(rft,{open:w,setOpen:V,isFullscreen:S,onFullscreenChange:fe=>p(fe?"dashboard":null),fullscreenContainer:v})})})]})]}),l.jsx("div",{ref:Me,className:J("absolute inset-0",!S&&"pointer-events-none")}),ee&&l.jsx("div",{className:J("absolute z-50 transition-all duration-300 ease-in-out",m().horizontal,m().vertical),style:h(),children:l.jsx(se,{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:()=>{f.current||V(!0)},onMouseDown:d,onTouchStart:d,title:"Open Assistant (drag to move)",children:l.jsx(Ope,{className:"h-5 w-5"})})})]})]}):null}const Ble=C.forwardRef(({children:e,className:t,...n},r)=>l.jsx("div",{className:J("semaphor-scope",t),ref:r,...n,children:e}));function X5({children:e}){return l.jsx(Ble,{style:{height:"100%",width:"100%"},children:l.jsx(Mme,{defaultTheme:"system",storageKey:"vite-ui-theme",children:l.jsx(wr,{delayDuration:0,children:e})})})}function Ule({children:e,preferences:t}){const{currentUser:n}=zo(),r=C.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 l.jsx(GW.Provider,{value:r,children:l.jsx(qO,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function gft(e=2e3,t=500){const n=ape(),[r,s]=C.useState(!1),[o,i]=C.useState(!1),a=C.useRef(null);return C.useEffect(()=>{const c=setTimeout(()=>s(!0),e);return()=>clearTimeout(c)},[e]),C.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 Q5({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=gft(e,t);return C.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]),l.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 Hle(e){if(typeof window>"u")return null;const{preferences:t}=e;return l.jsx(Oa,{FallbackComponent:tE,children:l.jsxs(_A,{dashboardProps:e,children:[l.jsx(Q5,{componentType:"dashboard",componentId:e.id}),l.jsx(X5,{children:l.jsx(Ule,{preferences:t,children:l.jsx("main",{className:"flex h-full flex-col",children:l.jsx(QF,{...e,type:"dashboard",children:l.jsx(Vle,{})})})})})]})})}function xft(e){return!!e.expression}function bft(e){if(e)return e.startsWith("card-source-")?e.replace("card-source-",""):e}function yft(e){const t=bft(e);return t?t.startsWith("calc_")||t.startsWith("calc_dim_"):!1}function Wle(e){return e.fieldScope==="domain"&&e.entityName===mo||e.entityName===Ao||e.qualifiedEntityName===Ao}function vft(e){return Wle(e)}function wft(e){return e.entityName===mo||(e.fieldScope==="dashboard"||e.fieldScope==="card")&&yft(e.id)&&!e.entityName}function hd(e){return xft(e)?vft(e)?"domain_calculated":wft(e)?"user_calculated":"inline_expression":"none"}function Jg(e){return hd(e)!=="none"}function Sa(e){if(!Jg(e))return!1;const t=hd(e);return t==="domain_calculated"||t==="user_calculated"?!0:e.fieldScope==="domain"||e.fieldScope==="dashboard"||e.fieldScope==="card"}function qle(e){return Sa(e)&&e.fieldScope!=="card"}function Gle(e,t,n){return Jg(e)?t==="editor"?!0:t==="filter"?Sa(e)&&e.fieldScope!=="card":Sa(e)&&(n==null?void 0:n.isValuePickSafe)!==!1:!1}function pB(e,t){return e.map(n=>({...n,fieldScope:t}))}function Yle(){const{columns:e,columnGroups:t,isLoading:n,hasError:r,error:s,refetch:o}=o5(),i=Ve(S=>S.frame.calculatedFields),a=Ve(S=>S.card.calculatedFields),c=Ve(S=>S.card.config),u=te(S=>S.dashboard),d=te(S=>S.selectedSheetId),f=te(S=>S.selectedFrameId),h=te(S=>S.isVisualEditing),m=C.useMemo(()=>e.filter(S=>hd(S)==="domain_calculated"),[e]),p=C.useMemo(()=>e.filter(S=>hd(S)!=="domain_calculated"),[e]),g=C.useMemo(()=>{var N;const S=(N=u==null?void 0:u.sheets)==null?void 0:N.find(j=>j.id===d);return hme(S,f)},[u==null?void 0:u.sheets,f,d]),x=C.useMemo(()=>{const S=h?i||[]:g;return S.length?pB(S,"dashboard"):[]},[i,h,g]),b=C.useMemo(()=>fme(x),[x]),y=C.useMemo(()=>{const S=(a||[]).filter(E=>Sa(E)&&E.fieldScope!=="domain"),N=((c==null?void 0:c.metricColumns)||[]).filter(E=>Sa(E)&&E.fieldScope!=="domain"),j=((c==null?void 0:c.groupByColumns)||[]).filter(E=>Sa(E)&&E.fieldScope!=="domain"),T=nU([...S,...N,...j]).filter(E=>!b.has(df(E)));return pB(T,"card").map(E=>({...E,id:`card-source-${E.id}`}))},[a,c==null?void 0:c.groupByColumns,c==null?void 0:c.metricColumns,b]),v=C.useMemo(()=>[...m,...x,...y,...p],[y,p,x,m]),w=C.useMemo(()=>t.filter(S=>S.entityId!==j7),[t]);return{columns:e,columnGroups:w,rawColumnGroups:t,columnFields:p,domainCalculatedFields:m,dashboardCalculatedFields:x,cardCalculatedFields:y,scopedFields:v,isLoading:n,hasError:r,error:s,refetch:o}}function wm(e){const t=new Map;return e.forEach(n=>{const r=Jg(n)?(()=>{const s="expression"in n&&n.expression||"",o=n.qualifiedEntityName||n.entityName||"";return s?["calculated",n.fieldScope||"physical",n.role||"field",o,n.qualifiedFieldName||n.name,s].join("::"):["calculated",n.fieldScope||"physical",n.role||"field",o,tC(n.id)||n.qualifiedFieldName||n.name].join("::")})():["physical",n.fieldScope||"physical",n.role||"field",n.qualifiedEntityName||"",n.qualifiedFieldName||n.name,n.name].join("::");t.has(r)||t.set(r,n)}),Array.from(t.values())}function J5(e){return!f0(e)}function GT(e,t){return wm(e.filter(n=>Gle(n,t,{isValuePickSafe:J5(n)})))}function Cft(e){return!Jg(e)||Gle(e,"inline-filter",{isValuePickSafe:J5(e)})}function Sft(e){return!Jg(e)||qle(e)}function Kle(){const e=Yle(),t=C.useMemo(()=>wm(e.scopedFields),[e.scopedFields]),n=C.useMemo(()=>wm([...e.columns,...e.dashboardCalculatedFields]),[e.columns,e.dashboardCalculatedFields]),r=C.useMemo(()=>wm(n.filter(Sft)),[n]),s=C.useMemo(()=>GT(t,"editor"),[t]),o=C.useMemo(()=>GT(n.filter(qle),"filter"),[n]),i=C.useMemo(()=>wm(t.filter(J5)),[t]),a=C.useMemo(()=>wm(i.filter(Cft)),[i]),c=C.useMemo(()=>GT(a,"inline-filter"),[a]);return{...e,filterableFields:t,sharedFilterableFields:n,dashboardFilterableFields:r,inlineFilterableFields:a,scopedCalculatedFields:s,sharedCalculatedFields:o,inlineCalculatedFields:c,valuePickFilterableFields:i}}function eL(e){const{tokenProps:t,authToken:n}=nt(),r=t==null?void 0:t.apiServiceUrl;return qt({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return or(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 Zle(e,t,n){if(t==="source")return{isValid:!0};const r=wn(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 Xle(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 Nft(e,t){return(e||[]).map(n=>({...n,id:t(n),label:n.label!==void 0?n.label:n.name}))}const jft=new Set(["COUNT","DISTINCT"]),Eft=new Set(["running_total","moving_average","previous_period_delta"]);function kft(e){return wn(e.dataType||"")==="number"?!0:e.aggregate?jft.has(e.aggregate.toUpperCase()):!1}function Tft(e,t){var r,s;return!!((s=(r=e.parameters)==null?void 0:r.windowTransform)==null?void 0:s.function)}function tL(e,t){var n,r;return e==="aggregateTable"&&((((n=t.rowAggregates)==null?void 0:n.length)??0)>0||(((r=t.columnAggregates)==null?void 0:r.length)??0)>0)}function Qle({cardType:e,cardConfig:t,metric:n,transformMode:r}){var i,a,c;if(e==="detailTable"||e==="kpi")return{supported:!1,reason:"Metric transforms are not supported for this card type."};if((((i=t.groupByColumns)==null?void 0:i.length)??0)===0)return{supported:!1,reason:"Metric transforms require at least one grouped dimension."};if(!kft(n))return{supported:!1,reason:"Metric transforms are only available for numeric metrics."};const s=(((a=t.pivotByColumns)==null?void 0:a.length)??0)>0,o=e==="pivotTable"||tL(e,t);return s&&!o?{supported:!1,reason:"Metric transforms with pivot dimensions are only supported for pivotTable and subtotal-enabled aggregateTable in V1."}:Eft.has(r)&&(((c=t.groupByColumns)==null?void 0:c.length)??0)===0?{supported:!1,reason:"This transform requires grouped dimensions for ordering."}:{supported:!0}}function Ift(e){return e.find(t=>wn(t.dataType||"")==="date")}function _ft(e){return e}function Ob({cardType:e,cardConfig:t,orderByFieldId:n}){const r=(t.groupByColumns||[]).filter(o=>o.id&&o.id!==n).map(o=>o.id),s=[];if(e==="pivotTable"||tL(e,t))for(const o of t.pivotByColumns||[])o.id&&s.push(o.id);return Array.from(new Set([...r,...s]))}function Dft({transformMode:e,cardType:t,cardConfig:n,fallbackOrderByFieldId:r}){var i;const s=r||((i=Ift(n.groupByColumns||[]))==null?void 0:i.id),o=Ob({cardType:t,cardConfig:n,orderByFieldId:s});return e==="moving_average"?{function:"moving_average",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,movingAverage:{windowSize:7,minPeriods:1}}:e==="previous_period_delta"?{function:"previous_period_delta",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,previousPeriodDelta:{mode:"absolute"}}:e==="percent_of_total"?{function:"percent_of_total",percentOfTotal:{scope:"grand_total",output:"percent"},partitionByFieldIds:[]}:{function:"running_total",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,frame:"unbounded_preceding"}}const Mft=new Set(["table","aggregateTable","pivotTable","detailTable"]);function Aft(e){return e.alias||e.label||e.name}function Jle(e,t,n){var a,c,u;if(!e)return null;const r=ki(t.format);if(!r)return null;const s=n||{};let o=s,i=!1;if(Mft.has(e.type)){const d=Q7(r),f=Aft(t);if(d&&!((c=(a=s.tablePrefs)==null?void 0:a.columnSettingsMap)==null?void 0:c[f])){const m=Hs();o={...o,tablePrefs:{...o.tablePrefs||{},columnSettingsMap:{...((u=o.tablePrefs)==null?void 0:u.columnSettingsMap)||{},[f]:{...m,type:"number",textAlign:"right",numberFormat:{...m.numberFormat,...d}}}}},i=!0}if(!s.formatNumber){const h=sme(r);h&&(o={...o,formatNumber:{decimalPlaces:h.decimalPlaces,minimumFractionDigits:h.minimumFractionDigits,maximumFractionDigits:h.maximumFractionDigits,currency:h.currency,locale:h.locale,prefix:h.prefix,suffix:h.suffix,useGrouping:h.useGrouping,percentValueMode:h.percentValueMode,enabled:!0}},i=!0)}}return i?o:null}const ece=e=>{var Q;const t=(Q=e==null?void 0:e.dataSource)==null?void 0:Q.semanticDomainId,{data:n}=eL(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:c,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f,setCardPreferences:h}=lr(),m=Ve(Y=>Y.card.type),p=e==null?void 0:e.id,g=(Y,V)=>{if(Y.id)return Y.id;const Z=Y.qualifiedEntityName||Y.entityName||V;return`${V}-${Z}-${Y.name}`},x=C.useCallback(Y=>{if(!(e!=null&&e.config))return[];switch(Y){case"groupBy":return(e.config.groupByColumns||[]).map(V=>({...V,id:g(V,"groupBy"),label:V.label!==void 0?V.label:V.name}));case"metrics":return(e.config.metricColumns||[]).map(V=>({...V,id:g(V,"metrics"),label:V.label!==void 0?V.label:V.name}));case"pivotBy":return(e.config.pivotByColumns||[]).map(V=>({id:g(V,"pivotBy"),name:V.name,dataType:V.dataType,label:V.label!==void 0?V.label:V.name,qualifiedEntityName:V.qualifiedEntityName,entityId:V.entityId,entityName:V.entityName,entityType:V.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map(V=>({id:g(V,"sortBy"),name:V.name,dataType:V.dataType,label:V.label!==void 0?V.label:V.name,qualifiedEntityName:V.qualifiedEntityName,entityId:V.entityId,entityName:V.entityName,entityType:V.entityType,direction:V.direction}));case"detailColumns":return Nft(e.config.detailColumns,V=>g(V,"detailColumns"));case"source":return[];default:return[]}},[e]),b=C.useCallback((Y,V)=>{if(p)switch(Y){case"groupBy":{r(p,{groupByColumns:V});break}case"metrics":{r(p,{metricColumns:V});break}case"pivotBy":{r(p,{pivotByColumns:V});break}case"sortBy":{r(p,{sortByColumns:V});break}case"detailColumns":{r(p,{detailColumns:V});break}}},[p,r]),y=C.useCallback((Y,V,Z)=>{if(!p)return;const B=x(Y),H=B[V];if(H)switch(Y){case"groupBy":s(p,H.id,{label:Z});break;case"metrics":o(p,H.id,{label:Z});break;case"pivotBy":i(p,H.id,{label:Z});break;case"sortBy":a(p,H.id,{label:Z});break;case"detailColumns":{const G=B.map((K,X)=>X===V?{...K,label:Z}:K);r(p,{detailColumns:G});break}}},[p,x,s,o,i,a,r]),v=C.useCallback((Y,V)=>{if(!p)return;const B=x("metrics")[Y];B&&o(p,B.id,{aggregate:V,label:kZ(B.name,V)})},[p,x,o]),w=C.useCallback((Y,V,Z,B="groupBy")=>{if(!p)return;const H=x(B),G=H[Y];if(!G)return;const K={dateFormat:V,customFormat:V==="custom"&&Z?Z:void 0};if(B==="detailColumns"){const X=H.map((ne,ce)=>ce===Y?{...ne,...K}:ne);r(p,{detailColumns:X});return}s(p,G.id,K)},[p,x,r,s]),S=C.useCallback((Y,V)=>{if(!p)return;const B=x("groupBy")[Y];B&&s(p,B.id,{granularity:V})},[p,x,s]),N=C.useCallback((Y,V)=>{if(!p)return;const B=x("metrics")[Y];B&&o(p,B.id,{aliasTemplate:V})},[p,x,o]),j=C.useCallback((Y,V)=>{if(console.log("handleValueAliasesChange",Y,V),!p)return;console.log("handleValueAliasesChange",Y,V);const B=x("metrics")[Y];B&&(console.log("handleValueAliasesChange",V),o(p,B.id,{valueAliases:V}))},[p,x,o]),k=C.useCallback((Y,V)=>{var H,G;if(!p)return;const B=x("metrics")[Y];B&&(o(p,B.id,{format:V}),m==="kpi"&&((G=(H=e==null?void 0:e.preferences)==null?void 0:H.kpiVisualOptions)!=null&&G.formatOptions)&&h({...e.preferences,kpiVisualOptions:{...e.preferences.kpiVisualOptions,formatOptions:void 0}}))},[e,p,m,x,h,o]),T=C.useCallback((Y,V)=>{var G;if(!p)return;const B=x("metrics")[Y];if(!B)return;const H=V!=="none"&&((G=B.parameters)==null?void 0:G.windowTransform);o(p,B.id,{comparisonType:V,...V!=="target"?{targetValue:void 0}:{},...H?{parameters:{...B.parameters||{},windowTransform:void 0}}:{}})},[p,x,o]),E=C.useCallback((Y,V)=>{var ce,ee,ie;if(!p||!(e!=null&&e.config))return;const B=x("metrics")[Y];if(!B)return;if(V==="none"){o(p,B.id,{parameters:{...B.parameters||{},windowTransform:void 0}});return}const H=Qle({cardType:m,cardConfig:e.config,metric:B,transformMode:V});if(!H.supported){qe.error(H.reason||"Metric transform is not supported here.");return}const G=new Set((e.config.groupByColumns||[]).map(re=>re.id)),K=(ie=(ee=(ce=B.parameters)==null?void 0:ce.windowTransform)==null?void 0:ee.orderBy)==null?void 0:ie.fieldId,X=K&&G.has(K)?K:void 0,ne=Dft({transformMode:V,cardType:m,cardConfig:e.config,fallbackOrderByFieldId:X});o(p,B.id,{comparisonType:"none",targetValue:void 0,parameters:{...B.parameters||{},windowTransform:ne}})},[e,p,m,x,o]),I=C.useCallback((Y,V)=>{var ne,ce;if(!p||!(e!=null&&e.config))return;const B=x("metrics")[Y];if(!B)return;const H=(ne=B.parameters)==null?void 0:ne.windowTransform;if(!H||!["running_total","moving_average","previous_period_delta"].includes(H.function))return;const G=Ob({cardType:m,cardConfig:e.config,orderByFieldId:V}),X=(H.partitionByFieldIds||G).filter(ee=>ee!==V);o(p,B.id,{parameters:{...B.parameters||{},windowTransform:{...H,orderBy:{fieldId:V,direction:((ce=H.orderBy)==null?void 0:ce.direction)||"asc"},partitionByFieldIds:X}}})},[e,p,m,x,o]),_=C.useCallback((Y,V)=>{var G;if(!p)return;const B=x("metrics")[Y];if(!B)return;const H=(G=B.parameters)==null?void 0:G.windowTransform;!H||!["running_total","moving_average","previous_period_delta"].includes(H.function)||o(p,B.id,{parameters:{...B.parameters||{},windowTransform:{...H,orderBy:H.orderBy?{...H.orderBy,direction:V}:H.orderBy}}})},[p,x,o]),P=C.useCallback((Y,V)=>{var X,ne;if(!p||!(e!=null&&e.config))return;const B=x("metrics")[Y];if(!B)return;const H=(X=B.parameters)==null?void 0:X.windowTransform;if(!H)return;const G=Ob({cardType:m,cardConfig:e.config,orderByFieldId:(ne=H.orderBy)==null?void 0:ne.fieldId}),K=new Set(H.partitionByFieldIds||G);K.has(V)?K.delete(V):K.add(V),o(p,B.id,{parameters:{...B.parameters||{},windowTransform:{...H,partitionByFieldIds:Array.from(K)}}})},[e,p,m,x,o]),M=C.useCallback((Y,V)=>{var ne,ce;if(!p)return;const B=x("metrics")[Y];if(!B)return;const H=(ne=B.parameters)==null?void 0:ne.windowTransform;if(!H||H.function!=="moving_average")return;const G=Math.max(1,Math.floor(V||1)),K=((ce=H.movingAverage)==null?void 0:ce.minPeriods)||1,X=Math.min(K,G);o(p,B.id,{parameters:{...B.parameters||{},windowTransform:{...H,movingAverage:{windowSize:G,minPeriods:X}}}})},[p,x,o]),R=C.useCallback((Y,V)=>{var X,ne;if(!p)return;const B=x("metrics")[Y];if(!B)return;const H=(X=B.parameters)==null?void 0:X.windowTransform;if(!H||H.function!=="moving_average")return;const G=((ne=H.movingAverage)==null?void 0:ne.windowSize)||7,K=Math.max(1,Math.min(Math.floor(V||1),G));o(p,B.id,{parameters:{...B.parameters||{},windowTransform:{...H,movingAverage:{windowSize:G,minPeriods:K}}}})},[p,x,o]),L=C.useCallback((Y,V)=>{var G;if(!p)return;const B=x("metrics")[Y];if(!B)return;const H=(G=B.parameters)==null?void 0:G.windowTransform;!H||H.function!=="previous_period_delta"||o(p,B.id,{parameters:{...B.parameters||{},windowTransform:{...H,previousPeriodDelta:{mode:V}}}})},[p,x,o]),O=C.useCallback((Y,V)=>{var K;if(!p||!(e!=null&&e.config))return;const B=x("metrics")[Y];if(!B)return;const H=(K=B.parameters)==null?void 0:K.windowTransform;if(!H||H.function!=="percent_of_total")return;const G=V==="grand_total"?[]:(H.partitionByFieldIds||[]).length>0?H.partitionByFieldIds||[]:Ob({cardType:m,cardConfig:e.config,orderByFieldId:void 0});o(p,B.id,{parameters:{...B.parameters||{},windowTransform:{...H,partitionByFieldIds:G,percentOfTotal:{...H.percentOfTotal||{},scope:V}}}})},[e,p,m,x,o]),U=C.useCallback((Y,V)=>{var G;if(!p)return;const B=x("metrics")[Y];if(!B)return;const H=(G=B.parameters)==null?void 0:G.windowTransform;!H||H.function!=="percent_of_total"||o(p,B.id,{parameters:{...B.parameters||{},windowTransform:{...H,percentOfTotal:{...H.percentOfTotal||{},output:V}}}})},[p,x,o]),z=C.useCallback(Y=>{p&&r(p,{showTrendline:Y})},[p,r]),A=C.useCallback(Y=>{p&&r(p,{trendlineWindow:Y})},[p,r]),W=C.useCallback(Y=>{p&&r(p,{trendlineGranularity:Y})},[p,r]),$=C.useCallback((Y,V)=>{if(!p)return;const B=x("metrics")[Y];B&&o(p,B.id,{targetValue:V})},[p,x,o]),D=C.useCallback(async Y=>{var ne;if(!p)return;const V=[...x("groupBy"),...x("pivotBy"),...x("metrics"),...x("sortBy"),...x("detailColumns")],Z=Y,B=V_e(Z,V,{joinPlan:(ne=e==null?void 0:e.config)==null?void 0:ne.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!B.isValid){B.showError&&wZ();return}const H=Q_e(Z,V,m);if(!H){qe.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const G=Zle(Z,H,m);if(!G.isValid){qe.error("Invalid Field Type",{description:G.reason,position:"top-center",duration:3e3});return}const K=x(H);if(CZ(Z,K))return;const X=TZ(Z,H,K);if(X){const ce=[...K,X];if(b(H,ce),H==="metrics"){const ee=Jle(e,X,e==null?void 0:e.preferences);ee&&h(ee),Xle(m,e==null?void 0:e.config,r,p,ce)}}},[p,e,x,b,t,n,m,r,h]),q=C.useCallback((Y,V)=>{if(!p)return;const B=x(Y)[V];if(B){if(Y!=="sortBy"){const H=x("sortBy"),G=H.filter(K=>!(K.name===B.name&&K.qualifiedEntityName===B.qualifiedEntityName));G.length!==H.length&&r(p,{sortByColumns:G})}switch(Y){case"groupBy":c(p,B.id);break;case"metrics":u(p,B.id);break;case"pivotBy":d(p,B.id);break;case"sortBy":f(p,B.id);break;case"detailColumns":{r(p,{detailColumns:(x("detailColumns")||[]).filter((H,G)=>G!==V)});break}}}},[p,x,c,u,d,f,r]);return{getFieldsForContainer:x,setFieldsForContainer:b,updateLabel:y,handleAggregationChange:v,handleDateFormatChange:w,handleGranularityChange:S,handleAliasTemplateChange:N,handleValueAliasesChange:j,handleMetricFormatChange:k,removeField:q,handleFieldClick:D,handleMetricComparisonChange:T,handleMetricWindowTransformChange:E,handleMetricWindowOrderByChange:I,handleMetricWindowDirectionChange:_,handleMetricWindowPartitionToggle:P,handleMetricMovingAverageWindowSizeChange:M,handleMetricMovingAverageMinPeriodsChange:R,handleMetricPreviousPeriodDeltaModeChange:L,handleMetricPercentOfTotalScopeChange:O,handleMetricPercentOfTotalOutputChange:U,handleKpiShowTrendlineChange:z,handleKpiTrendlineWindowChange:A,handleKpiTrendlineGranularityChange:W,handleMetricTargetValueChange:$,cardType:m}};function RE(e,t){var ye,ve,Le,$e,Ye,Ke,Ze,st;const{tokenProps:n}=nt(),r=ds(),s=nt().authToken||e,o=Ve(le=>le.selectedConnectionId),i=Ve(le=>le.card),{queryKey:a}=c1e(i),c=Ve(le=>le.selectedDatamodelId),u=Ve(le=>le.isDevMode),d=Ve(le=>le.selectedDatabaseName),f=Ve(le=>le.selectedSchemaName),h=Ve(le=>le.selectedTableName),m=Ve(le=>le.actions.setSelectedConnectionId),p=Ve(le=>le.actions.setSelectedDatamodelId),g=Ve(le=>le.actions.setSelectedDatabaseName),x=Ve(le=>le.actions.setSelectedSchemaName),b=Ve(le=>le.actions.setSelectedTableName);Ve(le=>le.actions.setCardSql);const{setQueryConfig:y}=lr();function v(le){var Te;if(!o||!le)return!1;const Oe=((Te=T==null?void 0:T.capabilities)==null?void 0:Te.path)||[],ke=Oe.includes("database"),Ie=Oe.includes("schema");return!(!Oe.includes("table")||ke&&(!d||d==="NA")||Ie&&!f)}function w(le){var Oe;return!o||!le?!1:!!((Oe=T==null?void 0:T.capabilities)!=null&&Oe.path.includes("database"))}const{refetchConnections:S,connectionsData:N,isConnectionsLoading:j,isConnectionsError:k,selectedConnection:T}=Ti(e),{refetch:E,data:I,isLoading:_,isError:P}=qt({queryKey:["models",o],queryFn:()=>or(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),M=T==null?void 0:T.type,R=((ye=T==null?void 0:T.capabilities)==null?void 0:ye.path.includes("schema"))??!1,L=((ve=T==null?void 0:T.capabilities)==null?void 0:ve.path.length)===1&&((Le=T==null?void 0:T.capabilities)==null?void 0:Le.path[0])==="table",O=L,{data:U,isLoading:z,isFetching:A,isError:W,refetch:$}=qt({queryKey:["databases",o],queryFn:()=>or(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:w(M)}),{data:D,isLoading:q,isFetching:Q,isError:Y,refetch:V}=qt({queryKey:["schemas",o,d],queryFn:()=>or(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&R&&d!=="NA"}),{data:Z,isLoading:B,isFetching:H,isError:G,refetch:K}=qt({queryKey:["tables",o,d,f],queryFn:()=>or(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(M)}),{columns:X,isColumnsLoading:ne,isColumnsFetching:ce,isColumnsError:ee,refetchColumns:ie}=_Z(e);C.useEffect(()=>{L&&(g(""),x(""),p(""),M==="API"&&b("api"))},[M,b,g,x,p,L]);const re=(T==null?void 0:T.type)==="API"?($e=T==null?void 0:T.type)==null?void 0:$e.toLowerCase():h||"",de=R&&f||"";function Me(le){b(le),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function Ne(le){x(le),b("")}function je(le){g(le==="none"?"":le),x(""),b(""),le!=="none"&&le!==""&&p("")}function fe(le){m(le)}function _e(le){p(le==="none"?"":le),le!=="none"&&le!==""&&g("")}U&&((Ye=U==null?void 0:U.databases)==null?void 0:Ye.length)>0,D&&((Ke=D==null?void 0:D.schemas)==null?void 0:Ke.length)>0;const we=N==null?void 0:N.connections.map(le=>({id:le.id,name:le.name,type:le.type})),oe=(Ze=I==null?void 0:I.datamodels)==null?void 0:Ze.map(le=>({id:le.id,name:le.name})),ge=U==null?void 0:U.databases.map(le=>({id:le.database_name,name:le.database_name})),Ee=D==null?void 0:D.schemas.map(le=>({id:le.schema_name,name:le.schema_name})),he=Z==null?void 0:Z.tables.map(le=>({id:le.table_name,name:le.table_name})),me=(st=I==null?void 0:I.datamodels.find(le=>le.id===c))==null?void 0:st.name,Pe=T!=null&&T.capabilities?X1({schemaName:de,tableName:re,modelName:me,databaseName:d||"",capabilities:T.capabilities}):re;return{connectionItems:we,selectedConnectionId:o,selectedConnection:T,isConnectionsLoading:j,isConnectionsError:k,modelItems:oe,selectedDatamodelId:c,selectedDatamodelName:me,isModelsLoading:_,isModelsError:P,selectedDatabaseName:d,databaseItems:ge,isDatabasesLoadingOrFetching:z||A,isDatabaseError:W,schemaItems:Ee,selectedSchemaName:f,isSchemaLoadingOrFetching:q||Q,isSchemaError:Y,tableItems:he,selectedTableName:h,isTableLoadingOrFetching:B||H,isTableError:G,columns:X,isColumnsLoadingOrFetching:ne||ce,isColumnsError:ee,isNonDbConnection:O,connectionType:M,tableName:re,formattedTableName:Pe,schemaName:de,refetchConnections:S,refetchModels:E,refetchDatabases:$,refetchSchemas:V,refetchTables:K,refetchColumns:ie,handleConnectionChange:fe,handleDatamodelChange:_e,handleDatabaseChange:je,handleSchemaChange:Ne,handleTableChange:Me}}function c1(e){return`${e}-${vr()}`}function gB(e,t){const n=Pl(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 Rft(e,t){const n=Pl(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"quarter":return`Quarter of ${n}`;case"year":return`Year of ${n}`;case"hour":return`Hour of ${n}`;case"minute":return`Minute of ${n}`;case"second":return`Second of ${n}`;default:return n}}function nL(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 tce(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function nce(){const e=Ve(j=>j.sqlGen),t=Ve(j=>j.isDevMode),n=Ve(j=>j.card.dataSource),r=Ve(j=>{var k,T;return(T=(k=j.card)==null?void 0:k.queryConfig)==null?void 0:T.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=nL(n),a=tce(n),c=Ve(j=>j.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:m,setIsShowingVisual:p}=lr(),{modelItems:g,selectedDatamodelName:x}=RE(),{selectedConnection:b}=Ti(),y=b==null?void 0:b.capabilities,v=j=>({column_name:j.name,data_type:j.dataType,label:j.label,description:j.description});return{handleDevModeFieldClick:j=>{var T;if(!t)return;const k=v(j);if(t&&a&&s&&y){const E=nA(k,e);m(E);const I=(T=g==null?void 0:g.find(P=>P.id===c))==null?void 0:T.name,_=tA(E,o||"",s,I||"",i||"",y,j.qualifiedEntityName);_&&(f(_),h(!0))}else if(!t){if(l0(k.data_type))if(r&&r.length>0){const E={...k,role:"groupby",id:c1(k.column_name),name:k.column_name,type:k.data_type};d(E)}else{const E={...k,role:"metric",id:c1(k.column_name),name:k.column_name,label:gB(k.column_name,"COUNT"),type:k.data_type,aggregate:"COUNT"};u(E)}if(ja(k.data_type)){const E={...k,role:"groupby",id:c1(k.column_name),name:k.column_name,type:k.data_type,label:Rft(k.column_name,"month"),granularity:"month"};d(E)}if(Na(k.data_type)){const E={...k,role:"metric",id:c1(k.column_name),name:k.column_name,label:gB(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=X1({schemaName:o||"",tableName:s,modelName:x,databaseName:i||"",capabilities:y});p(!1);const T=(b==null?void 0:b.type)==="MSSQL"?`SELECT top 10 * FROM ${j}`:`SELECT * FROM ${j} LIMIT 10`;f(T),h(!0)},handleShowCount:()=>{if(!a||!s||!y){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const j=X1({schemaName:o||"",tableName:s,modelName:x,databaseName:i||"",capabilities:y});f(`SELECT COUNT(*) as count FROM ${j}`),h(!0)},isNumberField:j=>Na(j.dataType)}}function Fft(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 rce(e){const t=e;return{id:e.id,name:e.name,qualifiedFieldName:e.qualifiedFieldName,qualifiedEntityName:e.qualifiedEntityName,entityName:e.entityName,entityId:e.entityId,entityType:e.entityType,dataType:e.dataType,role:e.role,fieldScope:e.fieldScope,expression:t.expression,calculatedFormula:t.calculatedFormula}}function sce(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 HS(e){var t,n;return e?!!(e.entityName===mo||e.expression||(n=(t=e.calculatedFormula)==null?void 0:t.inputFields)!=null&&n.length):!1}function xB(e){return e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e}function Zy(e,t){var g,x,b,y,v,w,S;if(!e.fieldMeta)return e.column===t.qualifiedFieldName||e.column===t.name;const n=xB((g=e.fieldMeta)==null?void 0:g.id),r=xB(t.id),s=((x=e.fieldMeta)==null?void 0:x.qualifiedFieldName)||e.column,o=s===t.qualifiedFieldName||s===t.name,i=(b=e.fieldMeta)==null?void 0:b.qualifiedEntityName,a=!i||!t.qualifiedEntityName||i===t.qualifiedEntityName,c=(y=e.fieldMeta)==null?void 0:y.entityId,u=!c||!t.entityId||c===t.entityId,d=(v=e.fieldMeta)==null?void 0:v.fieldScope;if(d&&t.fieldScope&&d!==t.fieldScope)return!1;const f=(w=e.fieldMeta)==null?void 0:w.role;if(f&&t.role&&f!==t.role)return!1;const h=HS(e.fieldMeta)||HS(t);if(h&&n&&r&&n===r)return!0;if(!h&&(!a||!u))return!1;const m=(S=e.fieldMeta)==null?void 0:S.expression,p=t.expression;return m||p?o&&a&&u&&m===p:o&&a&&u}function oce(){const e=te(c=>c.dashboard.filters)||[],t=te(c=>c.selectedSheetId),n=te(c=>c.actions.addFilter),r=te(c=>c.actions.removeFilter),{removeFilterValues:s}=en(),o=Ve(c=>c.card.dataSource),{selectedConnection:i}=Ti();function a(c,u="sheet"){const{qualifiedColumnName:d,qualifiedTableName:f,formattedColumnName:h}=Fft(c);let m;if(u==="sheet"&&t){const p=Xl(e,t);m=p.find(g=>g.fieldMeta&&Zy(g,c))||FPe(p.filter(g=>!g.fieldMeta),d,f,t)}else m=e==null?void 0:e.find(p=>Zy(p,c)||!p.fieldMeta&&Lp(p.column)===Lp(d));if(m)s(m.id),r(m.id);else{const p=vr(),g=rce(c),x=sce(o,{connectionId:i==null?void 0:i.id,connectionType:i==null?void 0:i.type}),b=HS(g),y=u==="sheet"&&t?[t]:void 0,v=wn(c.dataType)==="date"?"between":"in";return n({id:p,location:u,column:d,title:c.label||c.name,dataType:c.dataType,qualifiedTableName:f,connectionId:(i==null?void 0:i.id)||"",operation:v,applyToSheetIds:y,sql:b?"":rne(c.dataType,f,h),fieldMeta:g,semanticContext:x}),p}}return{assignFilter:a}}function Pft({column:e}){const[t,n]=C.useState(!1),r=Ve(v=>v.isDevMode),s=Ve(v=>v.card.dataSource),{tableName:o,schemaName:i,databaseName:a}=nL(s),c=Ve(v=>v.selectedDatamodelId),u=Ve(v=>v.sqlGen),{modelItems:d,selectedConnection:f}=RE(),h=f==null?void 0:f.capabilities,m=Ve(v=>v.actions.setSqlGen),p=Ve(v=>v.actions.setCardSql),g=Ve(v=>v.actions.setRunSql),x=tce(s);function b(v,w){var T,E;if(!x||!o){console.warn("Cannot generate SQL: missing table metadata");return}const S=nA(v,u,w),N=(T=d==null?void 0:d.find(I=>I.id===c))==null?void 0:T.name;if(m(S),!h){console.warn("Cannot generate SQL: missing connection capabilities");return}const j=(E=v.qualifiedFieldName)==null?void 0:E.split(".").slice(0,-1).join("."),k=tA(S,i||"",o,N||"",a||"",h,j);k&&(p(k),g(!0)),n(!1)}function y(){return l.jsxs("ul",{className:"text-xs",children:[l.jsx("li",{onClick:()=>b(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),l.jsx("li",{onClick:()=>b(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),l.jsx("li",{onClick:()=>b(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),l.jsx("li",{onClick:()=>b(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),l.jsx("li",{onClick:()=>b(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return!r||!x?null:l.jsxs(Yc,{openDelay:0,open:t,onOpenChange:n,children:[l.jsx(Kc,{asChild:!0,children:l.jsx(_h,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),l.jsx(Aa,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:y()})]})}const ice="absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 font-mono text-[7px] font-semibold leading-none shadow-sm",bB="bg-emerald-500/90 text-white",Oft="bg-blue-500/90 text-white";function ace(e){const t=hd(e);return t==="none"?null:t==="inline_expression"?{label:"{}",badgeClassName:bB}:{label:"fx",badgeClassName:e.role==="metric"?bB:Oft}}function Lft(e){if(!e)return[];const t=[{label:"Type",value:e.type}];if("locale"in e&&e.locale&&t.push({label:"Locale",value:e.locale}),e.prefix&&t.push({label:"Prefix",value:e.prefix}),e.suffix&&t.push({label:"Suffix",value:e.suffix}),e.type==="date")return e.pattern&&t.push({label:"Pattern",value:e.pattern}),e.timezone&&t.push({label:"Timezone",value:e.timezone}),e.sourceTimezone&&t.push({label:"Source TZ",value:e.sourceTimezone}),e.relative!==void 0&&t.push({label:"Relative",value:e.relative?"On":"Off"}),t;if("minimumFractionDigits"in e||"maximumFractionDigits"in e){const n=e.minimumFractionDigits,r=e.maximumFractionDigits;if(n!==void 0||r!==void 0){const s=n!==void 0&&r!==void 0?n===r?`${n}`:`${n}-${r}`:`${n??"auto"}-${r??"auto"}`;t.push({label:"Decimals",value:s})}}return"useGrouping"in e&&e.useGrouping!==void 0&&t.push({label:"Grouping",value:e.useGrouping?"On":"Off"}),"currency"in e&&e.currency&&t.push({label:"Currency",value:e.currency}),"percentValueMode"in e&&e.percentValueMode&&t.push({label:"Percent Input",value:e.percentValueMode}),"negativeStyle"in e&&e.negativeStyle&&t.push({label:"Negative Style",value:e.negativeStyle}),"compact"in e&&e.compact!==void 0&&t.push({label:"Compact",value:e.compact?"On":"Off"}),"scale"in e&&e.scale!==void 0&&t.push({label:"Scale",value:String(e.scale)}),t}function $ft(e){var n;if(!e.expression)return null;const t=((n=e.calculatedFormula)==null?void 0:n.inputFields)||[];return t.length?e.expression.replace(/\{field_(\d+)\}/g,(r,s)=>{const o=t[Number(s)];return o?`{${o.name||o.label}}`:r}):e.expression}function zft({field:e,fieldState:t}){const n=$ft(e),r=Lft(e.format);return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[l.jsx("h3",{className:"text-[13px] font-medium text-foreground",children:e.label||e.name}),l.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-[11px] text-muted-foreground",children:e.dataType})]}),e.description&&l.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:e.description}),n&&l.jsxs("div",{className:"mb-3 rounded bg-muted/50 p-2",children:[l.jsx("p",{className:"mb-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:"Expression"}),l.jsx("code",{className:"block whitespace-pre-wrap break-all font-mono text-xs text-foreground",children:n})]}),r.length>0&&l.jsxs("div",{className:"mb-3 rounded bg-muted/50 p-2",children:[l.jsx("p",{className:"mb-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:"Format"}),l.jsx("div",{className:"space-y-0.5",children:r.map(s=>l.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[l.jsx("span",{className:"text-muted-foreground",children:s.label}),l.jsx("span",{className:"font-mono text-foreground",children:s.value})]},`${s.label}-${s.value}`))})]}),t&&t.tooltip&&l.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:l.jsx("p",{className:"text-xs text-muted-foreground",children:t.tooltip})}),l.jsx("div",{className:"overflow-x-auto border-t border-border pt-2",children:l.jsx("span",{className:"font-mono text-[11px] text-muted-foreground",children:e.name})})]})}function yB({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s,actions:o}){const i=Ve(G=>G.isDevMode),a=t==="filter"||t==="inline-filter",c=i||a||(n==null?void 0:n.state)==="unreachable"&&!a,u=te(G=>G.dashboard.filters),d=te(G=>G.selectedSheetId),f=te(G=>G.actions.removeFilter),{removeFilterValues:h}=en(),{assignFilter:m}=oce(),p=t==="filter"?Xl(u,d):u,g=t==="filter"?p==null?void 0:p.find(G=>{if(Zy(G,e))return!0;if(G.fieldMeta)return!1;const K=Lp(G.column||""),X=Lp(e.name);return K.endsWith(`.${X}`)||K===X}):void 0,x=!!g,b=t==="inline-filter"&&(s==null?void 0:s.some(G=>Zy(G,e))),y=x||b,v=g&&a?u==null?void 0:u.find(G=>G.id===g.id):void 0,w=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:w,selectedSheetId:d});const[S,N]=C.useState(!1),[j,k]=C.useState(null),{attributes:T,listeners:E,setNodeRef:I,transform:_,transition:P,isDragging:M}=Yg({id:e.id,disabled:c}),[R,L]=C.useState(!1),O=Ve(G=>G.card),{handleFieldClick:U}=ece(O),{handleDevModeFieldClick:z,isNumberField:A}=nce(),W=()=>{v&&(console.log("[SourceField] Removing multi-sheet filter:",v.id),h(v.id),f(v.id)),k(null),N(!1)},$=()=>{if(t==="inline-filter"&&r){r(e);return}t==="filter"?y&&w?(k(e),N(!0)):m(e,"sheet"):i?z(e):U(e)},D={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},q={transform:ji.Transform.toString(_),transition:P},Q=()=>{if(!n||a)return{};const K={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",...K},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...K},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...K}}[n.state]||K};function Y(G){return G==="domain"?{label:"Semantic domain",Icon:Vpe,className:"text-foreground/55 hover:text-foreground/85"}:G==="dashboard"?{label:"Dashboard",Icon:VA,className:"text-foreground/55 hover:text-foreground/85"}:{label:"Card",Icon:tH,className:"text-foreground/55 hover:text-foreground/85"}}const V=Q(),Z=e.fieldScope,B=Z?Y(Z):null,H=ace(e);return l.jsxs("div",{ref:I,style:q,...c?{}:T,...c?{}:E,className:J("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",M&&"scale-95 opacity-50",!M&&"border",V.borderColor||"border-transparent",V.bgColor||"",V.hoverBorderColor,V.hoverBgColor||"hover:bg-muted",V.opacity,V.cursor,x&&"border-accent-foreground/20 bg-accent",b&&"border-primary/20 bg-primary/10",{"cursor-pointer":i||a,"cursor-grab active:cursor-grabbing":!c&&!i&&!a}),title:n==null?void 0:n.tooltip,children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:$,children:[l.jsxs("div",{className:"relative shrink-0",children:[bh(e.dataType),H&&l.jsx("span",{className:J(ice,H.badgeClassName),children:H.label})]}),l.jsxs(Yc,{openDelay:200,closeDelay:100,children:[l.jsx(Kc,{asChild:!0,children:l.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:l.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${R?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),l.jsx(Aa,{side:"bottom",align:"start",className:"ml-5 w-72 p-3",children:l.jsx(zft,{field:e,fieldState:n})})]}),i&&!a&&A(e)&&l.jsx("div",{onClick:G=>G.stopPropagation(),children:l.jsx(Pft,{column:D})}),t==="editor"&&B&&l.jsxs("div",{className:"ml-auto flex items-center",onClick:G=>G.stopPropagation(),onPointerDown:G=>G.stopPropagation(),children:[o&&l.jsx("div",{className:"mr-1 flex items-center opacity-0 transition-opacity pointer-events-none group-hover/container:opacity-100 group-hover/container:pointer-events-auto group-focus-within/container:opacity-100 group-focus-within/container:pointer-events-auto [@media(hover:none)]:opacity-100 [@media(hover:none)]:pointer-events-auto",children:o}),l.jsxs(Nn,{children:[l.jsx(jn,{asChild:!0,children:l.jsx("span",{"aria-label":`${B.label} calculated field`,title:"",className:J("block p-0.5 transition-colors",B.className),children:l.jsx(B.Icon,{className:"h-3.5 w-3.5"})})}),l.jsxs(Dn,{side:"top",align:"end",children:[B.label," calculated field"]})]})]}),o&&(!B||t!=="editor")&&l.jsx("div",{className:"ml-auto flex items-center",onClick:G=>G.stopPropagation(),onPointerDown:G=>G.stopPropagation(),children:o})]}),R&&l.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:l.jsx(wi,{className:"",children:l.jsxs(Ia,{className:"space-y-2 p-3",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(nH,{className:"h-4 w-4 text-muted-foreground"}),l.jsx("span",{className:"break-all",children:e.label||e.name})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Ype,{className:"h-4 w-4 text-muted-foreground"}),l.jsx("span",{className:"break-all",children:e.name})]}),l.jsx(Xe,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),l.jsx(Gc,{open:S,onOpenChange:N,children:l.jsxs(zl,{children:[l.jsxs(Vl,{children:[l.jsx(Ul,{children:"Remove Filter from Multiple Sheets?"}),l.jsx(Hl,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),l.jsxs(Bl,{children:[l.jsx(ql,{children:"Cancel"}),l.jsx(Wl,{onClick:W,children:"Remove Filter"})]})]})})]})}var qa="Accordion",Vft=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[rL,Bft,Uft]=x0(qa),[FE]=fs(qa,[Uft,BX]),sL=BX(),lce=C.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return l.jsx(rL.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?l.jsx(Gft,{...o,ref:t}):l.jsx(qft,{...s,ref:t})})});lce.displayName=qa;var[cce,Hft]=FE(qa),[uce,Wft]=FE(qa,{collapsible:!1}),qft=C.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,c]=As({prop:n,defaultProp:r??"",onChange:s,caller:qa});return l.jsx(cce,{scope:e.__scopeAccordion,value:C.useMemo(()=>a?[a]:[],[a]),onItemOpen:c,onItemClose:C.useCallback(()=>o&&c(""),[o,c]),children:l.jsx(uce,{scope:e.__scopeAccordion,collapsible:o,children:l.jsx(dce,{...i,ref:t})})})}),Gft=C.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i,a]=As({prop:n,defaultProp:r??[],onChange:s,caller:qa}),c=C.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=C.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return l.jsx(cce,{scope:e.__scopeAccordion,value:i,onItemOpen:c,onItemClose:u,children:l.jsx(uce,{scope:e.__scopeAccordion,collapsible:!0,children:l.jsx(dce,{...o,ref:t})})})}),[Yft,PE]=FE(qa),dce=C.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=C.useRef(null),c=Et(a,t),u=Bft(n),f=pd(s)==="ltr",h=Ge(e.onKeyDown,m=>{var k;if(!Vft.includes(m.key))return;const p=m.target,g=u().filter(T=>{var E;return!((E=T.ref.current)!=null&&E.disabled)}),x=g.findIndex(T=>T.ref.current===p),b=g.length;if(x===-1)return;m.preventDefault();let y=x;const v=0,w=b-1,S=()=>{y=x+1,y>w&&(y=v)},N=()=>{y=x-1,y<v&&(y=w)};switch(m.key){case"Home":y=v;break;case"End":y=w;break;case"ArrowRight":o==="horizontal"&&(f?S():N());break;case"ArrowDown":o==="vertical"&&S();break;case"ArrowLeft":o==="horizontal"&&(f?N():S());break;case"ArrowUp":o==="vertical"&&N();break}const j=y%b;(k=g[j].ref.current)==null||k.focus()});return l.jsx(Yft,{scope:n,disabled:r,direction:s,orientation:o,children:l.jsx(rL.Slot,{scope:n,children:l.jsx(lt.div,{...i,"data-orientation":o,ref:c,onKeyDown:r?void 0:h})})})}),WS="AccordionItem",[Kft,oL]=FE(WS),fce=C.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=PE(WS,n),i=Hft(WS,n),a=sL(n),c=Vr(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return l.jsx(Kft,{scope:n,open:u,disabled:d,triggerId:c,children:l.jsx(WX,{"data-orientation":o.orientation,"data-state":bce(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});fce.displayName=WS;var hce="AccordionHeader",mce=C.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=PE(qa,n),o=oL(hce,n);return l.jsx(lt.h3,{"data-orientation":s.orientation,"data-state":bce(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});mce.displayName=hce;var TM="AccordionTrigger",pce=C.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=PE(qa,n),o=oL(TM,n),i=Wft(TM,n),a=sL(n);return l.jsx(rL.ItemSlot,{scope:n,children:l.jsx($Me,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});pce.displayName=TM;var gce="AccordionContent",xce=C.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=PE(qa,n),o=oL(gce,n),i=sL(n);return l.jsx(zMe,{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}})});xce.displayName=gce;function bce(e){return e?"open":"closed"}var Zft=lce,Xft=fce,Qft=mce,yce=pce,vce=xce;const OE=Zft,qp=F.forwardRef(({className:e,...t},n)=>l.jsx(Xft,{ref:n,className:J("border-b",e),...t}));qp.displayName="AccordionItem";const Gp=F.forwardRef(({className:e,children:t,...n},r)=>l.jsx(Qft,{className:"flex",children:l.jsxs(yce,{ref:r,className:J("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,l.jsx(pr,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));Gp.displayName=yce.displayName;const Yp=F.forwardRef(({className:e,children:t,...n},r)=>l.jsx(vce,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:l.jsx("div",{className:J("pb-4 pt-0",e),children:t})}));Yp.displayName=vce.displayName;let wce=(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 Xy=[{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}],iL=e=>e.trim().toLowerCase().replace(/\s+/g,"_"),of=e=>e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e;function Cce(e,t){e.forEach(n=>{var i;const r=n.id||n.qualifiedFieldName||n.name;if(r&&t.visited.has(r))return;if(r&&t.visited.add(r),Wle(n)){t.disqualified=!0;return}const s=(i=n.calculatedFormula)==null?void 0:i.inputFields;if(s!=null&&s.length){Cce(s,t);return}if(n.expression&&!(hd(n)==="inline_expression"&&Sa(n)&&n.fieldScope==="domain")){t.disqualified=!0;return}if(!n.entityName||!n.entityId){t.disqualified=!0;return}const o=n.qualifiedEntityName||n.entityId||n.entityName;t.entities.has(o)||t.entities.set(o,{entityName:n.entityName,entityId:n.entityId,qualifiedEntityName:n.qualifiedEntityName})})}function aL(e){const t={entities:new Map,disqualified:!1,visited:new Set};if(Cce(e,t),t.disqualified||t.entities.size!==1)return{kind:"multi-entity"};const[n]=Array.from(t.entities.values());return!(n!=null&&n.entityName)||!n.entityId?{kind:"multi-entity"}:{kind:"inline",entityName:n.entityName,entityId:n.entityId,qualifiedEntityName:n.qualifiedEntityName}}const vB="calculated_fields";function Jft(e){return e?e.startsWith("calc_")||e.startsWith("calc_dim_"):!1}function eht(e){return e.fieldScope==="domain"||e.fieldScope==="dashboard"||e.fieldScope==="card"||e.entityName===mo||e.entityName===vB||e.qualifiedEntityName===vB||Jft(e.id)}function tht(e){return e.aggregate?e.aggregate:NZ(e.dataType)}function nht(e,t){const n=tht(t);return n==="DISTINCT"?`COUNT(DISTINCT ${e})`:`${n}(${e})`}function rht(e,t){return e.replace(/\{field_(\d+)\}/g,(n,r)=>{const s=Number(r),o=t[s];return!o||eht(o)||typeof o.expression=="string"&&SZ(o.expression)?n:nht(n,o)})}function wB(e,t,n,r,s,o,i,a,c,u){const d=Xy.find(y=>y.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(c===void 0||Number.isNaN(c))throw new Error("Constant factor is required for scale operation");f=d.template().replace("{constant}",String(c)),h=[n],m=c}else{if(!n||!r)throw new Error("Metrics A and B are required for standard operations");f=d.template(),h=[n,r]}t!=="custom"&&(f=rht(f,h));const p={operation:t,inputFields:h,...m!==void 0&&{constant:m}},g=iL(e),x=aL(h);return{id:i||`calc_${wce(10)}`,name:g,label:e,alias:g,qualifiedFieldName:g,dataType:"number",role:"metric",expression:f,calculatedFormula:p,entityId:x.kind==="inline"?x.entityId:o,entityName:x.kind==="inline"?x.entityName:mo,qualifiedEntityName:x.kind==="inline"?x.qualifiedEntityName:void 0,entityType:x.kind==="inline"?"dataset":"table",description:`Calculated field: ${e}`}}function sht(e){var r,s;const t=Xy.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 oht(e,t,n,r,s,o){const i=iL(e),a=aL(n);return jZ({id:o||`calc_dim_${wce(10)}`,name:i,label:e.trim(),alias:i,qualifiedFieldName:i,dataType:r,role:"groupby",expression:t.trim(),calculatedFormula:{operation:"custom",inputFields:n.map(c=>c.role==="metric"?{...c,role:"metric"}:{...c,role:"groupby"})},entityId:a.kind==="inline"?a.entityId:s,entityName:a.kind==="inline"?a.entityName:mo,qualifiedEntityName:a.kind==="inline"?a.qualifiedEntityName:void 0,entityType:a.kind==="inline"?"dataset":"table",description:`Calculated field: ${e.trim()}`})}function iht({value:e,onChange:t,disabled:n,options:r=["dimension","metric"]}){const s=r.length>0?r:["dimension","metric"],o=["dimension","metric"].filter(c=>s.includes(c)),i=n||o.length<=1,a=o.includes(e)?e:o[0];return l.jsx(Fs,{value:a,onValueChange:c=>t(c),className:"w-full",children:l.jsx(ws,{className:"grid w-full",style:{gridTemplateColumns:`repeat(${o.length}, minmax(0, 1fr))`},children:o.map(c=>l.jsx(on,{value:c,disabled:i,children:c==="metric"?"Calculated Metric":"Calculated Dimension"},c))})})}function aht({groups:e,searchTerm:t,onSearchTermChange:n,onFieldClick:r,selectedFieldIds:s,disabled:o}){const i=new Set(s||[]),a=e.length>0||t.length>0,c=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 x of g){const b=u(p,x);if(b!==p)return b}return p.includes(".")&&p.split(".").pop()||p};return l.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3 border-r border-border pr-4",children:[a&&l.jsxs("div",{className:"relative",children:[l.jsx(Gs,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),l.jsx(at,{value:t,onChange:f=>n(f.target.value),placeholder:"Search fields...",className:"pl-10 pr-10"}),t&&l.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:l.jsx(Dt,{className:"size-3.5"})})]}),l.jsx(Ua,{className:"min-h-0 flex-1",children:e.length===0?l.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."}):l.jsx(OE,{type:"multiple",defaultValue:c,className:"space-y-2",children:e.map(f=>l.jsxs(qp,{value:f.id,className:"border-none",children:[l.jsx(Gp,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:f.label}),l.jsx(Xe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:f.fields.length})]})}),l.jsx(Yp,{className:"pb-2",children:l.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",x=d(h,f.label);return l.jsxs("button",{type:"button",onClick:()=>h.isCompatible&&!o&&r(h),className:J("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:[l.jsxs("div",{className:"relative shrink-0",children:[bh(h.dataType),h.isCalculated&&l.jsx("span",{className:J("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"})]}),l.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:l.jsx("span",{className:J("block truncate text-sm text-foreground/80",!p&&"group-hover/container:text-foreground"),children:x})}),m&&l.jsx(Xe,{variant:"secondary",className:"shrink-0 text-[10px]",children:"Selected"})]},h.id)})})})]},f.id))})})]})}function lht({value:e,onChange:t,allowCustom:n,disabled:r}){const s=Xy.filter(c=>n?!0:c.id!=="custom"),i=!s.some(c=>c.id==="custom")&&e==="custom"?[...s,Xy.find(c=>c.id==="custom")]:s,a=i.find(c=>c.id===e);return l.jsxs("div",{className:"space-y-2",children:[l.jsxs(mt,{value:e,onValueChange:c=>t(c),disabled:r,children:[l.jsx(ft,{children:l.jsx(gt,{})}),l.jsx(ht,{children:l.jsxs(GF,{children:[l.jsx(gj,{children:"OPERATIONS"}),i.map(c=>l.jsx(De,{value:c.id,children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"font-mono text-sm",children:c.symbol}),l.jsx("span",{children:c.label})]})},c.id))]})})]}),a&&l.jsx("p",{className:"text-xs text-muted-foreground",children:a.description})]})}const cht={COUNT:"Count",DISTINCT:"Count Distinct",SUM:"Sum",AVG:"Average",MIN:"Minimum",MAX:"Maximum",MEDIAN:"Median"};function uht({value:e,onChange:t,disabled:n,fieldDataType:r,allowMedian:s}){const i=(r?wn(r):"number")==="number",a=["SUM","AVG","COUNT","DISTINCT","MIN","MAX"],c=i?s?[...a,"MEDIAN"]:a:["COUNT","DISTINCT"];return l.jsxs(mt,{value:e,onValueChange:u=>t(u),disabled:n,children:[l.jsx(ft,{className:"h-9",children:l.jsx(gt,{})}),l.jsx(ht,{children:c.map(u=>l.jsx(De,{value:u,children:cht[u]},u))})]})}const dht=e=>{const n=(e.name||e.baseLabel||e.label||e.tokenLabel||"").trim();return n.includes(".")&&n.split(".").pop()||n};function CB({label:e,input:t,availableFields:n,excludeFieldIds:r,onFieldSelect:s,onAggregateChange:o,onRemove:i,onActivate:a,allowMedian:c,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 l.jsxs("div",{className:J("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:[l.jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded bg-muted font-mono text-xs font-semibold",children:e}),l.jsxs("div",{className:"flex flex-1 gap-2",children:[l.jsxs(mt,{value:d,onValueChange:h=>{const m=f.find(p=>p.id===h);m&&s(m)},disabled:u,children:[l.jsx(ft,{className:"h-9 flex-1",children:l.jsx(gt,{placeholder:"Select field"})}),l.jsx(ht,{children:f.map(h=>l.jsx(De,{value:h.id,children:dht(h)},h.id))})]}),l.jsx("div",{className:"w-36",children:l.jsx(uht,{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:c})})]}),t&&l.jsx(se,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:h=>{h.stopPropagation(),i()},disabled:u,children:l.jsx(Dt,{className:"h-3.5 w-3.5"})})]})}const SB=C.forwardRef(function({value:t,onChange:n,onGenerate:r,showGenerate:s,docsUrl:o,placeholder:i,disabled:a},c){return l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx(xe,{children:"Expression"}),l.jsxs("div",{className:"flex items-center gap-2",children:[o&&l.jsxs("a",{href:o,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",children:["Docs",l.jsx(pp,{className:"h-3 w-3"})]}),s&&l.jsxs(se,{type:"button",size:"sm",variant:"outline",onClick:r,disabled:a,className:"h-7 text-xs",children:[l.jsx(cC,{className:"mr-1.5 h-3.5 w-3.5"}),"Generate with AI"]})]})]}),l.jsx(ei,{ref:c,value:t,onChange:u=>n(u.target.value),disabled:a,rows:3,placeholder:i||"CASE WHEN {Amount} > 100 THEN 'Large' ELSE 'Small' END",className:"min-h-0 resize-none overflow-y-auto font-mono text-xs leading-5"})]})}),lL=F.forwardRef(({className:e,sideOffset:t=8,...n},r)=>l.jsx(aq,{children:l.jsx(Ble,{children:l.jsx(NR,{ref:r,sideOffset:t,className:J("z-[60] overflow-hidden rounded-lg border bg-popover text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95","data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n})})}));lL.displayName="ValidationTooltipContent";const Sce=lq;function YT(e,t){return`${e} ${t}${e===1?"":"s"}`}function fht({result:e}){const t=e.errors.length>0,n=YT(e.tokens.length,"token"),r=e.errors.length>0?YT(e.errors.length,"error"):null,s=e.warnings.length>0?YT(e.warnings.length,"warning"):null,o=e.errors.map(i=>i.suggestion?`${i.message} (${i.suggestion})`:i.message).join(`
|
|
1393
|
-
`);return l.jsxs(Nn,{delayDuration:120,children:[l.jsx(jn,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":t?"Validation failed. Hover to view details.":"Validation passed. Hover to view details.",className:J("inline-flex h-5 w-5 items-center justify-center rounded-full transition-colors",t?"bg-destructive text-destructive-foreground hover:bg-destructive/90":"bg-emerald-600 text-white hover:bg-emerald-700"),children:t?l.jsx(Dt,{className:"h-3 w-3","aria-hidden":!0}):l.jsx(Zr,{className:"h-3 w-3","aria-hidden":!0})})}),l.jsxs(lL,{side:"top",align:"start",avoidCollisions:!0,collisionPadding:12,className:"w-[min(440px,calc(100vw-32px))] p-0",children:[l.jsxs("div",{className:"space-y-2.5 p-3 text-xs",children:[l.jsx("div",{className:J("font-semibold",t?"text-destructive":"text-emerald-700"),children:t?"Validation failed":"Validation passed"}),l.jsxs("div",{className:"flex flex-wrap gap-x-2 gap-y-1 text-[11px] text-muted-foreground",children:[l.jsx("span",{children:n}),r&&l.jsx("span",{children:r}),s&&l.jsx("span",{children:s}),e.inferredDataType&&l.jsxs("span",{children:["type: ",e.inferredDataType]})]}),e.tokens.length>0&&l.jsxs("div",{className:"space-y-1.5 border-t pt-2",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Tokens"}),l.jsx("div",{className:"max-h-28 space-y-1 overflow-y-auto pr-1 select-text",children:e.tokens.map((i,a)=>l.jsxs("div",{className:"flex items-start gap-1.5",children:[l.jsx("span",{className:"rounded bg-muted px-1.5 py-0.5 font-mono leading-none",children:`{${i.token}}`}),l.jsx(DA,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground"}),i.field?l.jsx("span",{className:"break-all text-muted-foreground",children:i.field.qualifiedFieldName||i.field.name}):l.jsx("span",{className:"text-muted-foreground",children:"Unresolved"})]},`${i.token}-${a}`))})]}),e.errors.length>0&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-destructive",children:"Errors"}),l.jsx(Pc,{text:o,ariaLabel:"Copy validation errors",className:"h-5 w-5 p-0 text-destructive/70 hover:text-destructive"})]}),l.jsx("div",{className:"max-h-32 space-y-1 overflow-y-auto pr-1 text-destructive select-text",children:e.errors.map((i,a)=>l.jsxs("div",{className:"break-words",children:[i.message,i.suggestion?` (${i.suggestion})`:""]},`${i.code}-${a}`))})]}),e.warnings.length>0&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-amber-700",children:"Warnings"}),l.jsx("div",{className:"max-h-32 space-y-1 overflow-y-auto pr-1 text-amber-700 select-text",children:e.warnings.map((i,a)=>l.jsxs("div",{className:"break-words",children:[i.message,i.suggestion?` (${i.suggestion})`:""]},`${i.code}-${a}`))})]}),e.inferredDataType&&l.jsxs("div",{className:"border-t pt-2 text-[11px] text-muted-foreground",children:["Inferred output type:"," ",l.jsx("span",{className:"font-medium text-foreground",children:e.inferredDataType})]})]}),l.jsx(Sce,{className:"fill-popover"})]})]})}function NB({onValidate:e,isValidating:t,validationResult:n,error:r,disabled:s}){return l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(se,{type:"button",variant:"outline",size:"sm",onClick:e,disabled:t||s,children:t?"Validating expression (may take a few seconds)...":"Validate Expression"}),n&&l.jsx(fht,{result:n}),!n&&r&&l.jsxs(Nn,{delayDuration:120,children:[l.jsx(jn,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":"Validation failed. Hover to view details.",className:"inline-flex h-5 w-5 items-center justify-center rounded-full bg-destructive text-destructive-foreground hover:bg-destructive/90",children:l.jsx(Dt,{className:"h-3 w-3","aria-hidden":!0})})}),l.jsxs(lL,{side:"top",align:"start",avoidCollisions:!0,collisionPadding:12,className:"w-[min(420px,calc(100vw-32px))] p-3",children:[l.jsxs("div",{className:"space-y-2 text-xs",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("span",{className:"font-semibold text-destructive",children:"Validation failed"}),l.jsx(Pc,{text:r,ariaLabel:"Copy validation error",className:"h-5 w-5 p-0 text-destructive/70 hover:text-destructive"})]}),l.jsx("p",{className:"max-h-40 overflow-y-auto break-words text-destructive select-text",children:r})]}),l.jsx(Sce,{className:"fill-popover"})]})]})]})}function hht({scope:e,onChange:t,showDashboardScope:n,error:r,disabled:s}){return l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(xe,{children:"Availability"}),l.jsxs(ho,{value:e,onValueChange:o=>t(o),className:"gap-0.5",disabled:s,children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(In,{id:"scope-card",value:"card"}),l.jsx(xe,{htmlFor:"scope-card",className:"text-sm font-normal",children:"This card only"})]}),n&&l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(In,{id:"scope-dashboard",value:"dashboard"}),l.jsx(xe,{htmlFor:"scope-dashboard",className:"text-sm font-normal",children:"All cards on this sheet"})]})]}),r&&l.jsx("p",{className:"text-xs text-destructive",children:r})]})}function mht(e){var r;const t=Eh(e,"AI generation failed"),n=(r=Cme(e))==null?void 0:r[0];return n?n.hint?`${n.message} Hint: ${n.hint}`:n.message||t:t}function pht({endpoint:e,availableFields:t,fieldType:n,dialect:r}){const{authToken:s}=nt(),[o,i]=C.useState(!1),[a,c]=C.useState(null);return{generateExpression:C.useCallback(async d=>{var f;if(!e)return c("AI generation is not available"),null;if(!d.trim())return c("Describe what you want to calculate"),null;i(!0),c(null);try{const h={type:"calculated-field-expression",context:{userQuery:d,availableFields:t.map(p=>({name:p.tokenLabel,dataType:p.dataType,...p.role==="metric"||p.role==="groupby"?{role:p.role}:{}})),fieldType:n},options:{dialect:r}},m=await ys(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 c(mht(h)),null}finally{i(!1)}},[e,t,n,r,s==null?void 0:s.accessToken]),isGenerating:o,error:a}}function Nce(e){return e.entityName===Ao||e.qualifiedEntityName===Ao||e.entityName===mo}function ght(e){return Nce(e)?Ao:e.qualifiedEntityName||e.entityName||"Other"}function xht(e){return Nce(e)?"Calculated Fields":e.qualifiedEntityName?Xf(e.entityName||e.qualifiedEntityName):Xf(e.entityName||"Other")}function bht({open:e,onOpenChange:t,availableFields:n,fieldType:r,onExpressionGenerated:s,endpoint:o,dialect:i}){const[a,c]=C.useState(""),[u,d]=C.useState(""),[f,h]=C.useState(""),[m,p]=C.useState([]),g=C.useRef(null),{generateExpression:x,isGenerating:b,error:y}=pht({endpoint:o,availableFields:n,fieldType:r,dialect:i}),v=C.useMemo(()=>{const _=f.trim().toLowerCase();return _?n.filter(P=>[P.label,P.baseLabel,P.name,P.tokenLabel,P.entityName,P.qualifiedEntityName].filter(Boolean).join(" ").toLowerCase().includes(_)):n},[n,f]),w=C.useMemo(()=>{const _=new Map;return v.forEach(P=>{var L;const M=ght(P),R=xht(P);_.has(M)||_.set(M,{id:M,label:R,fields:[]}),(L=_.get(M))==null||L.fields.push(P)}),Array.from(_.values())},[v]),S=C.useMemo(()=>w.map(_=>_.id),[w]);C.useEffect(()=>{e&&p(S)},[e,S]),C.useEffect(()=>{if(e){if(f.trim()){p(S);return}p(_=>{const P=_.filter(M=>S.includes(M));return P.length>0?P:S})}},[e,f,S]);const N=_=>{const M=(_.name||_.baseLabel||_.label||_.tokenLabel||"").trim();return M.includes(".")&&M.split(".").pop()||M},j=_=>{const P=`{${_}}`,M=g.current;if(!M){c(O=>O+P);return}const R=M.selectionStart||0,L=M.selectionEnd||0;c(O=>`${O.slice(0,R)}${P}${O.slice(L)}`),requestAnimationFrame(()=>{M.focus();const O=R+P.length;M.setSelectionRange(O,O)})},k=_=>{const P=_.tokenLabel||_.name||_.baseLabel||_.label||"";P.trim()&&j(P.trim())},T=async()=>{const _=await x(a.trim());_&&d(_)},E=()=>{u.trim()&&(s(u.trim()),c(""),d(""),t(!1))},I=()=>{c(""),d(""),h(""),p([]),t(!1)};return l.jsx(Ur,{open:e,onOpenChange:_=>{_?t(!0):I()},children:l.jsxs(Tr,{className:"max-w-3xl",children:[l.jsxs(Ir,{children:[l.jsx(_r,{children:"Generate Expression with AI"}),l.jsx(is,{children:"Describe what you want to calculate and we will draft a SQL expression."})]}),l.jsxs("div",{className:"space-y-6",children:[l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(xe,{htmlFor:"ai-prompt",children:"Describe what you want to calculate"}),l.jsx(ei,{id:"ai-prompt",ref:g,value:a,onChange:_=>c(_.target.value),placeholder:"Create a bucket that categorizes orders as 'Large' when amount is greater than 1000",rows:2})]}),l.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs text-muted-foreground",children:[l.jsx("span",{children:"Be specific about conditions, buckets, or math you want to apply."}),l.jsx(se,{size:"sm",onClick:T,disabled:b||!a.trim(),children:b?"Generating...":u?"Regenerate":"Generate"})]}),y&&l.jsx("p",{className:"text-xs text-destructive whitespace-pre-wrap",children:y})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(xe,{children:"Available fields"}),l.jsxs("div",{className:"relative",children:[l.jsx(Gs,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),l.jsx(at,{value:f,onChange:_=>h(_.target.value),placeholder:"Search fields...",className:"pl-9"})]}),l.jsx("div",{className:"overflow-hidden rounded-lg border border-border",children:l.jsx(Ua,{className:"h-64",children:w.length===0?l.jsx("div",{className:"py-6 text-center text-xs text-muted-foreground",children:"No fields match your search."}):l.jsx(OE,{type:"multiple",value:m,onValueChange:p,className:"space-y-1 p-2",children:w.map(_=>l.jsxs(qp,{value:_.id,className:"border-none",children:[l.jsx(Gp,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[360px] truncate text-sm font-medium text-primary",children:_.label}),l.jsx(Xe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:_.fields.length})]})}),l.jsx(Yp,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:_.fields.map(P=>l.jsxs("button",{type:"button",onClick:()=>k(P),className:"group/container flex w-full items-center gap-3 rounded-lg border border-transparent px-2 py-2 text-left transition-all hover:bg-muted",children:[l.jsxs("div",{className:"relative shrink-0",children:[bh(P.dataType),P.isCalculated&&l.jsx("span",{className:J("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",P.role==="metric"?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate font-mono text-xs text-foreground/90 group-hover/container:text-foreground",children:N(P)}),l.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:P.tokenLabel})]}),l.jsx(Xe,{variant:"secondary",className:"shrink-0 px-1.5 py-0 text-[11px]",children:P.dataType})]},P.id))})})]},_.id))})})})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(xe,{children:"Generated expression"}),l.jsx(ei,{value:u,onChange:_=>d(_.target.value),rows:2,className:"font-mono text-sm"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Review and edit the generated expression before using it."})]})]}),l.jsxs(Rs,{className:"gap-2",children:[l.jsx(se,{variant:"ghost",onClick:I,children:"Cancel"}),l.jsx(se,{onClick:E,disabled:!u.trim(),children:"Use Expression"})]})]})})}const yht=/\{([^}]+)\}/g;function LE(e){return e.trim().toLowerCase()}function jce(e){return Array.from(e.matchAll(yht)).map(t=>t[1]).filter(Boolean)}function vht(e){const t=new Set,n=[];return e.forEach(r=>{const s=LE(r);t.has(s)||(t.add(s),n.push(r))}),n}function cL(e){const t=new Map,n=(r,s)=>{const o=LE(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 Cm(e,t){const n=jce(e),r=vht(n),s=cL(t),o=r.map(a=>{const c=s.get(LE(a))||[];return c.length===1?c[0]:null}),i=r.filter((a,c)=>!o[c]);return{orderedTokens:r,orderedFields:o,unresolvedTokens:i}}function IM(e,t){return t.reduce((n,r,s)=>{const o=new RegExp(`\\{${wht(r)}\\}`,"gi");return n.replace(o,`{field_${s}}`)},e)}function wht(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Cht=e=>e.entityName===Ao||e.qualifiedEntityName===Ao||e.entityName===mo?"Calculated Fields":e.qualifiedEntityName?Xf(e.entityName||e.qualifiedEntityName):Xf(e.entityName||"Other");function Sht(e){return e.entityName===Ao||e.qualifiedEntityName===Ao||e.entityName===mo?Ao:e.qualifiedEntityName||e.entityName||"Other"}const Nht=e=>wn(e.dataType||"")==="number";function jht(e,t,n){const r=new Set((n||[]).map(s=>of(s)));return e.filter(s=>{const o=of(s.id);return o&&r.has(o)?!1:t==="dimension"?s.role!=="metric":!0})}function Eht(e){const t=new Map,n=new Map;return e.forEach(r=>{let o=r.entityName&&r.entityName!==mo?`${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 kht(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||Nht(o);return{...o,isCompatible:i}}).filter(o=>r)}function Tht(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 Iht(e){const t=new Map;return e.forEach(n=>{var s;const r=Sht(n);t.has(r)||t.set(r,{id:r,label:Cht(n),fields:[]}),(s=t.get(r))==null||s.fields.push(n)}),Array.from(t.values())}function _ht({fields:e,mode:t,searchTerm:n,excludeFieldIds:r,selectedAggregate:s,showIncompatible:o}){const i=C.useMemo(()=>jht(e,t,r),[e,t,r]),a=C.useMemo(()=>Eht(i),[i]),c=C.useMemo(()=>i.map(m=>{const p=m.label||m.name,g=m.role==="metric"&&f0(m)||m.role==="groupby"&&J7(m);return{...m,baseLabel:p,tokenLabel:a.get(m.id)||p,isCalculated:g,isCompatible:!0}}),[i,a]),u=C.useMemo(()=>cL(c),[c]),d=C.useMemo(()=>kht(c,t,s,o),[c,t,s,o]),f=C.useMemo(()=>Tht(d,n),[d,n]),h=C.useMemo(()=>Iht(f),[f]);return{allFields:c,filteredFields:f,groups:h,tokenCandidates:u}}const Dht=e=>wn(e.dataType||"")==="number",jB=e=>Dht(e)?"SUM":"COUNT",Mht=e=>{if(e.role==="metric"){const n=e;return{...n,aggregate:n.aggregate||jB(e)}}const t=jB(e);return{...e,role:"metric",aggregate:t,alias:`${(e.alias||e.name).toLowerCase()}_${t.toLowerCase()}`}},Aht=(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"}}};function Rht({expression:e,availableFields:t,validationEndpoint:n,connectionId:r,dialect:s,fieldType:o,outputType:i,validationContext:a}){const{authToken:c}=nt(),[u,d]=C.useState(null),[f,h]=C.useState(!1),[m,p]=C.useState(null),g=C.useMemo(()=>cL(t),[t]),x=C.useMemo(()=>jce(e).map(S=>{const N=g.get(LE(S))||[];return{token:S,field:N.length===1?N[0]:null}}),[e,g]),b=C.useCallback((w,S)=>{const N=[{code:"SQL_VALIDATION_ERROR",message:w,suggestion:(S==null?void 0:S.suggestion)||(S==null?void 0:S.errorCode)}];return{isValid:!1,tokens:x,errors:N,warnings:[]}},[x]),y=C.useCallback(async()=>{var M;p(null);const w=n==null?void 0:n.trim();if(!w){const R=b("Validation endpoint is not configured");return d(R),R}if(!!!(a!=null&&a.cardConfig&&(a!=null&&a.cardDataSource)&&(a!=null&&a.cardId)&&(a!=null&&a.connectionId||r))){const R=b("Validation context is incomplete for server-side validation");return d(R),R}const{orderedTokens:N,orderedFields:j}=Cm(e,t),k=[],T=[];N.forEach((R,L)=>{const O=j[L];O&&(k.push(R),T.push(O))});const E=o==="metric"?T.map(Mht):T,I=Aht(e,T),_=IM(e,k),P={type:"calculated-field-expression",fieldType:o,expression:_,inputFields:E,outputType:i,options:{validateWithExplain:!0},context:{connectionId:(a==null?void 0:a.connectionId)||r,cardId:a==null?void 0:a.cardId,cardConfig:a==null?void 0:a.cardConfig,cardDataSource:a==null?void 0:a.cardDataSource,activeFilters:(a==null?void 0:a.activeFilters)||[],cardType:(a==null?void 0:a.cardType)||"table",dialect:s}};h(!0);try{const R=await ys(w,(c==null?void 0:c.accessToken)||"",P),L=R==null?void 0:R.status,O=R==null?void 0:R.error,U=R==null?void 0:R.errorCode,z=[],A=[];L==="invalid"?z.push({code:"SQL_VALIDATION_ERROR",message:O||"Expression failed SQL validation",suggestion:U?`Validation code: ${U}`:void 0}):L==="unverified"?A.push({code:"EXECUTION_UNVERIFIED",message:O||"Execution could not be fully verified in this environment.",suggestion:"Syntax checks passed. This expression may still run successfully."}):L!=="valid"&&z.push({code:"SQL_VALIDATION_ERROR",message:O||"Unexpected SQL validation response from server",suggestion:U?`Validation code: ${U}`:void 0});const W={isValid:(L==="valid"||L==="unverified")&&z.length===0,tokens:x,errors:z,warnings:A,inferredDataType:(R==null?void 0:R.inferredDataType)??((M=R==null?void 0:R.metadata)==null?void 0:M.inferredDataType)??I??i??void 0};return d(W),W}catch(R){const L=(R==null?void 0:R.error)||(R==null?void 0:R.message)||"Expression validation failed";p(L);const O=b(L);return d(O),O}finally{h(!1)}},[n,a,r,e,t,o,i,s,c==null?void 0:c.accessToken,b,x]),v=C.useCallback(()=>{d(null),p(null)},[]);return{validationResult:u,isValidating:f,serverError:m,validateExpression:y,resetValidation:v}}function EB(e,t){const{aggregate:n,...r}=e;return{...r,...t}}function Fht({fields:e,normalizedName:t,existingFieldId:n,targetKind:r,targetEntityName:s,targetQualifiedEntityName:o}){return e.some(i=>{if(n&&i.id===n||i.name!==t)return!1;const a=hd(i);if(r==="inline"){const c=vA(i),u=o||s;return a==="inline_expression"&&!!u&&c===u}return a==="domain_calculated"})}const kB=[{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"}],Pht=[],Oht="https://docs.semaphor.cloud/docs/concepts/calculated-fields/metrics",Lht="https://docs.semaphor.cloud/docs/concepts/calculated-fields/dimensions",$ht="SUM({amount} - {discount_amount}) / NULLIF(SUM({quantity}), 0)",zht="CASE WHEN {Amount} > 100 THEN 'Large' ELSE 'Small' END",KT=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})`},Ece=e=>wn(e.dataType||"")==="number",Sm=e=>Ece(e)?"SUM":"COUNT",ZT=(e,t)=>Ece(e)||t==="COUNT"||t==="DISTINCT"?t:Sm(e);function XT(e,t){if(e.role==="metric"){const n=e;return f0(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 dm(e,t){const n=e.role==="metric"&&f0(e);return{field:e,aggregate:n&&e.aggregate||t,isCalculatedField:n}}function kce({open:e,onOpenChange:t,availableFields:n,existingField:r,existingFieldScope:s,onSave:o,onSaveToDashboard:i,cardId:a,initialFieldType:c="metric",allowedFieldTypes:u}){var be;const{tokenProps:d}=nt(),{selectedConnection:f}=IZ(),h=Ve(pe=>{var ze;return(ze=pe.card)==null?void 0:ze.config}),m=Ve(pe=>{var ze;return(ze=pe.card)==null?void 0:ze.dataSource}),p=Ve(pe=>{var ze;return(ze=pe.card)==null?void 0:ze.type}),x=Ve(pe=>pe.filterValues)??Pht,b=(f==null?void 0:f.dialect)==="bigquery"||(f==null?void 0:f.dialect)==="snowflake",[y,v]=C.useState(c),[w,S]=C.useState(""),[N,j]=C.useState("ratio"),[k,T]=C.useState(null),[E,I]=C.useState(null),[_,P]=C.useState(1),[M,R]=C.useState(""),[L,O]=C.useState(null),[U,z]=C.useState("card"),[A,W]=C.useState({}),[$,D]=C.useState("A"),[q,Q]=C.useState(""),[Y,V]=C.useState(!1),[Z,B]=C.useState(null),[H,G]=C.useState(!1),[K,X]=C.useState(!1),ne=C.useRef(null),ce=C.useRef(!1),ee=C.useRef(null),{userContext:ie}=zo(),re=C.useMemo(()=>n.filter(pe=>pe.fieldScope==="domain"&&!!pe.expression),[n]),de=C.useMemo(()=>re.filter(pe=>pe.role==="metric"),[re]),Me=C.useMemo(()=>re.filter(pe=>pe.role==="groupby"),[re]),je=!((ie==null?void 0:ie.type)==="organization"),fe=!!i,_e=!!i,we=(be=d==null?void 0:d.apiServiceUrl)==null?void 0:be.replace(/\/$/,""),oe=we?`${we}/v1/calculated-fields/validate`:"/v1/calculated-fields/validate",ge=we?`${we}/v1/ai/generate`:"/v1/ai/generate",Ee=C.useMemo(()=>{var ut;const pe=[...n];return(((ut=r==null?void 0:r.calculatedFormula)==null?void 0:ut.inputFields)||[]).forEach(_t=>{pe.some(xn=>xn.id===_t.id||xn.qualifiedFieldName===_t.qualifiedFieldName||xn.name===_t.name)||pe.push(_t)}),pe},[n,r]),he=$==="A"?k:E,me=y==="metric"&&N!=="custom"?he==null?void 0:he.aggregate:void 0,{allFields:Pe,groups:ye}=_ht({fields:Ee,mode:y,searchTerm:q,excludeFieldIds:r?[r.id]:void 0,selectedAggregate:me,showIncompatible:!0}),ve=Pe,{validationResult:Le,validateExpression:$e,isValidating:Ye,serverError:Ke,resetValidation:Ze}=Rht({expression:M,availableFields:ve,validationEndpoint:oe,connectionId:f==null?void 0:f.id,dialect:f==null?void 0:f.dialect,fieldType:y,outputType:L||void 0,validationContext:{connectionId:(f==null?void 0:f.id)||(m==null?void 0:m.connectionId),cardId:a,cardConfig:h||{},cardDataSource:m||null,activeFilters:x,cardType:p}}),st=Le==null?void 0:Le.inferredDataType,le=L||st||"string",Oe=Xy.find(pe=>pe.id===N),ke=C.useMemo(()=>{if(y==="dimension"){const{orderedFields:pe}=Cm(M,ve);return pe.filter(ze=>!!ze)}if(N==="custom"){const{orderedFields:pe}=Cm(M,ve);return pe.filter(ze=>!!ze)}return[k==null?void 0:k.field,E==null?void 0:E.field].filter(pe=>!!pe)},[ve,M,y,k==null?void 0:k.field,E==null?void 0:E.field,N]),Ie=C.useMemo(()=>aL(ke),[ke]),We=C.useMemo(()=>{if(!w.trim())return!1;const pe=iL(w);return Fht({fields:y==="metric"?de:Me,normalizedName:pe,existingFieldId:s==="domain"?r==null?void 0:r.id:void 0,targetKind:Ie.kind==="inline"?"inline":"root",targetEntityName:Ie.kind==="inline"?Ie.entityName:void 0,targetQualifiedEntityName:Ie.kind==="inline"?Ie.qualifiedEntityName:void 0})},[Ie,Me,de,r,s,y,w]),Te=C.useMemo(()=>{if(y==="metric"&&N==="custom"){const{orderedFields:ze}=Cm(M,ve);return ze.filter(ut=>!!ut).map(ut=>ut.id)}const pe=[];return k!=null&&k.field.id&&pe.push(k.field.id),E!=null&&E.field.id&&pe.push(E.field.id),pe},[ve,M,y,k,E,N]),Ue=pe=>{je||v(pe)},et=pe=>{je||(j(pe),pe==="scale"&&I(null),pe==="custom"&&(T(null),I(null)))},xt=()=>{S(""),j("ratio"),T(null),I(null),P(1),R(""),O(null),z("card"),W({}),Q(""),V(!1),B(null),G(!1),Ze(),t(!1)},dt=C.useCallback(pe=>Ee.find(ze=>ze.qualifiedFieldName===pe.qualifiedFieldName||ze.name===pe.name)||pe,[Ee]),St=C.useCallback(pe=>{if(!pe.calculatedFormula)return;const ze=pe.calculatedFormula;if(j(ze.operation),R(""),ze.operation==="scale"){const zt=ze.inputFields[0];zt&&T(dm(dt(zt),zt.aggregate||"SUM")),P(ze.constant===void 0?1:ze.constant);return}if(ze.operation==="custom"){R(Ot(pe.expression||"",ze.inputFields||[])),T(null),I(null);return}const[ut,_t]=ze.inputFields;ut&&T(dm(dt(ut),ut.aggregate||"SUM")),_t&&I(dm(dt(_t),_t.aggregate||"SUM"))},[dt]),Ot=C.useCallback((pe,ze)=>pe.replace(/\{field_(\d+)\}/g,(ut,_t)=>{var cr;const zt=ze[Number(_t)];return zt?`{${((cr=ve.find(vo=>vo.id===zt.id))==null?void 0:cr.tokenLabel)||zt.label||zt.name}}`:ut}),[ve]);C.useEffect(()=>{var ut;if(!e){ce.current=!1,ee.current=null;return}const pe=r?`${r.role}-${r.id||r.name}`:"new";if(ce.current&&ee.current===pe)return;if(ce.current=!0,ee.current=pe,W({}),Q(""),Ze(),r){if(r.role==="metric"){v("metric"),S(r.label||r.name),z(s||"card"),St(r);return}v("dimension");const _t=r;S(_t.label||_t.name),z(s||"card"),R(Ot(_t.expression||"",((ut=_t.calculatedFormula)==null?void 0:ut.inputFields)||[]));const zt=kB.some(xn=>xn.value===_t.dataType)?_t.dataType:"string";O(zt);return}const ze=u&&u.length>0?u.includes(c)?c:u[0]:c;v(ze),S(""),j("ratio"),T(null),I(null),P(1),R(""),O(null),z("card")},[e,r,s,c,u,St,Ot,Ze]);const bt=pe=>{const ze=`{${pe}}`,ut=ne.current;if(!ut){R(cr=>cr+ze);return}const _t=ut.selectionStart||0,zt=ut.selectionEnd||0,xn=`${M.slice(0,_t)}${ze}${M.slice(zt)}`;R(xn),requestAnimationFrame(()=>{ut.focus();const cr=_t+ze.length;ut.setSelectionRange(cr,cr)})},an=pe=>{if(je)return;if(y==="dimension"||N==="custom"){bt(pe.tokenLabel||pe.label||pe.name);return}const ze=ZT(pe,$==="A"?(k==null?void 0:k.aggregate)||Sm(pe):(E==null?void 0:E.aggregate)||Sm(pe)),ut=dm(pe,ze);if($==="A"){T(ut),E||D("B");return}I(ut),k||D("A")},Tt=(pe,ze)=>{if(!je){if(pe==="A"&&k){T({...k,aggregate:ze});return}pe==="B"&&E&&I({...E,aggregate:ze})}},Ce=async()=>{const pe={};if(w.trim()||(pe.name="Name is required"),N==="custom")M.trim()||(pe.expression="Expression is required"),pe.expression||(await $e()).isValid||(pe.expression="Fix validation errors before saving");else if(N==="scale")k||(pe.inputA="Please select a metric for input A"),Number.isNaN(_)&&(pe.constant="Please enter a valid multiplication factor");else{if(k||(pe.inputA="Please select a metric for input A"),E||(pe.inputB="Please select a metric for input B"),k&&E){const ze=k.field.id===E.field.id,ut=k.aggregate===E.aggregate;ze&&ut&&(pe.inputs="Inputs A and B must be different metrics")}if(r&&r.role==="metric"){const ze=of(r.id);(of(k==null?void 0:k.field.id)===ze||of(E==null?void 0:E.field.id)===ze)&&(pe.inputs="Cannot reference the field being edited")}}return W(pe),Object.keys(pe).length===0},rt=async()=>{const pe={};return w.trim()||(pe.name="Name is required"),M.trim()||(pe.expression="Expression is required"),pe.expression||(await $e()).isValid||(pe.expression="Fix validation errors before saving"),W(pe),Object.keys(pe).length===0},ct=()=>{const{orderedTokens:pe,orderedFields:ze}=Cm(M,ve),ut=ze.filter(xn=>!!xn),_t=IM(M,pe),zt=oht(w,_t,ut,le,a,r==null?void 0:r.id);return r&&r.role==="groupby"?{...r,...zt}:zt},pn=()=>{var _t;if(N==="custom"){const{orderedTokens:zt,orderedFields:xn}=Cm(M,ve),cr=xn.filter(vt=>!!vt),vo=(r==null?void 0:r.role)==="metric"?((_t=r.calculatedFormula)==null?void 0:_t.inputFields)||[]:[],Fe=new Map;vo.forEach(vt=>{const Kn=of(vt.id);Kn&&Fe.set(Kn,vt),vt.qualifiedFieldName&&Fe.set(vt.qualifiedFieldName,vt),vt.name&&Fe.set(vt.name,vt)});const Nt=cr.map(vt=>{const Kn=of(vt.id),tr=Kn&&Fe.get(Kn)||vt.qualifiedFieldName&&Fe.get(vt.qualifiedFieldName)||Fe.get(vt.name),nr=((tr==null?void 0:tr.role)==="metric"?tr.aggregate:void 0)||(vt.role==="metric"?vt.aggregate:void 0)||Sm(vt);return XT(vt,nr)}),En=IM(M,zt),tn=wB(w,N,null,null,{},a,r==null?void 0:r.id,En,void 0,Nt);return r&&r.role==="metric"?EB(r,tn):tn}const pe=k?XT(k.field,k.aggregate):null,ze=E?XT(E.field,E.aggregate):null,ut=wB(w,N,pe,ze,{},a,r==null?void 0:r.id,void 0,N==="scale"?_:void 0);return r&&r.role==="metric"?EB(r,ut):ut},Jr=async pe=>{if(pe==="domain"){W(ut=>({...ut,scope:"Domain scope is not available in this explorer."}));return}if(y==="dimension"){const ut=ct();if(pe==="dashboard"){if(!i){W(_t=>({..._t,scope:"Shared sheet scope is not available"}));return}await i(ut),xt();return}await o(ut),xt();return}const ze=pn();if(pe==="dashboard"){if(!i){W(ut=>({...ut,scope:"Shared sheet scope is not available"}));return}await i(ze),xt();return}await o(ze),xt()},Nr=async()=>{if(je)return;if(W({}),y==="metric"){if(!await Ce())return}else if(!await rt())return;const pe=fe?U:s||"card";if(y==="metric"&&pe!=="domain"&&We&&!r){B(pe),G(!0);return}X(!0);try{await Jr(pe)}finally{X(!1)}},es=C.useMemo(()=>{if(!Oe||N==="custom")return"";if(N==="scale"){const pe=Number.isFinite(_)?_:1;return`${KT(k)} x ${pe}`}return`${KT(k)||"A"} ${Oe.symbol} ${KT(E)||"B"}`},[Oe,N,k,E,_]),ri=C.useMemo(()=>Ie.kind==="inline"?"Inline":"Multi-Entity",[Ie]),yo=y==="metric"?Oht:Lht,Ga=y==="metric"?$ht:zht,ru=y==="metric"?"Calculated Metric":"Calculated Dimension",yt=y==="metric"?"border-emerald-600/30 bg-emerald-500/10 text-emerald-700":"border-sky-600/30 bg-sky-500/10 text-sky-700";return l.jsxs(l.Fragment,{children:[l.jsxs(Ur,{modal:!1,open:e,onOpenChange:pe=>{pe?t(!0):xt()},children:[e&&l.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),l.jsxs(Tr,{className:"max-w-5xl max-h-[90vh] overflow-hidden",onInteractOutside:pe=>{pe.preventDefault()},children:[l.jsxs(Ir,{children:[l.jsxs(_r,{className:"flex items-center gap-2",children:[l.jsxs("span",{children:[r?"Edit":"Create"," Calculated Field"]}),l.jsx(Xe,{variant:"outline",className:yt,children:ru}),l.jsx(Xe,{variant:"secondary",children:ri})]}),l.jsx(is,{children:"Build calculated metrics and dimensions using expressions."})]}),l.jsxs("div",{className:"grid h-[70vh] min-h-0 grid-cols-[280px_1fr] gap-6",children:[l.jsx(aht,{groups:ye,searchTerm:q,onSearchTermChange:Q,onFieldClick:an,selectedFieldIds:Te,disabled:je}),l.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-4 overflow-y-auto pr-2 pb-6",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(xe,{children:"Field Type"}),l.jsx(iht,{value:y,onChange:Ue,disabled:je||!!r,options:u||["metric","dimension"]})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(xe,{htmlFor:"calculated-name",children:"Name"}),l.jsx(at,{id:"calculated-name",value:w,onChange:pe=>S(pe.target.value),placeholder:y==="metric"?"e.g., Profit Margin":"e.g., Sales Tier",className:A.name?"border-destructive":"",disabled:je}),A.name&&l.jsx("p",{className:"text-xs text-destructive",children:A.name})]}),fe&&_e&&l.jsx("div",{className:"space-y-3",children:l.jsx(hht,{scope:U,onChange:z,showDashboardScope:_e,error:A.scope,disabled:je})}),y==="metric"&&l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(xe,{children:"Operation"}),l.jsx(lht,{value:N,onChange:et,allowCustom:!0,disabled:je}),A.operation&&l.jsx("p",{className:"text-xs text-destructive",children:A.operation})]}),N==="custom"?l.jsxs("div",{className:"space-y-3",children:[l.jsx(SB,{ref:ne,value:M,onChange:pe=>{R(pe)},onGenerate:()=>V(!0),showGenerate:!!ge&&!je,docsUrl:yo,placeholder:Ga,disabled:je}),l.jsx(NB,{onValidate:$e,isValidating:Ye,validationResult:Le,error:Ke,disabled:je}),A.expression&&l.jsx("p",{className:"text-xs text-destructive",children:A.expression})]}):l.jsxs("div",{className:"space-y-3",children:[l.jsx(xe,{children:"Inputs"}),l.jsx(CB,{label:"A",input:k,availableFields:ve,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:pe=>{const ze=ZT(pe,(k==null?void 0:k.aggregate)||Sm(pe));T(dm(pe,ze))},onAggregateChange:pe=>Tt("A",pe),onRemove:()=>T(null),onActivate:()=>D("A"),allowMedian:b,disabled:je}),A.inputA&&l.jsx("p",{className:"text-xs text-destructive",children:A.inputA}),N!=="scale"&&l.jsxs(l.Fragment,{children:[l.jsx(CB,{label:"B",input:E,availableFields:ve,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:pe=>{const ze=ZT(pe,(E==null?void 0:E.aggregate)||Sm(pe));I(dm(pe,ze))},onAggregateChange:pe=>Tt("B",pe),onRemove:()=>I(null),onActivate:()=>D("B"),allowMedian:b,disabled:je}),A.inputB&&l.jsx("p",{className:"text-xs text-destructive",children:A.inputB})]}),N==="scale"&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(xe,{htmlFor:"constantFactor",children:"Multiplication Factor"}),l.jsx(at,{id:"constantFactor",type:"number",step:"any",value:Number.isNaN(_)?"":_,onChange:pe=>P(pe.target.value===""?Number.NaN:Number(pe.target.value)),className:A.constant?"border-destructive":"",placeholder:"e.g., 0.15",disabled:je}),A.constant&&l.jsx("p",{className:"text-xs text-destructive",children:A.constant})]}),l.jsx("div",{className:"rounded-md border bg-muted/40 p-3 font-mono text-sm",children:es||"Select inputs to preview formula"}),A.inputs&&l.jsxs(Aj,{variant:"destructive",children:[l.jsx(zc,{className:"h-4 w-4"}),l.jsx(Rj,{children:A.inputs})]})]})]}),y==="dimension"&&l.jsxs("div",{className:"space-y-3",children:[l.jsx(SB,{ref:ne,value:M,onChange:pe=>{R(pe)},onGenerate:()=>V(!0),showGenerate:!!ge&&!je,docsUrl:yo,placeholder:Ga,disabled:je}),l.jsx(NB,{onValidate:$e,isValidating:Ye,validationResult:Le,error:Ke,disabled:je}),A.expression&&l.jsx("p",{className:"text-xs text-destructive",children:A.expression}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(xe,{children:"Output Type"}),l.jsxs(mt,{value:le,onValueChange:pe=>O(pe),disabled:je,children:[l.jsx(ft,{children:l.jsx(gt,{placeholder:"Select output type"})}),l.jsx(ht,{children:kB.map(pe=>l.jsx(De,{value:pe.value,children:pe.label},pe.value))})]}),st&&!L&&l.jsxs("p",{className:"text-xs text-muted-foreground",children:["Suggested type: ",st]})]})]})]})]}),l.jsxs(Rs,{children:[l.jsx(se,{variant:"outline",onClick:xt,disabled:K,children:"Cancel"}),l.jsx(se,{onClick:()=>void Nr(),disabled:K||Ye||je,children:K?l.jsxs(l.Fragment,{children:[l.jsx(Mn,{className:"mr-2 h-4 w-4 animate-spin"}),r?"Updating":"Saving"," ",y==="metric"?"Metric":"Dimension","..."]}):l.jsxs(l.Fragment,{children:[r?"Update":"Save"," ",y==="metric"?"Metric":"Dimension"]})})]})]})]}),l.jsx(bht,{open:Y,onOpenChange:V,availableFields:ve,fieldType:y,onExpressionGenerated:async pe=>{R(pe),Ze()},endpoint:ge,dialect:f==null?void 0:f.dialect}),l.jsx(Gc,{open:H,onOpenChange:G,children:l.jsxs(zl,{children:[l.jsxs(Vl,{children:[l.jsx(Ul,{children:"Name Conflict"}),l.jsxs(Hl,{children:['A domain metric named "',w.trim(),'" already exists. Your local version will override it in this'," ",Z==="dashboard"?"dashboard":"card",". Continue?"]})]}),l.jsxs(Bl,{children:[l.jsx(ql,{onClick:()=>{B(null)},children:"Choose Different Name"}),l.jsx(Wl,{onClick:async()=>{if(Z){G(!1),X(!0);try{await Jr(Z)}finally{X(!1),B(null)}}},children:"Continue"})]})]})})]})}function Vht(e,t){const n=e.fieldScope==="dashboard";if(e.role==="metric"){const r=t.metricFields.find(s=>zu(s,e,{allowComparableFallback:n}));if(r)return r}if(e.role==="groupby"){const r=t.groupByFields.find(s=>zu(s,e,{allowComparableFallback:n}));if(r)return r}return t.storedCalculatedFields.find(r=>zu(r,e,{allowComparableFallback:n}))}function Bht(e,t){const n={...e,fieldScope:"domain"};return t.find(r=>r.fieldScope==="domain"&&zu(r,n))}function Tce(e,t){var n,r,s,o;if(e.role==="metric"&&t.role==="metric"){const i=e,a=t;return{...a,parameters:i.parameters||a.parameters?{filters:((n=i.parameters)==null?void 0:n.filters)??((r=a.parameters)==null?void 0:r.filters),windowTransform:((s=i.parameters)==null?void 0:s.windowTransform)??((o=a.parameters)==null?void 0:o.windowTransform)}:void 0,aliasTemplate:i.aliasTemplate??a.aliasTemplate,valueAliases:i.valueAliases??a.valueAliases,customFormat:i.customFormat??a.customFormat,comparisonType:i.comparisonType??a.comparisonType,comparisonDisplay:i.comparisonDisplay??a.comparisonDisplay,targetValue:i.targetValue??a.targetValue}}if(e.role==="groupby"&&t.role==="groupby"){const i=e,a=t;return{...a,granularity:i.granularity??a.granularity,dateFormat:i.dateFormat??a.dateFormat,customFormat:i.customFormat??a.customFormat,timeDrillPath:i.timeDrillPath??a.timeDrillPath}}return t}function Ice(e,t,n,r){if(!n)return null;const o=tU(e,n||t,r);if(n&&o<0)return null;if(o>=0){const i=e[o],a=i==null?void 0:i.id,c=r!=null&&r.mergeMatchedField?r.mergeMatchedField(i,t):t,d=a&&a!==c.id&&!((i==null?void 0:i.fieldScope)==="domain"&&c.fieldScope==="domain")?{...c,id:a}:c;return e.map((f,h)=>h===o?d:f)}return null}function _ce(e,t){return{...e,fieldScope:t}}function _M(e){const t=_ce(e.updatedField,"card"),n=Ice(e.activeFields,t,e.editingField,{allowComparableFallback:e.previousScope==="dashboard",mergeMatchedField:Tce}),r=rU(e.storedFields,t,e.editingField,{allowComparableFallback:e.previousScope==="dashboard"}),s=e.previousScope==="dashboard"&&e.editingField?jm(e.sharedFields,e.editingField,{allowComparableFallback:!0}):e.sharedFields;return{nextActiveFields:n,nextStoredFields:r,nextSharedFields:s}}function DM(e){const t=_ce(e.updatedField,"dashboard"),n=Ice(e.activeFields,t,e.editingField,{allowComparableFallback:e.previousScope==="dashboard",mergeMatchedField:Tce}),r=rU(e.sharedFields,t,e.editingField,{allowComparableFallback:!0}),s=e.previousScope==="card"&&e.editingField?jm(e.storedFields,e.editingField,{allowComparableFallback:!0}):e.storedFields;return{nextActiveFields:n,nextStoredFields:s,nextSharedFields:r}}function Nm(e){const{nextSharedFields:t,currentSharedFields:n,isVisualEditing:r,selectedSheetId:s,updateFrame:o,updateSheetCalculatedFields:i,currentFrame:a,nextFramePatch:c,persistFrame:u,persistFrames:d}=e,f=c?{...c,calculatedFields:t}:{calculatedFields:t};(t!==n||c)&&o(f),s&&(r||(u&&(d!=null&&d.length)?d.forEach(h=>{u(s,{...h,calculatedFields:void 0})}):u&&a&&c&&u(s,{...a,...c,calculatedFields:void 0}),i&&i(s,t)))}const Dce=C.memo(function({context:t="editor",onFieldSelect:n,inlineFilters:r}={}){var Ot,bt,an,Tt;const[s,o]=C.useState(""),[i,a]=C.useState("all"),[c,u]=C.useState(!1),[d,f]=C.useState(null),[h,m]=C.useState("card"),[p,g]=C.useState("metric"),[x,b]=C.useState(null),[y,v]=C.useState(!1);Ve(Ce=>Ce.isDevMode);const w=Ve(Ce=>Ce.card.dataSource),S=Ve(Ce=>Ce.card.config),N=Ve(Ce=>Ce.card),j=Ve(Ce=>Ce.frame),k=Ve(Ce=>Ce.actions.updateCardConfig),T=Ve(Ce=>Ce.actions.updateCard),E=Ve(Ce=>Ce.actions.updateFrame),I=te(Ce=>Ce.isVisualEditing),_=te(Ce=>Ce.selectedSheetId),P=te(Ce=>Ce.actions.updateSheetCalculatedFields),{userContext:M}=zo(),{autoJoinMetadata:R}=Dl(N),{rawColumnGroups:L,scopedFields:O,dashboardFilterableFields:U,inlineFilterableFields:z,scopedCalculatedFields:A,sharedCalculatedFields:W,inlineCalculatedFields:$,isLoading:D,error:q}=Kle(),Q=(w==null?void 0:w.mode)==="semanticDomain"?w.semanticDomainId:void 0,{data:Y}=eL(Q),V=C.useMemo(()=>[...(S==null?void 0:S.groupByColumns)||[],...(S==null?void 0:S.metricColumns)||[],...(S==null?void 0:S.detailColumns)||[]],[S==null?void 0:S.groupByColumns,S==null?void 0:S.metricColumns,S==null?void 0:S.detailColumns]);(bt=(Ot=S==null?void 0:S.joinPlan)==null?void 0:Ot.baseEntity)==null||bt.name,(Tt=(an=R==null?void 0:R.resolvedJoinPlan)==null?void 0:an.baseEntity)==null||Tt.name,nce();const Z=t==="editor"?A:t==="filter"?W:$,B=Z.length>0,H=(M==null?void 0:M.type)==="organization",G=t==="editor"?O:t==="filter"?U:z,K=L,X=s.toLowerCase(),ne=(S==null?void 0:S.metricColumns)||[],ce=(S==null?void 0:S.groupByColumns)||[],ee=N.calculatedFields||[],ie=Ce=>Ce.name.toLowerCase().includes(X)||Ce.dataType.toLowerCase().includes(X)||Ce.label&&Ce.label.toLowerCase().includes(X)||Ce.qualifiedEntityName&&Ce.qualifiedEntityName.toLowerCase().includes(X),re=C.useCallback(Ce=>(Ce.label||Ce.name).toLowerCase().trim(),[]),de=C.useCallback((Ce,rt)=>re(Ce).localeCompare(re(rt),void 0,{numeric:!0,sensitivity:"base"}),[re]),Me=G.filter(ie).sort(de),Ne=C.useCallback(Ce=>t==="editor"?Jg(Ce):Sa(Ce),[t]),je=Ce=>{if(Ne(Ce))return"calculated";if(Ce.dataType==="number"||Ce.dataType==="integer"||Ce.dataType==="float"||Ce.dataType==="decimal"||Ce.dataType==="currency")return"metrics";const rt=wn(Ce.dataType);return["date","string","boolean"].includes(rt)?"dimensions":rt==="number"?"metrics":"dimensions"},fe=Ce=>{const rt=Ce.filter(ie);return i==="all"?rt:rt.filter(ct=>je(ct)===i)},_e=i==="all"?Me:Me.filter(Ce=>je(Ce)===i),we=B?fe(Z).sort(de):[],oe=G.filter(Ce=>je(Ce)!=="calculated"),Ee=fe(oe).sort(de).reduce((Ce,rt)=>{const ct=rt.qualifiedEntityName||"Other Fields";return Ce[ct]||(Ce[ct]={label:Xf(rt.entityName),fields:[]}),Ce[ct].fields.push(rt),Ce},{}),he=C.useMemo(()=>Object.entries(Ee).map(([Ce,rt])=>{const ct=K.find(Jr=>Jr.entityName===Ce)||{entityName:Ce,label:rt.label},pn=Ce===Ao?"Domain Calculated Fields":ct.label||ct.entityName;return{groupName:Ce,groupLabel:pn,fields:[...rt.fields].sort(de)}}).sort((Ce,rt)=>Ce.groupLabel.localeCompare(rt.groupLabel,void 0,{numeric:!0,sensitivity:"base"})),[Ee,K,de]),me=Ce=>Ce.id||`${Ce.entityName}-${Ce.qualifiedEntityName}-${Ce.name}-${Ce.role||"field"}`,Pe=C.useMemo(()=>{const Ce=new Map;return G.forEach(ct=>{Ce.set(me(ct),EF(ct,{joinabilityMap:(Y==null?void 0:Y.joinabilityMap)||null,selectedFields:V,cardConfig:S,autoJoinMetadata:R}))}),Ce},[G,Y==null?void 0:Y.joinabilityMap,V,S,R]),ye=B?[{key:"scope-calculated",label:"Calculated Fields",fields:we}].filter(Ce=>Ce.fields.length>0):[],Le=[...ye.map(Ce=>Ce.key),...he.map(Ce=>Ce.groupName)],$e=Me.filter(Ce=>je(Ce)==="dimensions").length,Ye=Me.filter(Ce=>je(Ce)==="metrics").length,Ke=Me.filter(Ce=>je(Ce)==="calculated").length,Ze=Me.length>0&&t!=="inline-filter",st=t==="inline-filter"?"w-full":"w-[290px]";if(D)return l.jsx("div",{className:J("flex h-full flex-col items-center justify-center py-8",st),children:l.jsx(ld,{size:"md",color:"muted","aria-label":"Loading data"})});if(q)return l.jsxs("div",{className:J("flex h-full flex-col items-center justify-center py-8",st),children:[l.jsx(yl,{className:"mb-4 h-12 w-12 text-red-300"}),l.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),l.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:q.message||"Failed to load column data"})]});if(!w||!w.selectedEntities||w.selectedEntities.length===0)return l.jsxs("div",{className:J("flex flex-col items-center justify-center py-8 text-center",st),children:[l.jsx(yl,{className:"mb-4 h-12 w-12 text-gray-300"}),l.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),l.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 le=t==="inline-filter"?"px-3 pb-3":"px-3 pb-6",Oe=t==="inline-filter"?"overflow-hidden":"",ke=Ce=>Vht(Ce,{storedCalculatedFields:ee,metricFields:ne,groupByFields:ce}),Ie=Ce=>{T(N.id,{calculatedFields:jm(ee,Ce,{allowComparableFallback:Ce.fieldScope==="dashboard"})})},We=Ce=>{var rt;return(rt=j==null?void 0:j.calculatedFields)==null?void 0:rt.find(ct=>zu(ct,Ce))},Te=Ce=>{if(Ce.role==="metric"){k(N.id,{metricColumns:jm(ne,Ce,{allowComparableFallback:Ce.fieldScope==="dashboard"})});return}Ce.role==="groupby"&&k(N.id,{groupByColumns:jm(ce,Ce,{allowComparableFallback:Ce.fieldScope==="dashboard"})})},Ue=Ce=>{if(!j)return;const rt=jm(j.calculatedFields||[],Ce);Nm({nextSharedFields:rt,currentSharedFields:j.calculatedFields||[],isVisualEditing:I,selectedSheetId:_,updateFrame:E,updateSheetCalculatedFields:P})},et=Ce=>{if(!H)return;if(Ce.fieldScope==="domain"){qe.error("Domain calculated fields are read-only in this explorer.");return}if(Ce.fieldScope==="dashboard"){const ct=We(Ce);if(!ct)return;f(ct),m("dashboard"),g(ct.role==="metric"?"metric":"dimension"),u(!0);return}const rt=ke(Ce);rt&&(f(rt),m("card"),g(rt.role==="metric"?"metric":"dimension"),u(!0))},xt=async Ce=>{if(H){if(Ce.fieldScope==="domain"){qe.error("Domain calculated fields are read-only in this explorer.");return}if(Ce.fieldScope==="dashboard"){Ue(Ce),Te(Ce);return}Te(Ce),Ie(Ce)}},dt=async()=>{if(x){v(!0);try{await xt(x),b(null)}catch{}finally{v(!1)}}},St=Ce=>{if(!H)return null;const rt=Ce.fieldScope==="domain",ct=rt;return l.jsxs(xd,{children:[l.jsx(bd,{asChild:!0,children:l.jsx(se,{variant:"ghost",size:"icon",className:"h-6 w-6 rounded-full","aria-label":"Calculated field actions",children:l.jsx(_h,{className:"h-3.5 w-3.5"})})}),l.jsxs(Wc,{align:"end",className:"w-36",children:[rt?l.jsx(Bs,{disabled:!0,children:"Read Only In Explorer"}):l.jsx(Bs,{onClick:()=>et(Ce),children:"Edit"}),l.jsx(Bs,{className:"text-destructive focus:text-destructive",disabled:ct,onClick:()=>b(Ce),children:"Delete"})]})]})};return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:J("mt-2 flex h-full w-full grow flex-col gap-2",le,Oe),children:[l.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[G.length>0&&l.jsxs("div",{className:"relative",children:[l.jsx(Gs,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),l.jsx(at,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:s,onChange:Ce=>o(Ce.target.value)}),s&&l.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:l.jsx(Dt,{className:"size-3.5"})})]}),Ze&&l.jsx(Fs,{defaultValue:"all",value:i,onValueChange:Ce=>a(Ce),className:"mb-4",children:l.jsxs(ws,{className:"grid h-11 w-full grid-cols-4 rounded-lg border border-border/60 bg-muted/50 p-1",children:[l.jsxs(on,{value:"all",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:["All",l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:Me.length})]}),l.jsxs(on,{value:"dimensions",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:[l.jsx(fN,{className:"size-3.5 shrink-0"}),l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:$e})]}),l.jsxs(on,{value:"metrics",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:[l.jsx(aN,{className:"size-3.5 shrink-0"}),l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:Ye})]}),l.jsxs(on,{value:"calculated",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:[l.jsx(MA,{className:"size-3.5 shrink-0"}),l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:Ke})]})]})}),t==="editor"&&i==="calculated"&&H&&l.jsx("div",{className:"flex items-center justify-end gap-2",children:l.jsxs(se,{size:"sm",variant:"outline",className:"w-full",onClick:()=>{f(null),m("card"),g("dimension"),u(!0)},children:[l.jsx(Br,{className:"mr-2 h-3.5 w-3.5"}),"Add calculated field"]})})]}),l.jsxs(Ua,{className:"min-h-0 flex-1",children:[l.jsxs(OE,{type:"multiple",defaultValue:Le,className:"space-y-2",children:[ye.map(Ce=>l.jsxs(qp,{value:Ce.key,className:"border-none",children:[l.jsx(Gp,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:Ce.label}),l.jsx(Xe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:Ce.fields.length})]})}),l.jsx(Yp,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:Ce.fields.map(rt=>{const ct=Pe.get(me(rt)),pn=t==="editor"&&H&&Sa(rt);return l.jsx(yB,{field:rt,context:t,fieldState:ct,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0,actions:pn?St(rt):void 0},rt.id)})})})]},Ce.key)),he.map(({groupName:Ce,groupLabel:rt,fields:ct})=>l.jsxs(qp,{value:Ce,className:"border-none",children:[l.jsx(Gp,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{title:rt,className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:rt}),l.jsx(Xe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:ct.length})]})}),l.jsx(Yp,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:ct.map(pn=>{const Jr=Pe.get(me(pn)),Nr=t==="editor"&&H&&Sa(pn);return l.jsx(yB,{field:pn,context:t,fieldState:Jr,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0,actions:Nr?St(pn):void 0},pn.id)})})})]},Ce))]}),G.length===0&&l.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[l.jsx("p",{children:"No fields found for selected data source"}),l.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"})]}),G.length>0&&_e.length===0&&l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),l.jsx(Fa,{orientation:"horizontal"}),l.jsx(Fa,{orientation:"vertical"})]})]}),l.jsx(Gc,{open:!!x,onOpenChange:Ce=>{Ce||b(null)},children:l.jsxs(zl,{children:[l.jsxs(Vl,{children:[l.jsx(Ul,{children:"Delete calculated field?"}),l.jsxs(Hl,{children:["This will remove"," ",l.jsx("span",{className:"font-medium text-foreground",children:(x==null?void 0:x.label)||(x==null?void 0:x.name)||"this calculated field"})," ",(x==null?void 0:x.fieldScope)==="domain"?"from the semantic domain.":"from this configuration."]})]}),l.jsxs(Bl,{children:[l.jsx(ql,{disabled:y,children:"Cancel"}),l.jsx(Wl,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:y,onClick:Ce=>{Ce.preventDefault(),dt()},children:y?"Deleting...":"Delete"})]})]})}),l.jsx(kce,{open:c,onOpenChange:Ce=>{u(Ce),Ce||(f(null),m("card"))},availableFields:O,existingField:d??void 0,existingFieldScope:h,initialFieldType:p,onSave:Ce=>{const rt=d,ct=(j==null?void 0:j.calculatedFields)||[];if(Ce.role==="metric"){const{nextActiveFields:es,nextStoredFields:ri,nextSharedFields:yo}=_M({activeFields:ne,storedFields:ee,sharedFields:ct,updatedField:Ce,editingField:rt,previousScope:h});es&&k(N.id,{metricColumns:es}),T(N.id,{calculatedFields:ri}),j&&yo!==ct&&Nm({nextSharedFields:yo,currentSharedFields:ct,isVisualEditing:I,selectedSheetId:_,updateFrame:E,updateSheetCalculatedFields:P});return}const{nextActiveFields:pn,nextStoredFields:Jr,nextSharedFields:Nr}=_M({activeFields:ce,storedFields:ee,sharedFields:ct,updatedField:Ce,editingField:rt,previousScope:h});pn&&k(N.id,{groupByColumns:pn}),T(N.id,{calculatedFields:Jr}),j&&Nr!==ct&&Nm({nextSharedFields:Nr,currentSharedFields:ct,isVisualEditing:I,selectedSheetId:_,updateFrame:E,updateSheetCalculatedFields:P})},onSaveToDashboard:Ce=>{const rt=d,ct=(j==null?void 0:j.calculatedFields)||[];if(Ce.role==="metric"){const{nextActiveFields:es,nextStoredFields:ri,nextSharedFields:yo}=DM({activeFields:ne,storedFields:ee,sharedFields:ct,updatedField:Ce,editingField:rt,previousScope:h});j&&Nm({nextSharedFields:yo,currentSharedFields:ct,isVisualEditing:I,selectedSheetId:_,updateFrame:E,updateSheetCalculatedFields:P}),es&&k(N.id,{metricColumns:es}),T(N.id,{calculatedFields:ri});return}const{nextActiveFields:pn,nextStoredFields:Jr,nextSharedFields:Nr}=DM({activeFields:ce,storedFields:ee,sharedFields:ct,updatedField:Ce,editingField:rt,previousScope:h});j&&Nm({nextSharedFields:Nr,currentSharedFields:ct,isVisualEditing:I,selectedSheetId:_,updateFrame:E,updateSheetCalculatedFields:P}),pn&&k(N.id,{groupByColumns:pn}),T(N.id,{calculatedFields:Jr})},cardId:N.id})]})}),Mce=C.memo(function({context:t="editor"}={}){return l.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",l.jsx(Dce,{context:t})," "]})});function Ace(){const e=Ve(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=lr();C.useEffect(()=>{var m;if(!e)return;const{tableName:i,schemaName:a,databaseName:c,connectionId:u}=nL(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(c||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function Uht(){Ace();const e=te(c=>c.selectedSheetId),t=te(c=>c.selectedFrameId),n=te(c=>c.dashboard),r=te(c=>c.actions.getSelectedFrame),{setSelectedFrameId:s}=en(),{setCard:o}=lr(),i=Ve(c=>c.card.dataSource);return C.useEffect(()=>{var u,d;let c=r();if(!c){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),c=h)}if(c){const f=c.cards.find(h=>h.id===c.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function Hht(){const e=te(o=>o.dashboard.filterLayout),{setFilterLayout:t}=en(),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 l.jsxs(Lr,{children:[l.jsx($r,{asChild:!0,children:l.jsx(se,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0","aria-label":"Filter display settings",children:l.jsx(vl,{className:"h-4 w-4"})})}),l.jsx(zr,{className:"w-[280px]",align:"end",children:l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("h4",{className:"mb-3 text-sm font-medium",children:"Filter Display"}),l.jsxs(ho,{value:n,onValueChange:o=>t({displayMode:o}),className:"space-y-2",children:[l.jsxs("div",{className:"flex items-start space-x-3",children:[l.jsx(In,{value:"canvas",id:"canvas",className:"mt-0.5"}),l.jsxs("div",{className:"grid gap-0.5",children:[l.jsx(xe,{htmlFor:"canvas",className:"cursor-pointer font-normal",children:"Canvas Cards"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Filters as draggable, resizable cards on the dashboard"})]})]}),l.jsxs("div",{className:"flex items-start space-x-3",children:[l.jsx(In,{value:"toolbar",id:"toolbar",className:"mt-0.5"}),l.jsxs("div",{className:"grid gap-0.5",children:[l.jsx(xe,{htmlFor:"toolbar",className:"cursor-pointer font-normal",children:"Toolbar"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Compact horizontal toolbar below dashboard controls"})]})]})]})]}),n==="toolbar"&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex items-center space-x-2 border-t pt-4",children:[l.jsx(Gt,{id:"wrap",checked:r,onCheckedChange:o=>t({toolbarWrap:o===!0})}),l.jsx(xe,{htmlFor:"wrap",className:"cursor-pointer text-sm font-normal",children:"Wrap filters to multiple lines"})]}),l.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[l.jsx(Gt,{id:"download",checked:s,onCheckedChange:o=>t({showDownloadButton:o===!0})}),l.jsx(xe,{htmlFor:"download",className:"cursor-pointer text-sm font-normal",children:"Show download button"})]})]}),l.jsx("p",{className:"border-t pt-3 text-xs text-muted-foreground",children:"Individual filters can override this setting in their configuration."})]})})]})}function Wht(){const e=te(n=>n.actions.setShowFilters),{hasEntities:t}=Uht();return l.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col overflow-hidden border-l",children:[l.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[l.jsx(xe,{className:"px-2 text-base",children:"Dashboard Filters"}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(Hht,{}),l.jsx(se,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:l.jsx(vse,{})})]})]}),!t&&l.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[l.jsx(yl,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),l.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&l.jsx("div",{className:"flex grow overflow-y-auto",children:l.jsx(vv,{collisionDetection:xv,children:l.jsx(wv,{items:[],strategy:r5,children:l.jsx(Mce,{context:"filter"})})})})]})}function qht(){const e=te(r=>r.dashboard.filters),t=te(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?l.jsx("div",{className:J("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=>l.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[l.jsx(ZO,{filter:r}),l.jsx(Bg,{filter:r})]},r.id))}):null}function Ght(){const e=te(r=>r.showFilters),t=te(r=>r.isVisualEditing),n=te(r=>r.isDashboardEditing);return l.jsxs("div",{role:"dashboard-plus-main",className:J("",{"max-h-0 overflow-hidden":t,"flex grow overflow-hidden":!t}),children:[l.jsxs("section",{className:"flex grow flex-col overflow-y-auto",children:[n&&l.jsx(qht,{}),l.jsx(Vle,{})]}),e&&l.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:l.jsx(Wht,{})})]})}const Yht=C.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-C25JMBLV.js"))),Kht=C.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-DU3NzdD5.js"))),Zht=C.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-DFuRB4cG.js"))),Xht=C.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-C6qnO0ID.js")).then(e=>({default:e.ResourceManagementPanel})));function Qht({showControls:e=!1,showFooter:t=!0,...n}){const r=te(c=>c.isDashboardPanelOpen),s=te(c=>c.isVisualEditing),o=te(c=>c.showDashboardJSON),i=te(c=>c.actions.setIsDashboardPanelOpen),{preferences:a}=n;return l.jsx(Oa,{FallbackComponent:tE,children:l.jsxs(_A,{dashboardProps:n,children:[l.jsx(H0e,{}),l.jsx(Q5,{componentType:"surfboard",componentId:n.id}),l.jsx(X5,{children:l.jsxs(Ule,{preferences:a,children:[o&&l.jsx(C.Suspense,{fallback:null,children:l.jsx(Zht,{})}),l.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&l.jsx(C.Suspense,{fallback:null,children:l.jsx(Yht,{})}),l.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&l.jsx(C.Suspense,{fallback:null,children:l.jsx(Xht,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),l.jsx("div",{className:"flex min-w-0 flex-1",children:l.jsxs(QF,{...n,type:"dashboard",children:[s&&l.jsx(C.Suspense,{fallback:null,children:l.jsx(Kht,{})}),l.jsx(Ght,{})]})})]})]})]})})]})})}var Jht=Object.defineProperty,emt=(e,t,n)=>t in e?Jht(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,u1=(e,t,n)=>emt(e,typeof t!="symbol"?t+"":t,n);const tmt={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},nmt={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}},rmt={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function smt(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function Rce(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const omt={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=Rce(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},imt={stringify:e=>`${e}`,parse:e=>parseFloat(e)},amt={stringify:e=>e,parse:e=>e},QT={string:amt,number:imt,boolean:tmt,function:nmt,method:omt,json:rmt},Tx=Symbol.for("r2wc.render"),d1=Symbol.for("r2wc.connected"),Wd=Symbol.for("r2wc.context"),ai=Symbol.for("r2wc.props");function lmt(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),c={},u={},d={},f={};for(const m of i){c[m]=Array.isArray(t.props)?"string":t.props[m];const p=smt(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(),u1(this,o,!0),u1(this,s),u1(this,r,{}),u1(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[ai].container=this.container;for(const p of i){const g=d[p],x=this.getAttribute(g),b=c[p],y=b?QT[b]:null;if(b==="method"){const v=Rce(g);Object.defineProperty(this[ai].container,v,{enumerable:!0,configurable:!0,get(){return this[ai][v]},set(w){this[ai][v]=w,this[Tx]()}}),this[ai][p]=y.parse(x,g,this)}y!=null&&y.parse&&x&&(this[ai][p]=y.parse(x,g,this))}for(const p of a)this[ai][p]=g=>{const x=p.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(x,{detail:g,...u[p]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[d1]=!0,this[Tx]()}disconnectedCallback(){this[d1]=!1,this[Wd]&&n.unmount(this[Wd]),delete this[Wd]}attributeChangedCallback(p,g,x){const b=f[p],y=c[b],v=y?QT[y]:null;b in c&&v!=null&&v.parse&&x&&(this[ai][b]=v.parse(x,p,this),this[Tx]())}[(o=d1,s=Wd,r=ai,Tx)](){this[d1]&&(this[Wd]?n.update(this[Wd],this[ai]):this[Wd]=n.mount(this.container,e,this[ai]))}}for(const m of i){const p=d[m],g=c[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[ai][m]},set(x){this[ai][m]=x;const b=g?QT[g]:null;if(b!=null&&b.stringify){const y=b.stringify(x,p,this);this.getAttribute(p)!==y&&this.setAttribute(p,y)}else this[Tx]()}})}return h}function cmt(e,t,n){const r=Eue.createRoot(e),s=C.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function umt({root:e,ReactComponent:t},n){const r=C.createElement(t,n);e.render(r)}function dmt({root:e}){e.unmount()}function fmt(e,t={}){return lmt(e,t,{mount:cmt,update:umt,unmount:dmt})}const hmt={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",defaultControlValues:"json",controlContractOverrides:"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"},mmt=fmt(Hle,{props:hmt});var Fce={},Cs=Kr&&Kr.__assign||function(){return Cs=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++){t=arguments[n];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s])}return e},Cs.apply(this,arguments)},pmt=Kr&&Kr.__createBinding||(Object.create?function(e,t,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(t,n);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,s)}:function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),gmt=Kr&&Kr.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),xmt=Kr&&Kr.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&pmt(t,e,n);return gmt(t,e),t},bmt=Kr&&Kr.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(n[r[s]]=e[r[s]]);return n};Object.defineProperty(Fce,"__esModule",{value:!0});var Di=xmt(C),ymt=89,f1=90,vmt=77,TB=57,IB=219,_B=222,DB=192,MB=100,wmt=3e3,Cmt=typeof window<"u"&&"navigator"in window&&/Win/i.test(navigator.platform),JT=typeof window<"u"&&"navigator"in window&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),H1="npm__react-simple-code-editor__textarea",Smt=`
|
|
1393
|
+
`);return l.jsxs(Nn,{delayDuration:120,children:[l.jsx(jn,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":t?"Validation failed. Hover to view details.":"Validation passed. Hover to view details.",className:J("inline-flex h-5 w-5 items-center justify-center rounded-full transition-colors",t?"bg-destructive text-destructive-foreground hover:bg-destructive/90":"bg-emerald-600 text-white hover:bg-emerald-700"),children:t?l.jsx(Dt,{className:"h-3 w-3","aria-hidden":!0}):l.jsx(Zr,{className:"h-3 w-3","aria-hidden":!0})})}),l.jsxs(lL,{side:"top",align:"start",avoidCollisions:!0,collisionPadding:12,className:"w-[min(440px,calc(100vw-32px))] p-0",children:[l.jsxs("div",{className:"space-y-2.5 p-3 text-xs",children:[l.jsx("div",{className:J("font-semibold",t?"text-destructive":"text-emerald-700"),children:t?"Validation failed":"Validation passed"}),l.jsxs("div",{className:"flex flex-wrap gap-x-2 gap-y-1 text-[11px] text-muted-foreground",children:[l.jsx("span",{children:n}),r&&l.jsx("span",{children:r}),s&&l.jsx("span",{children:s}),e.inferredDataType&&l.jsxs("span",{children:["type: ",e.inferredDataType]})]}),e.tokens.length>0&&l.jsxs("div",{className:"space-y-1.5 border-t pt-2",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Tokens"}),l.jsx("div",{className:"max-h-28 space-y-1 overflow-y-auto pr-1 select-text",children:e.tokens.map((i,a)=>l.jsxs("div",{className:"flex items-start gap-1.5",children:[l.jsx("span",{className:"rounded bg-muted px-1.5 py-0.5 font-mono leading-none",children:`{${i.token}}`}),l.jsx(DA,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground"}),i.field?l.jsx("span",{className:"break-all text-muted-foreground",children:i.field.qualifiedFieldName||i.field.name}):l.jsx("span",{className:"text-muted-foreground",children:"Unresolved"})]},`${i.token}-${a}`))})]}),e.errors.length>0&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-destructive",children:"Errors"}),l.jsx(Pc,{text:o,ariaLabel:"Copy validation errors",className:"h-5 w-5 p-0 text-destructive/70 hover:text-destructive"})]}),l.jsx("div",{className:"max-h-32 space-y-1 overflow-y-auto pr-1 text-destructive select-text",children:e.errors.map((i,a)=>l.jsxs("div",{className:"break-words",children:[i.message,i.suggestion?` (${i.suggestion})`:""]},`${i.code}-${a}`))})]}),e.warnings.length>0&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-amber-700",children:"Warnings"}),l.jsx("div",{className:"max-h-32 space-y-1 overflow-y-auto pr-1 text-amber-700 select-text",children:e.warnings.map((i,a)=>l.jsxs("div",{className:"break-words",children:[i.message,i.suggestion?` (${i.suggestion})`:""]},`${i.code}-${a}`))})]}),e.inferredDataType&&l.jsxs("div",{className:"border-t pt-2 text-[11px] text-muted-foreground",children:["Inferred output type:"," ",l.jsx("span",{className:"font-medium text-foreground",children:e.inferredDataType})]})]}),l.jsx(Sce,{className:"fill-popover"})]})]})}function NB({onValidate:e,isValidating:t,validationResult:n,error:r,disabled:s}){return l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(se,{type:"button",variant:"outline",size:"sm",onClick:e,disabled:t||s,children:t?"Validating expression (may take a few seconds)...":"Validate Expression"}),n&&l.jsx(fht,{result:n}),!n&&r&&l.jsxs(Nn,{delayDuration:120,children:[l.jsx(jn,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":"Validation failed. Hover to view details.",className:"inline-flex h-5 w-5 items-center justify-center rounded-full bg-destructive text-destructive-foreground hover:bg-destructive/90",children:l.jsx(Dt,{className:"h-3 w-3","aria-hidden":!0})})}),l.jsxs(lL,{side:"top",align:"start",avoidCollisions:!0,collisionPadding:12,className:"w-[min(420px,calc(100vw-32px))] p-3",children:[l.jsxs("div",{className:"space-y-2 text-xs",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("span",{className:"font-semibold text-destructive",children:"Validation failed"}),l.jsx(Pc,{text:r,ariaLabel:"Copy validation error",className:"h-5 w-5 p-0 text-destructive/70 hover:text-destructive"})]}),l.jsx("p",{className:"max-h-40 overflow-y-auto break-words text-destructive select-text",children:r})]}),l.jsx(Sce,{className:"fill-popover"})]})]})]})}function hht({scope:e,onChange:t,showDashboardScope:n,error:r,disabled:s}){return l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(xe,{children:"Availability"}),l.jsxs(ho,{value:e,onValueChange:o=>t(o),className:"gap-0.5",disabled:s,children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(In,{id:"scope-card",value:"card"}),l.jsx(xe,{htmlFor:"scope-card",className:"text-sm font-normal",children:"This card only"})]}),n&&l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(In,{id:"scope-dashboard",value:"dashboard"}),l.jsx(xe,{htmlFor:"scope-dashboard",className:"text-sm font-normal",children:"All cards on this sheet"})]})]}),r&&l.jsx("p",{className:"text-xs text-destructive",children:r})]})}function mht(e){var r;const t=Eh(e,"AI generation failed"),n=(r=Cme(e))==null?void 0:r[0];return n?n.hint?`${n.message} Hint: ${n.hint}`:n.message||t:t}function pht({endpoint:e,availableFields:t,fieldType:n,dialect:r}){const{authToken:s}=nt(),[o,i]=C.useState(!1),[a,c]=C.useState(null);return{generateExpression:C.useCallback(async d=>{var f;if(!e)return c("AI generation is not available"),null;if(!d.trim())return c("Describe what you want to calculate"),null;i(!0),c(null);try{const h={type:"calculated-field-expression",context:{userQuery:d,availableFields:t.map(p=>({name:p.tokenLabel,dataType:p.dataType,...p.role==="metric"||p.role==="groupby"?{role:p.role}:{}})),fieldType:n},options:{dialect:r}},m=await ys(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 c(mht(h)),null}finally{i(!1)}},[e,t,n,r,s==null?void 0:s.accessToken]),isGenerating:o,error:a}}function Nce(e){return e.entityName===Ao||e.qualifiedEntityName===Ao||e.entityName===mo}function ght(e){return Nce(e)?Ao:e.qualifiedEntityName||e.entityName||"Other"}function xht(e){return Nce(e)?"Calculated Fields":e.qualifiedEntityName?Xf(e.entityName||e.qualifiedEntityName):Xf(e.entityName||"Other")}function bht({open:e,onOpenChange:t,availableFields:n,fieldType:r,onExpressionGenerated:s,endpoint:o,dialect:i}){const[a,c]=C.useState(""),[u,d]=C.useState(""),[f,h]=C.useState(""),[m,p]=C.useState([]),g=C.useRef(null),{generateExpression:x,isGenerating:b,error:y}=pht({endpoint:o,availableFields:n,fieldType:r,dialect:i}),v=C.useMemo(()=>{const _=f.trim().toLowerCase();return _?n.filter(P=>[P.label,P.baseLabel,P.name,P.tokenLabel,P.entityName,P.qualifiedEntityName].filter(Boolean).join(" ").toLowerCase().includes(_)):n},[n,f]),w=C.useMemo(()=>{const _=new Map;return v.forEach(P=>{var L;const M=ght(P),R=xht(P);_.has(M)||_.set(M,{id:M,label:R,fields:[]}),(L=_.get(M))==null||L.fields.push(P)}),Array.from(_.values())},[v]),S=C.useMemo(()=>w.map(_=>_.id),[w]);C.useEffect(()=>{e&&p(S)},[e,S]),C.useEffect(()=>{if(e){if(f.trim()){p(S);return}p(_=>{const P=_.filter(M=>S.includes(M));return P.length>0?P:S})}},[e,f,S]);const N=_=>{const M=(_.name||_.baseLabel||_.label||_.tokenLabel||"").trim();return M.includes(".")&&M.split(".").pop()||M},j=_=>{const P=`{${_}}`,M=g.current;if(!M){c(O=>O+P);return}const R=M.selectionStart||0,L=M.selectionEnd||0;c(O=>`${O.slice(0,R)}${P}${O.slice(L)}`),requestAnimationFrame(()=>{M.focus();const O=R+P.length;M.setSelectionRange(O,O)})},k=_=>{const P=_.tokenLabel||_.name||_.baseLabel||_.label||"";P.trim()&&j(P.trim())},T=async()=>{const _=await x(a.trim());_&&d(_)},E=()=>{u.trim()&&(s(u.trim()),c(""),d(""),t(!1))},I=()=>{c(""),d(""),h(""),p([]),t(!1)};return l.jsx(Ur,{open:e,onOpenChange:_=>{_?t(!0):I()},children:l.jsxs(Tr,{className:"max-w-3xl",children:[l.jsxs(Ir,{children:[l.jsx(_r,{children:"Generate Expression with AI"}),l.jsx(is,{children:"Describe what you want to calculate and we will draft a SQL expression."})]}),l.jsxs("div",{className:"space-y-6",children:[l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(xe,{htmlFor:"ai-prompt",children:"Describe what you want to calculate"}),l.jsx(ei,{id:"ai-prompt",ref:g,value:a,onChange:_=>c(_.target.value),placeholder:"Create a bucket that categorizes orders as 'Large' when amount is greater than 1000",rows:2})]}),l.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs text-muted-foreground",children:[l.jsx("span",{children:"Be specific about conditions, buckets, or math you want to apply."}),l.jsx(se,{size:"sm",onClick:T,disabled:b||!a.trim(),children:b?"Generating...":u?"Regenerate":"Generate"})]}),y&&l.jsx("p",{className:"text-xs text-destructive whitespace-pre-wrap",children:y})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(xe,{children:"Available fields"}),l.jsxs("div",{className:"relative",children:[l.jsx(Gs,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),l.jsx(at,{value:f,onChange:_=>h(_.target.value),placeholder:"Search fields...",className:"pl-9"})]}),l.jsx("div",{className:"overflow-hidden rounded-lg border border-border",children:l.jsx(Ua,{className:"h-64",children:w.length===0?l.jsx("div",{className:"py-6 text-center text-xs text-muted-foreground",children:"No fields match your search."}):l.jsx(OE,{type:"multiple",value:m,onValueChange:p,className:"space-y-1 p-2",children:w.map(_=>l.jsxs(qp,{value:_.id,className:"border-none",children:[l.jsx(Gp,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[360px] truncate text-sm font-medium text-primary",children:_.label}),l.jsx(Xe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:_.fields.length})]})}),l.jsx(Yp,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:_.fields.map(P=>l.jsxs("button",{type:"button",onClick:()=>k(P),className:"group/container flex w-full items-center gap-3 rounded-lg border border-transparent px-2 py-2 text-left transition-all hover:bg-muted",children:[l.jsxs("div",{className:"relative shrink-0",children:[bh(P.dataType),P.isCalculated&&l.jsx("span",{className:J("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",P.role==="metric"?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate font-mono text-xs text-foreground/90 group-hover/container:text-foreground",children:N(P)}),l.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:P.tokenLabel})]}),l.jsx(Xe,{variant:"secondary",className:"shrink-0 px-1.5 py-0 text-[11px]",children:P.dataType})]},P.id))})})]},_.id))})})})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(xe,{children:"Generated expression"}),l.jsx(ei,{value:u,onChange:_=>d(_.target.value),rows:2,className:"font-mono text-sm"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Review and edit the generated expression before using it."})]})]}),l.jsxs(Rs,{className:"gap-2",children:[l.jsx(se,{variant:"ghost",onClick:I,children:"Cancel"}),l.jsx(se,{onClick:E,disabled:!u.trim(),children:"Use Expression"})]})]})})}const yht=/\{([^}]+)\}/g;function LE(e){return e.trim().toLowerCase()}function jce(e){return Array.from(e.matchAll(yht)).map(t=>t[1]).filter(Boolean)}function vht(e){const t=new Set,n=[];return e.forEach(r=>{const s=LE(r);t.has(s)||(t.add(s),n.push(r))}),n}function cL(e){const t=new Map,n=(r,s)=>{const o=LE(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 Cm(e,t){const n=jce(e),r=vht(n),s=cL(t),o=r.map(a=>{const c=s.get(LE(a))||[];return c.length===1?c[0]:null}),i=r.filter((a,c)=>!o[c]);return{orderedTokens:r,orderedFields:o,unresolvedTokens:i}}function IM(e,t){return t.reduce((n,r,s)=>{const o=new RegExp(`\\{${wht(r)}\\}`,"gi");return n.replace(o,`{field_${s}}`)},e)}function wht(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Cht=e=>e.entityName===Ao||e.qualifiedEntityName===Ao||e.entityName===mo?"Calculated Fields":e.qualifiedEntityName?Xf(e.entityName||e.qualifiedEntityName):Xf(e.entityName||"Other");function Sht(e){return e.entityName===Ao||e.qualifiedEntityName===Ao||e.entityName===mo?Ao:e.qualifiedEntityName||e.entityName||"Other"}const Nht=e=>wn(e.dataType||"")==="number";function jht(e,t,n){const r=new Set((n||[]).map(s=>of(s)));return e.filter(s=>{const o=of(s.id);return o&&r.has(o)?!1:t==="dimension"?s.role!=="metric":!0})}function Eht(e){const t=new Map,n=new Map;return e.forEach(r=>{let o=r.entityName&&r.entityName!==mo?`${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 kht(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||Nht(o);return{...o,isCompatible:i}}).filter(o=>r)}function Tht(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 Iht(e){const t=new Map;return e.forEach(n=>{var s;const r=Sht(n);t.has(r)||t.set(r,{id:r,label:Cht(n),fields:[]}),(s=t.get(r))==null||s.fields.push(n)}),Array.from(t.values())}function _ht({fields:e,mode:t,searchTerm:n,excludeFieldIds:r,selectedAggregate:s,showIncompatible:o}){const i=C.useMemo(()=>jht(e,t,r),[e,t,r]),a=C.useMemo(()=>Eht(i),[i]),c=C.useMemo(()=>i.map(m=>{const p=m.label||m.name,g=m.role==="metric"&&f0(m)||m.role==="groupby"&&J7(m);return{...m,baseLabel:p,tokenLabel:a.get(m.id)||p,isCalculated:g,isCompatible:!0}}),[i,a]),u=C.useMemo(()=>cL(c),[c]),d=C.useMemo(()=>kht(c,t,s,o),[c,t,s,o]),f=C.useMemo(()=>Tht(d,n),[d,n]),h=C.useMemo(()=>Iht(f),[f]);return{allFields:c,filteredFields:f,groups:h,tokenCandidates:u}}const Dht=e=>wn(e.dataType||"")==="number",jB=e=>Dht(e)?"SUM":"COUNT",Mht=e=>{if(e.role==="metric"){const n=e;return{...n,aggregate:n.aggregate||jB(e)}}const t=jB(e);return{...e,role:"metric",aggregate:t,alias:`${(e.alias||e.name).toLowerCase()}_${t.toLowerCase()}`}},Aht=(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"}}};function Rht({expression:e,availableFields:t,validationEndpoint:n,connectionId:r,dialect:s,fieldType:o,outputType:i,validationContext:a}){const{authToken:c}=nt(),[u,d]=C.useState(null),[f,h]=C.useState(!1),[m,p]=C.useState(null),g=C.useMemo(()=>cL(t),[t]),x=C.useMemo(()=>jce(e).map(S=>{const N=g.get(LE(S))||[];return{token:S,field:N.length===1?N[0]:null}}),[e,g]),b=C.useCallback((w,S)=>{const N=[{code:"SQL_VALIDATION_ERROR",message:w,suggestion:(S==null?void 0:S.suggestion)||(S==null?void 0:S.errorCode)}];return{isValid:!1,tokens:x,errors:N,warnings:[]}},[x]),y=C.useCallback(async()=>{var M;p(null);const w=n==null?void 0:n.trim();if(!w){const R=b("Validation endpoint is not configured");return d(R),R}if(!!!(a!=null&&a.cardConfig&&(a!=null&&a.cardDataSource)&&(a!=null&&a.cardId)&&(a!=null&&a.connectionId||r))){const R=b("Validation context is incomplete for server-side validation");return d(R),R}const{orderedTokens:N,orderedFields:j}=Cm(e,t),k=[],T=[];N.forEach((R,L)=>{const O=j[L];O&&(k.push(R),T.push(O))});const E=o==="metric"?T.map(Mht):T,I=Aht(e,T),_=IM(e,k),P={type:"calculated-field-expression",fieldType:o,expression:_,inputFields:E,outputType:i,options:{validateWithExplain:!0},context:{connectionId:(a==null?void 0:a.connectionId)||r,cardId:a==null?void 0:a.cardId,cardConfig:a==null?void 0:a.cardConfig,cardDataSource:a==null?void 0:a.cardDataSource,activeFilters:(a==null?void 0:a.activeFilters)||[],cardType:(a==null?void 0:a.cardType)||"table",dialect:s}};h(!0);try{const R=await ys(w,(c==null?void 0:c.accessToken)||"",P),L=R==null?void 0:R.status,O=R==null?void 0:R.error,U=R==null?void 0:R.errorCode,z=[],A=[];L==="invalid"?z.push({code:"SQL_VALIDATION_ERROR",message:O||"Expression failed SQL validation",suggestion:U?`Validation code: ${U}`:void 0}):L==="unverified"?A.push({code:"EXECUTION_UNVERIFIED",message:O||"Execution could not be fully verified in this environment.",suggestion:"Syntax checks passed. This expression may still run successfully."}):L!=="valid"&&z.push({code:"SQL_VALIDATION_ERROR",message:O||"Unexpected SQL validation response from server",suggestion:U?`Validation code: ${U}`:void 0});const W={isValid:(L==="valid"||L==="unverified")&&z.length===0,tokens:x,errors:z,warnings:A,inferredDataType:(R==null?void 0:R.inferredDataType)??((M=R==null?void 0:R.metadata)==null?void 0:M.inferredDataType)??I??i??void 0};return d(W),W}catch(R){const L=(R==null?void 0:R.error)||(R==null?void 0:R.message)||"Expression validation failed";p(L);const O=b(L);return d(O),O}finally{h(!1)}},[n,a,r,e,t,o,i,s,c==null?void 0:c.accessToken,b,x]),v=C.useCallback(()=>{d(null),p(null)},[]);return{validationResult:u,isValidating:f,serverError:m,validateExpression:y,resetValidation:v}}function EB(e,t){const{aggregate:n,...r}=e;return{...r,...t}}function Fht({fields:e,normalizedName:t,existingFieldId:n,targetKind:r,targetEntityName:s,targetQualifiedEntityName:o}){return e.some(i=>{if(n&&i.id===n||i.name!==t)return!1;const a=hd(i);if(r==="inline"){const c=vA(i),u=o||s;return a==="inline_expression"&&!!u&&c===u}return a==="domain_calculated"})}const kB=[{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"}],Pht=[],Oht="https://docs.semaphor.cloud/docs/concepts/calculated-fields/metrics",Lht="https://docs.semaphor.cloud/docs/concepts/calculated-fields/dimensions",$ht="SUM({amount} - {discount_amount}) / NULLIF(SUM({quantity}), 0)",zht="CASE WHEN {Amount} > 100 THEN 'Large' ELSE 'Small' END",KT=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})`},Ece=e=>wn(e.dataType||"")==="number",Sm=e=>Ece(e)?"SUM":"COUNT",ZT=(e,t)=>Ece(e)||t==="COUNT"||t==="DISTINCT"?t:Sm(e);function XT(e,t){if(e.role==="metric"){const n=e;return f0(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 dm(e,t){const n=e.role==="metric"&&f0(e);return{field:e,aggregate:n&&e.aggregate||t,isCalculatedField:n}}function kce({open:e,onOpenChange:t,availableFields:n,existingField:r,existingFieldScope:s,onSave:o,onSaveToDashboard:i,cardId:a,initialFieldType:c="metric",allowedFieldTypes:u}){var be;const{tokenProps:d}=nt(),{selectedConnection:f}=IZ(),h=Ve(pe=>{var ze;return(ze=pe.card)==null?void 0:ze.config}),m=Ve(pe=>{var ze;return(ze=pe.card)==null?void 0:ze.dataSource}),p=Ve(pe=>{var ze;return(ze=pe.card)==null?void 0:ze.type}),x=Ve(pe=>pe.filterValues)??Pht,b=(f==null?void 0:f.dialect)==="bigquery"||(f==null?void 0:f.dialect)==="snowflake",[y,v]=C.useState(c),[w,S]=C.useState(""),[N,j]=C.useState("ratio"),[k,T]=C.useState(null),[E,I]=C.useState(null),[_,P]=C.useState(1),[M,R]=C.useState(""),[L,O]=C.useState(null),[U,z]=C.useState("card"),[A,W]=C.useState({}),[$,D]=C.useState("A"),[q,Q]=C.useState(""),[Y,V]=C.useState(!1),[Z,B]=C.useState(null),[H,G]=C.useState(!1),[K,X]=C.useState(!1),ne=C.useRef(null),ce=C.useRef(!1),ee=C.useRef(null),{userContext:ie}=zo(),re=C.useMemo(()=>n.filter(pe=>pe.fieldScope==="domain"&&!!pe.expression),[n]),de=C.useMemo(()=>re.filter(pe=>pe.role==="metric"),[re]),Me=C.useMemo(()=>re.filter(pe=>pe.role==="groupby"),[re]),je=!((ie==null?void 0:ie.type)==="organization"),fe=!!i,_e=!!i,we=(be=d==null?void 0:d.apiServiceUrl)==null?void 0:be.replace(/\/$/,""),oe=we?`${we}/v1/calculated-fields/validate`:"/v1/calculated-fields/validate",ge=we?`${we}/v1/ai/generate`:"/v1/ai/generate",Ee=C.useMemo(()=>{var ut;const pe=[...n];return(((ut=r==null?void 0:r.calculatedFormula)==null?void 0:ut.inputFields)||[]).forEach(_t=>{pe.some(xn=>xn.id===_t.id||xn.qualifiedFieldName===_t.qualifiedFieldName||xn.name===_t.name)||pe.push(_t)}),pe},[n,r]),he=$==="A"?k:E,me=y==="metric"&&N!=="custom"?he==null?void 0:he.aggregate:void 0,{allFields:Pe,groups:ye}=_ht({fields:Ee,mode:y,searchTerm:q,excludeFieldIds:r?[r.id]:void 0,selectedAggregate:me,showIncompatible:!0}),ve=Pe,{validationResult:Le,validateExpression:$e,isValidating:Ye,serverError:Ke,resetValidation:Ze}=Rht({expression:M,availableFields:ve,validationEndpoint:oe,connectionId:f==null?void 0:f.id,dialect:f==null?void 0:f.dialect,fieldType:y,outputType:L||void 0,validationContext:{connectionId:(f==null?void 0:f.id)||(m==null?void 0:m.connectionId),cardId:a,cardConfig:h||{},cardDataSource:m||null,activeFilters:x,cardType:p}}),st=Le==null?void 0:Le.inferredDataType,le=L||st||"string",Oe=Xy.find(pe=>pe.id===N),ke=C.useMemo(()=>{if(y==="dimension"){const{orderedFields:pe}=Cm(M,ve);return pe.filter(ze=>!!ze)}if(N==="custom"){const{orderedFields:pe}=Cm(M,ve);return pe.filter(ze=>!!ze)}return[k==null?void 0:k.field,E==null?void 0:E.field].filter(pe=>!!pe)},[ve,M,y,k==null?void 0:k.field,E==null?void 0:E.field,N]),Ie=C.useMemo(()=>aL(ke),[ke]),We=C.useMemo(()=>{if(!w.trim())return!1;const pe=iL(w);return Fht({fields:y==="metric"?de:Me,normalizedName:pe,existingFieldId:s==="domain"?r==null?void 0:r.id:void 0,targetKind:Ie.kind==="inline"?"inline":"root",targetEntityName:Ie.kind==="inline"?Ie.entityName:void 0,targetQualifiedEntityName:Ie.kind==="inline"?Ie.qualifiedEntityName:void 0})},[Ie,Me,de,r,s,y,w]),Te=C.useMemo(()=>{if(y==="metric"&&N==="custom"){const{orderedFields:ze}=Cm(M,ve);return ze.filter(ut=>!!ut).map(ut=>ut.id)}const pe=[];return k!=null&&k.field.id&&pe.push(k.field.id),E!=null&&E.field.id&&pe.push(E.field.id),pe},[ve,M,y,k,E,N]),Ue=pe=>{je||v(pe)},et=pe=>{je||(j(pe),pe==="scale"&&I(null),pe==="custom"&&(T(null),I(null)))},xt=()=>{S(""),j("ratio"),T(null),I(null),P(1),R(""),O(null),z("card"),W({}),Q(""),V(!1),B(null),G(!1),Ze(),t(!1)},dt=C.useCallback(pe=>Ee.find(ze=>ze.qualifiedFieldName===pe.qualifiedFieldName||ze.name===pe.name)||pe,[Ee]),St=C.useCallback(pe=>{if(!pe.calculatedFormula)return;const ze=pe.calculatedFormula;if(j(ze.operation),R(""),ze.operation==="scale"){const zt=ze.inputFields[0];zt&&T(dm(dt(zt),zt.aggregate||"SUM")),P(ze.constant===void 0?1:ze.constant);return}if(ze.operation==="custom"){R(Ot(pe.expression||"",ze.inputFields||[])),T(null),I(null);return}const[ut,_t]=ze.inputFields;ut&&T(dm(dt(ut),ut.aggregate||"SUM")),_t&&I(dm(dt(_t),_t.aggregate||"SUM"))},[dt]),Ot=C.useCallback((pe,ze)=>pe.replace(/\{field_(\d+)\}/g,(ut,_t)=>{var cr;const zt=ze[Number(_t)];return zt?`{${((cr=ve.find(vo=>vo.id===zt.id))==null?void 0:cr.tokenLabel)||zt.label||zt.name}}`:ut}),[ve]);C.useEffect(()=>{var ut;if(!e){ce.current=!1,ee.current=null;return}const pe=r?`${r.role}-${r.id||r.name}`:"new";if(ce.current&&ee.current===pe)return;if(ce.current=!0,ee.current=pe,W({}),Q(""),Ze(),r){if(r.role==="metric"){v("metric"),S(r.label||r.name),z(s||"card"),St(r);return}v("dimension");const _t=r;S(_t.label||_t.name),z(s||"card"),R(Ot(_t.expression||"",((ut=_t.calculatedFormula)==null?void 0:ut.inputFields)||[]));const zt=kB.some(xn=>xn.value===_t.dataType)?_t.dataType:"string";O(zt);return}const ze=u&&u.length>0?u.includes(c)?c:u[0]:c;v(ze),S(""),j("ratio"),T(null),I(null),P(1),R(""),O(null),z("card")},[e,r,s,c,u,St,Ot,Ze]);const bt=pe=>{const ze=`{${pe}}`,ut=ne.current;if(!ut){R(cr=>cr+ze);return}const _t=ut.selectionStart||0,zt=ut.selectionEnd||0,xn=`${M.slice(0,_t)}${ze}${M.slice(zt)}`;R(xn),requestAnimationFrame(()=>{ut.focus();const cr=_t+ze.length;ut.setSelectionRange(cr,cr)})},an=pe=>{if(je)return;if(y==="dimension"||N==="custom"){bt(pe.tokenLabel||pe.label||pe.name);return}const ze=ZT(pe,$==="A"?(k==null?void 0:k.aggregate)||Sm(pe):(E==null?void 0:E.aggregate)||Sm(pe)),ut=dm(pe,ze);if($==="A"){T(ut),E||D("B");return}I(ut),k||D("A")},Tt=(pe,ze)=>{if(!je){if(pe==="A"&&k){T({...k,aggregate:ze});return}pe==="B"&&E&&I({...E,aggregate:ze})}},Ce=async()=>{const pe={};if(w.trim()||(pe.name="Name is required"),N==="custom")M.trim()||(pe.expression="Expression is required"),pe.expression||(await $e()).isValid||(pe.expression="Fix validation errors before saving");else if(N==="scale")k||(pe.inputA="Please select a metric for input A"),Number.isNaN(_)&&(pe.constant="Please enter a valid multiplication factor");else{if(k||(pe.inputA="Please select a metric for input A"),E||(pe.inputB="Please select a metric for input B"),k&&E){const ze=k.field.id===E.field.id,ut=k.aggregate===E.aggregate;ze&&ut&&(pe.inputs="Inputs A and B must be different metrics")}if(r&&r.role==="metric"){const ze=of(r.id);(of(k==null?void 0:k.field.id)===ze||of(E==null?void 0:E.field.id)===ze)&&(pe.inputs="Cannot reference the field being edited")}}return W(pe),Object.keys(pe).length===0},rt=async()=>{const pe={};return w.trim()||(pe.name="Name is required"),M.trim()||(pe.expression="Expression is required"),pe.expression||(await $e()).isValid||(pe.expression="Fix validation errors before saving"),W(pe),Object.keys(pe).length===0},ct=()=>{const{orderedTokens:pe,orderedFields:ze}=Cm(M,ve),ut=ze.filter(xn=>!!xn),_t=IM(M,pe),zt=oht(w,_t,ut,le,a,r==null?void 0:r.id);return r&&r.role==="groupby"?{...r,...zt}:zt},pn=()=>{var _t;if(N==="custom"){const{orderedTokens:zt,orderedFields:xn}=Cm(M,ve),cr=xn.filter(vt=>!!vt),vo=(r==null?void 0:r.role)==="metric"?((_t=r.calculatedFormula)==null?void 0:_t.inputFields)||[]:[],Fe=new Map;vo.forEach(vt=>{const Kn=of(vt.id);Kn&&Fe.set(Kn,vt),vt.qualifiedFieldName&&Fe.set(vt.qualifiedFieldName,vt),vt.name&&Fe.set(vt.name,vt)});const Nt=cr.map(vt=>{const Kn=of(vt.id),tr=Kn&&Fe.get(Kn)||vt.qualifiedFieldName&&Fe.get(vt.qualifiedFieldName)||Fe.get(vt.name),nr=((tr==null?void 0:tr.role)==="metric"?tr.aggregate:void 0)||(vt.role==="metric"?vt.aggregate:void 0)||Sm(vt);return XT(vt,nr)}),En=IM(M,zt),tn=wB(w,N,null,null,{},a,r==null?void 0:r.id,En,void 0,Nt);return r&&r.role==="metric"?EB(r,tn):tn}const pe=k?XT(k.field,k.aggregate):null,ze=E?XT(E.field,E.aggregate):null,ut=wB(w,N,pe,ze,{},a,r==null?void 0:r.id,void 0,N==="scale"?_:void 0);return r&&r.role==="metric"?EB(r,ut):ut},Jr=async pe=>{if(pe==="domain"){W(ut=>({...ut,scope:"Domain scope is not available in this explorer."}));return}if(y==="dimension"){const ut=ct();if(pe==="dashboard"){if(!i){W(_t=>({..._t,scope:"Shared sheet scope is not available"}));return}await i(ut),xt();return}await o(ut),xt();return}const ze=pn();if(pe==="dashboard"){if(!i){W(ut=>({...ut,scope:"Shared sheet scope is not available"}));return}await i(ze),xt();return}await o(ze),xt()},Nr=async()=>{if(je)return;if(W({}),y==="metric"){if(!await Ce())return}else if(!await rt())return;const pe=fe?U:s||"card";if(y==="metric"&&pe!=="domain"&&We&&!r){B(pe),G(!0);return}X(!0);try{await Jr(pe)}finally{X(!1)}},es=C.useMemo(()=>{if(!Oe||N==="custom")return"";if(N==="scale"){const pe=Number.isFinite(_)?_:1;return`${KT(k)} x ${pe}`}return`${KT(k)||"A"} ${Oe.symbol} ${KT(E)||"B"}`},[Oe,N,k,E,_]),ri=C.useMemo(()=>Ie.kind==="inline"?"Inline":"Multi-Entity",[Ie]),yo=y==="metric"?Oht:Lht,Ga=y==="metric"?$ht:zht,ru=y==="metric"?"Calculated Metric":"Calculated Dimension",yt=y==="metric"?"border-emerald-600/30 bg-emerald-500/10 text-emerald-700":"border-sky-600/30 bg-sky-500/10 text-sky-700";return l.jsxs(l.Fragment,{children:[l.jsxs(Ur,{modal:!1,open:e,onOpenChange:pe=>{pe?t(!0):xt()},children:[e&&l.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),l.jsxs(Tr,{className:"max-w-5xl max-h-[90vh] overflow-hidden",onInteractOutside:pe=>{pe.preventDefault()},children:[l.jsxs(Ir,{children:[l.jsxs(_r,{className:"flex items-center gap-2",children:[l.jsxs("span",{children:[r?"Edit":"Create"," Calculated Field"]}),l.jsx(Xe,{variant:"outline",className:yt,children:ru}),l.jsx(Xe,{variant:"secondary",children:ri})]}),l.jsx(is,{children:"Build calculated metrics and dimensions using expressions."})]}),l.jsxs("div",{className:"grid h-[70vh] min-h-0 grid-cols-[280px_1fr] gap-6",children:[l.jsx(aht,{groups:ye,searchTerm:q,onSearchTermChange:Q,onFieldClick:an,selectedFieldIds:Te,disabled:je}),l.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-4 overflow-y-auto pr-2 pb-6",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(xe,{children:"Field Type"}),l.jsx(iht,{value:y,onChange:Ue,disabled:je||!!r,options:u||["metric","dimension"]})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(xe,{htmlFor:"calculated-name",children:"Name"}),l.jsx(at,{id:"calculated-name",value:w,onChange:pe=>S(pe.target.value),placeholder:y==="metric"?"e.g., Profit Margin":"e.g., Sales Tier",className:A.name?"border-destructive":"",disabled:je}),A.name&&l.jsx("p",{className:"text-xs text-destructive",children:A.name})]}),fe&&_e&&l.jsx("div",{className:"space-y-3",children:l.jsx(hht,{scope:U,onChange:z,showDashboardScope:_e,error:A.scope,disabled:je})}),y==="metric"&&l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(xe,{children:"Operation"}),l.jsx(lht,{value:N,onChange:et,allowCustom:!0,disabled:je}),A.operation&&l.jsx("p",{className:"text-xs text-destructive",children:A.operation})]}),N==="custom"?l.jsxs("div",{className:"space-y-3",children:[l.jsx(SB,{ref:ne,value:M,onChange:pe=>{R(pe)},onGenerate:()=>V(!0),showGenerate:!!ge&&!je,docsUrl:yo,placeholder:Ga,disabled:je}),l.jsx(NB,{onValidate:$e,isValidating:Ye,validationResult:Le,error:Ke,disabled:je}),A.expression&&l.jsx("p",{className:"text-xs text-destructive",children:A.expression})]}):l.jsxs("div",{className:"space-y-3",children:[l.jsx(xe,{children:"Inputs"}),l.jsx(CB,{label:"A",input:k,availableFields:ve,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:pe=>{const ze=ZT(pe,(k==null?void 0:k.aggregate)||Sm(pe));T(dm(pe,ze))},onAggregateChange:pe=>Tt("A",pe),onRemove:()=>T(null),onActivate:()=>D("A"),allowMedian:b,disabled:je}),A.inputA&&l.jsx("p",{className:"text-xs text-destructive",children:A.inputA}),N!=="scale"&&l.jsxs(l.Fragment,{children:[l.jsx(CB,{label:"B",input:E,availableFields:ve,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:pe=>{const ze=ZT(pe,(E==null?void 0:E.aggregate)||Sm(pe));I(dm(pe,ze))},onAggregateChange:pe=>Tt("B",pe),onRemove:()=>I(null),onActivate:()=>D("B"),allowMedian:b,disabled:je}),A.inputB&&l.jsx("p",{className:"text-xs text-destructive",children:A.inputB})]}),N==="scale"&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(xe,{htmlFor:"constantFactor",children:"Multiplication Factor"}),l.jsx(at,{id:"constantFactor",type:"number",step:"any",value:Number.isNaN(_)?"":_,onChange:pe=>P(pe.target.value===""?Number.NaN:Number(pe.target.value)),className:A.constant?"border-destructive":"",placeholder:"e.g., 0.15",disabled:je}),A.constant&&l.jsx("p",{className:"text-xs text-destructive",children:A.constant})]}),l.jsx("div",{className:"rounded-md border bg-muted/40 p-3 font-mono text-sm",children:es||"Select inputs to preview formula"}),A.inputs&&l.jsxs(Aj,{variant:"destructive",children:[l.jsx(zc,{className:"h-4 w-4"}),l.jsx(Rj,{children:A.inputs})]})]})]}),y==="dimension"&&l.jsxs("div",{className:"space-y-3",children:[l.jsx(SB,{ref:ne,value:M,onChange:pe=>{R(pe)},onGenerate:()=>V(!0),showGenerate:!!ge&&!je,docsUrl:yo,placeholder:Ga,disabled:je}),l.jsx(NB,{onValidate:$e,isValidating:Ye,validationResult:Le,error:Ke,disabled:je}),A.expression&&l.jsx("p",{className:"text-xs text-destructive",children:A.expression}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(xe,{children:"Output Type"}),l.jsxs(mt,{value:le,onValueChange:pe=>O(pe),disabled:je,children:[l.jsx(ft,{children:l.jsx(gt,{placeholder:"Select output type"})}),l.jsx(ht,{children:kB.map(pe=>l.jsx(De,{value:pe.value,children:pe.label},pe.value))})]}),st&&!L&&l.jsxs("p",{className:"text-xs text-muted-foreground",children:["Suggested type: ",st]})]})]})]})]}),l.jsxs(Rs,{children:[l.jsx(se,{variant:"outline",onClick:xt,disabled:K,children:"Cancel"}),l.jsx(se,{onClick:()=>void Nr(),disabled:K||Ye||je,children:K?l.jsxs(l.Fragment,{children:[l.jsx(Mn,{className:"mr-2 h-4 w-4 animate-spin"}),r?"Updating":"Saving"," ",y==="metric"?"Metric":"Dimension","..."]}):l.jsxs(l.Fragment,{children:[r?"Update":"Save"," ",y==="metric"?"Metric":"Dimension"]})})]})]})]}),l.jsx(bht,{open:Y,onOpenChange:V,availableFields:ve,fieldType:y,onExpressionGenerated:async pe=>{R(pe),Ze()},endpoint:ge,dialect:f==null?void 0:f.dialect}),l.jsx(Gc,{open:H,onOpenChange:G,children:l.jsxs(zl,{children:[l.jsxs(Vl,{children:[l.jsx(Ul,{children:"Name Conflict"}),l.jsxs(Hl,{children:['A domain metric named "',w.trim(),'" already exists. Your local version will override it in this'," ",Z==="dashboard"?"dashboard":"card",". Continue?"]})]}),l.jsxs(Bl,{children:[l.jsx(ql,{onClick:()=>{B(null)},children:"Choose Different Name"}),l.jsx(Wl,{onClick:async()=>{if(Z){G(!1),X(!0);try{await Jr(Z)}finally{X(!1),B(null)}}},children:"Continue"})]})]})})]})}function Vht(e,t){const n=e.fieldScope==="dashboard";if(e.role==="metric"){const r=t.metricFields.find(s=>zu(s,e,{allowComparableFallback:n}));if(r)return r}if(e.role==="groupby"){const r=t.groupByFields.find(s=>zu(s,e,{allowComparableFallback:n}));if(r)return r}return t.storedCalculatedFields.find(r=>zu(r,e,{allowComparableFallback:n}))}function Bht(e,t){const n={...e,fieldScope:"domain"};return t.find(r=>r.fieldScope==="domain"&&zu(r,n))}function Tce(e,t){var n,r,s,o;if(e.role==="metric"&&t.role==="metric"){const i=e,a=t;return{...a,parameters:i.parameters||a.parameters?{filters:((n=i.parameters)==null?void 0:n.filters)??((r=a.parameters)==null?void 0:r.filters),windowTransform:((s=i.parameters)==null?void 0:s.windowTransform)??((o=a.parameters)==null?void 0:o.windowTransform)}:void 0,aliasTemplate:i.aliasTemplate??a.aliasTemplate,valueAliases:i.valueAliases??a.valueAliases,customFormat:i.customFormat??a.customFormat,comparisonType:i.comparisonType??a.comparisonType,comparisonDisplay:i.comparisonDisplay??a.comparisonDisplay,targetValue:i.targetValue??a.targetValue}}if(e.role==="groupby"&&t.role==="groupby"){const i=e,a=t;return{...a,granularity:i.granularity??a.granularity,dateFormat:i.dateFormat??a.dateFormat,customFormat:i.customFormat??a.customFormat,timeDrillPath:i.timeDrillPath??a.timeDrillPath}}return t}function Ice(e,t,n,r){if(!n)return null;const o=tU(e,n||t,r);if(n&&o<0)return null;if(o>=0){const i=e[o],a=i==null?void 0:i.id,c=r!=null&&r.mergeMatchedField?r.mergeMatchedField(i,t):t,d=a&&a!==c.id&&!((i==null?void 0:i.fieldScope)==="domain"&&c.fieldScope==="domain")?{...c,id:a}:c;return e.map((f,h)=>h===o?d:f)}return null}function _ce(e,t){return{...e,fieldScope:t}}function _M(e){const t=_ce(e.updatedField,"card"),n=Ice(e.activeFields,t,e.editingField,{allowComparableFallback:e.previousScope==="dashboard",mergeMatchedField:Tce}),r=rU(e.storedFields,t,e.editingField,{allowComparableFallback:e.previousScope==="dashboard"}),s=e.previousScope==="dashboard"&&e.editingField?jm(e.sharedFields,e.editingField,{allowComparableFallback:!0}):e.sharedFields;return{nextActiveFields:n,nextStoredFields:r,nextSharedFields:s}}function DM(e){const t=_ce(e.updatedField,"dashboard"),n=Ice(e.activeFields,t,e.editingField,{allowComparableFallback:e.previousScope==="dashboard",mergeMatchedField:Tce}),r=rU(e.sharedFields,t,e.editingField,{allowComparableFallback:!0}),s=e.previousScope==="card"&&e.editingField?jm(e.storedFields,e.editingField,{allowComparableFallback:!0}):e.storedFields;return{nextActiveFields:n,nextStoredFields:s,nextSharedFields:r}}function Nm(e){const{nextSharedFields:t,currentSharedFields:n,isVisualEditing:r,selectedSheetId:s,updateFrame:o,updateSheetCalculatedFields:i,currentFrame:a,nextFramePatch:c,persistFrame:u,persistFrames:d}=e,f=c?{...c,calculatedFields:t}:{calculatedFields:t};(t!==n||c)&&o(f),s&&(r||(u&&(d!=null&&d.length)?d.forEach(h=>{u(s,{...h,calculatedFields:void 0})}):u&&a&&c&&u(s,{...a,...c,calculatedFields:void 0}),i&&i(s,t)))}const Dce=C.memo(function({context:t="editor",onFieldSelect:n,inlineFilters:r}={}){var Ot,bt,an,Tt;const[s,o]=C.useState(""),[i,a]=C.useState("all"),[c,u]=C.useState(!1),[d,f]=C.useState(null),[h,m]=C.useState("card"),[p,g]=C.useState("metric"),[x,b]=C.useState(null),[y,v]=C.useState(!1);Ve(Ce=>Ce.isDevMode);const w=Ve(Ce=>Ce.card.dataSource),S=Ve(Ce=>Ce.card.config),N=Ve(Ce=>Ce.card),j=Ve(Ce=>Ce.frame),k=Ve(Ce=>Ce.actions.updateCardConfig),T=Ve(Ce=>Ce.actions.updateCard),E=Ve(Ce=>Ce.actions.updateFrame),I=te(Ce=>Ce.isVisualEditing),_=te(Ce=>Ce.selectedSheetId),P=te(Ce=>Ce.actions.updateSheetCalculatedFields),{userContext:M}=zo(),{autoJoinMetadata:R}=Dl(N),{rawColumnGroups:L,scopedFields:O,dashboardFilterableFields:U,inlineFilterableFields:z,scopedCalculatedFields:A,sharedCalculatedFields:W,inlineCalculatedFields:$,isLoading:D,error:q}=Kle(),Q=(w==null?void 0:w.mode)==="semanticDomain"?w.semanticDomainId:void 0,{data:Y}=eL(Q),V=C.useMemo(()=>[...(S==null?void 0:S.groupByColumns)||[],...(S==null?void 0:S.metricColumns)||[],...(S==null?void 0:S.detailColumns)||[]],[S==null?void 0:S.groupByColumns,S==null?void 0:S.metricColumns,S==null?void 0:S.detailColumns]);(bt=(Ot=S==null?void 0:S.joinPlan)==null?void 0:Ot.baseEntity)==null||bt.name,(Tt=(an=R==null?void 0:R.resolvedJoinPlan)==null?void 0:an.baseEntity)==null||Tt.name,nce();const Z=t==="editor"?A:t==="filter"?W:$,B=Z.length>0,H=(M==null?void 0:M.type)==="organization",G=t==="editor"?O:t==="filter"?U:z,K=L,X=s.toLowerCase(),ne=(S==null?void 0:S.metricColumns)||[],ce=(S==null?void 0:S.groupByColumns)||[],ee=N.calculatedFields||[],ie=Ce=>Ce.name.toLowerCase().includes(X)||Ce.dataType.toLowerCase().includes(X)||Ce.label&&Ce.label.toLowerCase().includes(X)||Ce.qualifiedEntityName&&Ce.qualifiedEntityName.toLowerCase().includes(X),re=C.useCallback(Ce=>(Ce.label||Ce.name).toLowerCase().trim(),[]),de=C.useCallback((Ce,rt)=>re(Ce).localeCompare(re(rt),void 0,{numeric:!0,sensitivity:"base"}),[re]),Me=G.filter(ie).sort(de),Ne=C.useCallback(Ce=>t==="editor"?Jg(Ce):Sa(Ce),[t]),je=Ce=>{if(Ne(Ce))return"calculated";if(Ce.dataType==="number"||Ce.dataType==="integer"||Ce.dataType==="float"||Ce.dataType==="decimal"||Ce.dataType==="currency")return"metrics";const rt=wn(Ce.dataType);return["date","string","boolean"].includes(rt)?"dimensions":rt==="number"?"metrics":"dimensions"},fe=Ce=>{const rt=Ce.filter(ie);return i==="all"?rt:rt.filter(ct=>je(ct)===i)},_e=i==="all"?Me:Me.filter(Ce=>je(Ce)===i),we=B?fe(Z).sort(de):[],oe=G.filter(Ce=>je(Ce)!=="calculated"),Ee=fe(oe).sort(de).reduce((Ce,rt)=>{const ct=rt.qualifiedEntityName||"Other Fields";return Ce[ct]||(Ce[ct]={label:Xf(rt.entityName),fields:[]}),Ce[ct].fields.push(rt),Ce},{}),he=C.useMemo(()=>Object.entries(Ee).map(([Ce,rt])=>{const ct=K.find(Jr=>Jr.entityName===Ce)||{entityName:Ce,label:rt.label},pn=Ce===Ao?"Domain Calculated Fields":ct.label||ct.entityName;return{groupName:Ce,groupLabel:pn,fields:[...rt.fields].sort(de)}}).sort((Ce,rt)=>Ce.groupLabel.localeCompare(rt.groupLabel,void 0,{numeric:!0,sensitivity:"base"})),[Ee,K,de]),me=Ce=>Ce.id||`${Ce.entityName}-${Ce.qualifiedEntityName}-${Ce.name}-${Ce.role||"field"}`,Pe=C.useMemo(()=>{const Ce=new Map;return G.forEach(ct=>{Ce.set(me(ct),EF(ct,{joinabilityMap:(Y==null?void 0:Y.joinabilityMap)||null,selectedFields:V,cardConfig:S,autoJoinMetadata:R}))}),Ce},[G,Y==null?void 0:Y.joinabilityMap,V,S,R]),ye=B?[{key:"scope-calculated",label:"Calculated Fields",fields:we}].filter(Ce=>Ce.fields.length>0):[],Le=[...ye.map(Ce=>Ce.key),...he.map(Ce=>Ce.groupName)],$e=Me.filter(Ce=>je(Ce)==="dimensions").length,Ye=Me.filter(Ce=>je(Ce)==="metrics").length,Ke=Me.filter(Ce=>je(Ce)==="calculated").length,Ze=Me.length>0&&t!=="inline-filter",st=t==="inline-filter"?"w-full":"w-[290px]";if(D)return l.jsx("div",{className:J("flex h-full flex-col items-center justify-center py-8",st),children:l.jsx(ld,{size:"md",color:"muted","aria-label":"Loading data"})});if(q)return l.jsxs("div",{className:J("flex h-full flex-col items-center justify-center py-8",st),children:[l.jsx(yl,{className:"mb-4 h-12 w-12 text-red-300"}),l.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),l.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:q.message||"Failed to load column data"})]});if(!w||!w.selectedEntities||w.selectedEntities.length===0)return l.jsxs("div",{className:J("flex flex-col items-center justify-center py-8 text-center",st),children:[l.jsx(yl,{className:"mb-4 h-12 w-12 text-gray-300"}),l.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),l.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 le=t==="inline-filter"?"px-3 pb-3":"px-3 pb-6",Oe=t==="inline-filter"?"overflow-hidden":"",ke=Ce=>Vht(Ce,{storedCalculatedFields:ee,metricFields:ne,groupByFields:ce}),Ie=Ce=>{T(N.id,{calculatedFields:jm(ee,Ce,{allowComparableFallback:Ce.fieldScope==="dashboard"})})},We=Ce=>{var rt;return(rt=j==null?void 0:j.calculatedFields)==null?void 0:rt.find(ct=>zu(ct,Ce))},Te=Ce=>{if(Ce.role==="metric"){k(N.id,{metricColumns:jm(ne,Ce,{allowComparableFallback:Ce.fieldScope==="dashboard"})});return}Ce.role==="groupby"&&k(N.id,{groupByColumns:jm(ce,Ce,{allowComparableFallback:Ce.fieldScope==="dashboard"})})},Ue=Ce=>{if(!j)return;const rt=jm(j.calculatedFields||[],Ce);Nm({nextSharedFields:rt,currentSharedFields:j.calculatedFields||[],isVisualEditing:I,selectedSheetId:_,updateFrame:E,updateSheetCalculatedFields:P})},et=Ce=>{if(!H)return;if(Ce.fieldScope==="domain"){qe.error("Domain calculated fields are read-only in this explorer.");return}if(Ce.fieldScope==="dashboard"){const ct=We(Ce);if(!ct)return;f(ct),m("dashboard"),g(ct.role==="metric"?"metric":"dimension"),u(!0);return}const rt=ke(Ce);rt&&(f(rt),m("card"),g(rt.role==="metric"?"metric":"dimension"),u(!0))},xt=async Ce=>{if(H){if(Ce.fieldScope==="domain"){qe.error("Domain calculated fields are read-only in this explorer.");return}if(Ce.fieldScope==="dashboard"){Ue(Ce),Te(Ce);return}Te(Ce),Ie(Ce)}},dt=async()=>{if(x){v(!0);try{await xt(x),b(null)}catch{}finally{v(!1)}}},St=Ce=>{if(!H)return null;const rt=Ce.fieldScope==="domain",ct=rt;return l.jsxs(xd,{children:[l.jsx(bd,{asChild:!0,children:l.jsx(se,{variant:"ghost",size:"icon",className:"h-6 w-6 rounded-full","aria-label":"Calculated field actions",children:l.jsx(_h,{className:"h-3.5 w-3.5"})})}),l.jsxs(Wc,{align:"end",className:"w-36",children:[rt?l.jsx(Bs,{disabled:!0,children:"Read Only In Explorer"}):l.jsx(Bs,{onClick:()=>et(Ce),children:"Edit"}),l.jsx(Bs,{className:"text-destructive focus:text-destructive",disabled:ct,onClick:()=>b(Ce),children:"Delete"})]})]})};return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:J("mt-2 flex h-full w-full grow flex-col gap-2",le,Oe),children:[l.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[G.length>0&&l.jsxs("div",{className:"relative",children:[l.jsx(Gs,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),l.jsx(at,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:s,onChange:Ce=>o(Ce.target.value)}),s&&l.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:l.jsx(Dt,{className:"size-3.5"})})]}),Ze&&l.jsx(Fs,{defaultValue:"all",value:i,onValueChange:Ce=>a(Ce),className:"mb-4",children:l.jsxs(ws,{className:"grid h-11 w-full grid-cols-4 rounded-lg border border-border/60 bg-muted/50 p-1",children:[l.jsxs(on,{value:"all",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:["All",l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:Me.length})]}),l.jsxs(on,{value:"dimensions",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:[l.jsx(fN,{className:"size-3.5 shrink-0"}),l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:$e})]}),l.jsxs(on,{value:"metrics",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:[l.jsx(aN,{className:"size-3.5 shrink-0"}),l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:Ye})]}),l.jsxs(on,{value:"calculated",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:[l.jsx(MA,{className:"size-3.5 shrink-0"}),l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:Ke})]})]})}),t==="editor"&&i==="calculated"&&H&&l.jsx("div",{className:"flex items-center justify-end gap-2",children:l.jsxs(se,{size:"sm",variant:"outline",className:"w-full",onClick:()=>{f(null),m("card"),g("dimension"),u(!0)},children:[l.jsx(Br,{className:"mr-2 h-3.5 w-3.5"}),"Add calculated field"]})})]}),l.jsxs(Ua,{className:"min-h-0 flex-1",children:[l.jsxs(OE,{type:"multiple",defaultValue:Le,className:"space-y-2",children:[ye.map(Ce=>l.jsxs(qp,{value:Ce.key,className:"border-none",children:[l.jsx(Gp,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:Ce.label}),l.jsx(Xe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:Ce.fields.length})]})}),l.jsx(Yp,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:Ce.fields.map(rt=>{const ct=Pe.get(me(rt)),pn=t==="editor"&&H&&Sa(rt);return l.jsx(yB,{field:rt,context:t,fieldState:ct,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0,actions:pn?St(rt):void 0},rt.id)})})})]},Ce.key)),he.map(({groupName:Ce,groupLabel:rt,fields:ct})=>l.jsxs(qp,{value:Ce,className:"border-none",children:[l.jsx(Gp,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{title:rt,className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:rt}),l.jsx(Xe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:ct.length})]})}),l.jsx(Yp,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:ct.map(pn=>{const Jr=Pe.get(me(pn)),Nr=t==="editor"&&H&&Sa(pn);return l.jsx(yB,{field:pn,context:t,fieldState:Jr,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0,actions:Nr?St(pn):void 0},pn.id)})})})]},Ce))]}),G.length===0&&l.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[l.jsx("p",{children:"No fields found for selected data source"}),l.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"})]}),G.length>0&&_e.length===0&&l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),l.jsx(Fa,{orientation:"horizontal"}),l.jsx(Fa,{orientation:"vertical"})]})]}),l.jsx(Gc,{open:!!x,onOpenChange:Ce=>{Ce||b(null)},children:l.jsxs(zl,{children:[l.jsxs(Vl,{children:[l.jsx(Ul,{children:"Delete calculated field?"}),l.jsxs(Hl,{children:["This will remove"," ",l.jsx("span",{className:"font-medium text-foreground",children:(x==null?void 0:x.label)||(x==null?void 0:x.name)||"this calculated field"})," ",(x==null?void 0:x.fieldScope)==="domain"?"from the semantic domain.":"from this configuration."]})]}),l.jsxs(Bl,{children:[l.jsx(ql,{disabled:y,children:"Cancel"}),l.jsx(Wl,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:y,onClick:Ce=>{Ce.preventDefault(),dt()},children:y?"Deleting...":"Delete"})]})]})}),l.jsx(kce,{open:c,onOpenChange:Ce=>{u(Ce),Ce||(f(null),m("card"))},availableFields:O,existingField:d??void 0,existingFieldScope:h,initialFieldType:p,onSave:Ce=>{const rt=d,ct=(j==null?void 0:j.calculatedFields)||[];if(Ce.role==="metric"){const{nextActiveFields:es,nextStoredFields:ri,nextSharedFields:yo}=_M({activeFields:ne,storedFields:ee,sharedFields:ct,updatedField:Ce,editingField:rt,previousScope:h});es&&k(N.id,{metricColumns:es}),T(N.id,{calculatedFields:ri}),j&&yo!==ct&&Nm({nextSharedFields:yo,currentSharedFields:ct,isVisualEditing:I,selectedSheetId:_,updateFrame:E,updateSheetCalculatedFields:P});return}const{nextActiveFields:pn,nextStoredFields:Jr,nextSharedFields:Nr}=_M({activeFields:ce,storedFields:ee,sharedFields:ct,updatedField:Ce,editingField:rt,previousScope:h});pn&&k(N.id,{groupByColumns:pn}),T(N.id,{calculatedFields:Jr}),j&&Nr!==ct&&Nm({nextSharedFields:Nr,currentSharedFields:ct,isVisualEditing:I,selectedSheetId:_,updateFrame:E,updateSheetCalculatedFields:P})},onSaveToDashboard:Ce=>{const rt=d,ct=(j==null?void 0:j.calculatedFields)||[];if(Ce.role==="metric"){const{nextActiveFields:es,nextStoredFields:ri,nextSharedFields:yo}=DM({activeFields:ne,storedFields:ee,sharedFields:ct,updatedField:Ce,editingField:rt,previousScope:h});j&&Nm({nextSharedFields:yo,currentSharedFields:ct,isVisualEditing:I,selectedSheetId:_,updateFrame:E,updateSheetCalculatedFields:P}),es&&k(N.id,{metricColumns:es}),T(N.id,{calculatedFields:ri});return}const{nextActiveFields:pn,nextStoredFields:Jr,nextSharedFields:Nr}=DM({activeFields:ce,storedFields:ee,sharedFields:ct,updatedField:Ce,editingField:rt,previousScope:h});j&&Nm({nextSharedFields:Nr,currentSharedFields:ct,isVisualEditing:I,selectedSheetId:_,updateFrame:E,updateSheetCalculatedFields:P}),pn&&k(N.id,{groupByColumns:pn}),T(N.id,{calculatedFields:Jr})},cardId:N.id})]})}),Mce=C.memo(function({context:t="editor"}={}){return l.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",l.jsx(Dce,{context:t})," "]})});function Ace(){const e=Ve(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=lr();C.useEffect(()=>{var m;if(!e)return;const{tableName:i,schemaName:a,databaseName:c,connectionId:u}=nL(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(c||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function Uht(){Ace();const e=te(c=>c.selectedSheetId),t=te(c=>c.selectedFrameId),n=te(c=>c.dashboard),r=te(c=>c.actions.getSelectedFrame),{setSelectedFrameId:s}=en(),{setCard:o}=lr(),i=Ve(c=>c.card.dataSource);return C.useEffect(()=>{var u,d;let c=r();if(!c){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),c=h)}if(c){const f=c.cards.find(h=>h.id===c.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function Hht(){const e=te(o=>o.dashboard.filterLayout),{setFilterLayout:t}=en(),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 l.jsxs(Lr,{children:[l.jsx($r,{asChild:!0,children:l.jsx(se,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0","aria-label":"Filter display settings",children:l.jsx(vl,{className:"h-4 w-4"})})}),l.jsx(zr,{className:"w-[280px]",align:"end",children:l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("h4",{className:"mb-3 text-sm font-medium",children:"Filter Display"}),l.jsxs(ho,{value:n,onValueChange:o=>t({displayMode:o}),className:"space-y-2",children:[l.jsxs("div",{className:"flex items-start space-x-3",children:[l.jsx(In,{value:"canvas",id:"canvas",className:"mt-0.5"}),l.jsxs("div",{className:"grid gap-0.5",children:[l.jsx(xe,{htmlFor:"canvas",className:"cursor-pointer font-normal",children:"Canvas Cards"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Filters as draggable, resizable cards on the dashboard"})]})]}),l.jsxs("div",{className:"flex items-start space-x-3",children:[l.jsx(In,{value:"toolbar",id:"toolbar",className:"mt-0.5"}),l.jsxs("div",{className:"grid gap-0.5",children:[l.jsx(xe,{htmlFor:"toolbar",className:"cursor-pointer font-normal",children:"Toolbar"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Compact horizontal toolbar below dashboard controls"})]})]})]})]}),n==="toolbar"&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex items-center space-x-2 border-t pt-4",children:[l.jsx(Gt,{id:"wrap",checked:r,onCheckedChange:o=>t({toolbarWrap:o===!0})}),l.jsx(xe,{htmlFor:"wrap",className:"cursor-pointer text-sm font-normal",children:"Wrap filters to multiple lines"})]}),l.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[l.jsx(Gt,{id:"download",checked:s,onCheckedChange:o=>t({showDownloadButton:o===!0})}),l.jsx(xe,{htmlFor:"download",className:"cursor-pointer text-sm font-normal",children:"Show download button"})]})]}),l.jsx("p",{className:"border-t pt-3 text-xs text-muted-foreground",children:"Individual filters can override this setting in their configuration."})]})})]})}function Wht(){const e=te(n=>n.actions.setShowFilters),{hasEntities:t}=Uht();return l.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col overflow-hidden border-l",children:[l.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[l.jsx(xe,{className:"px-2 text-base",children:"Dashboard Filters"}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(Hht,{}),l.jsx(se,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:l.jsx(vse,{})})]})]}),!t&&l.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[l.jsx(yl,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),l.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&l.jsx("div",{className:"flex grow overflow-y-auto",children:l.jsx(vv,{collisionDetection:xv,children:l.jsx(wv,{items:[],strategy:r5,children:l.jsx(Mce,{context:"filter"})})})})]})}function qht(){const e=te(r=>r.dashboard.filters),t=te(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?l.jsx("div",{className:J("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=>l.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[l.jsx(ZO,{filter:r}),l.jsx(Bg,{filter:r})]},r.id))}):null}function Ght(){const e=te(r=>r.showFilters),t=te(r=>r.isVisualEditing),n=te(r=>r.isDashboardEditing);return l.jsxs("div",{role:"dashboard-plus-main",className:J("",{"max-h-0 overflow-hidden":t,"flex grow overflow-hidden":!t}),children:[l.jsxs("section",{className:"flex grow flex-col overflow-y-auto",children:[n&&l.jsx(qht,{}),l.jsx(Vle,{})]}),e&&l.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:l.jsx(Wht,{})})]})}const Yht=C.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-Zmrx1YI2.js"))),Kht=C.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-DBvH4PxE.js"))),Zht=C.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-B98ND-fr.js"))),Xht=C.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-C37Ddk0o.js")).then(e=>({default:e.ResourceManagementPanel})));function Qht({showControls:e=!1,showFooter:t=!0,...n}){const r=te(c=>c.isDashboardPanelOpen),s=te(c=>c.isVisualEditing),o=te(c=>c.showDashboardJSON),i=te(c=>c.actions.setIsDashboardPanelOpen),{preferences:a}=n;return l.jsx(Oa,{FallbackComponent:tE,children:l.jsxs(_A,{dashboardProps:n,children:[l.jsx(H0e,{}),l.jsx(Q5,{componentType:"surfboard",componentId:n.id}),l.jsx(X5,{children:l.jsxs(Ule,{preferences:a,children:[o&&l.jsx(C.Suspense,{fallback:null,children:l.jsx(Zht,{})}),l.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&l.jsx(C.Suspense,{fallback:null,children:l.jsx(Yht,{})}),l.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&l.jsx(C.Suspense,{fallback:null,children:l.jsx(Xht,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),l.jsx("div",{className:"flex min-w-0 flex-1",children:l.jsxs(QF,{...n,type:"dashboard",children:[s&&l.jsx(C.Suspense,{fallback:null,children:l.jsx(Kht,{})}),l.jsx(Ght,{})]})})]})]})]})})]})})}var Jht=Object.defineProperty,emt=(e,t,n)=>t in e?Jht(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,u1=(e,t,n)=>emt(e,typeof t!="symbol"?t+"":t,n);const tmt={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},nmt={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}},rmt={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function smt(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function Rce(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const omt={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=Rce(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},imt={stringify:e=>`${e}`,parse:e=>parseFloat(e)},amt={stringify:e=>e,parse:e=>e},QT={string:amt,number:imt,boolean:tmt,function:nmt,method:omt,json:rmt},Tx=Symbol.for("r2wc.render"),d1=Symbol.for("r2wc.connected"),Wd=Symbol.for("r2wc.context"),ai=Symbol.for("r2wc.props");function lmt(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),c={},u={},d={},f={};for(const m of i){c[m]=Array.isArray(t.props)?"string":t.props[m];const p=smt(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(),u1(this,o,!0),u1(this,s),u1(this,r,{}),u1(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[ai].container=this.container;for(const p of i){const g=d[p],x=this.getAttribute(g),b=c[p],y=b?QT[b]:null;if(b==="method"){const v=Rce(g);Object.defineProperty(this[ai].container,v,{enumerable:!0,configurable:!0,get(){return this[ai][v]},set(w){this[ai][v]=w,this[Tx]()}}),this[ai][p]=y.parse(x,g,this)}y!=null&&y.parse&&x&&(this[ai][p]=y.parse(x,g,this))}for(const p of a)this[ai][p]=g=>{const x=p.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(x,{detail:g,...u[p]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[d1]=!0,this[Tx]()}disconnectedCallback(){this[d1]=!1,this[Wd]&&n.unmount(this[Wd]),delete this[Wd]}attributeChangedCallback(p,g,x){const b=f[p],y=c[b],v=y?QT[y]:null;b in c&&v!=null&&v.parse&&x&&(this[ai][b]=v.parse(x,p,this),this[Tx]())}[(o=d1,s=Wd,r=ai,Tx)](){this[d1]&&(this[Wd]?n.update(this[Wd],this[ai]):this[Wd]=n.mount(this.container,e,this[ai]))}}for(const m of i){const p=d[m],g=c[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[ai][m]},set(x){this[ai][m]=x;const b=g?QT[g]:null;if(b!=null&&b.stringify){const y=b.stringify(x,p,this);this.getAttribute(p)!==y&&this.setAttribute(p,y)}else this[Tx]()}})}return h}function cmt(e,t,n){const r=Eue.createRoot(e),s=C.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function umt({root:e,ReactComponent:t},n){const r=C.createElement(t,n);e.render(r)}function dmt({root:e}){e.unmount()}function fmt(e,t={}){return lmt(e,t,{mount:cmt,update:umt,unmount:dmt})}const hmt={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",defaultControlValues:"json",controlContractOverrides:"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"},mmt=fmt(Hle,{props:hmt});var Fce={},Cs=Kr&&Kr.__assign||function(){return Cs=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++){t=arguments[n];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s])}return e},Cs.apply(this,arguments)},pmt=Kr&&Kr.__createBinding||(Object.create?function(e,t,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(t,n);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,s)}:function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),gmt=Kr&&Kr.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),xmt=Kr&&Kr.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&pmt(t,e,n);return gmt(t,e),t},bmt=Kr&&Kr.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(n[r[s]]=e[r[s]]);return n};Object.defineProperty(Fce,"__esModule",{value:!0});var Di=xmt(C),ymt=89,f1=90,vmt=77,TB=57,IB=219,_B=222,DB=192,MB=100,wmt=3e3,Cmt=typeof window<"u"&&"navigator"in window&&/Win/i.test(navigator.platform),JT=typeof window<"u"&&"navigator"in window&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),H1="npm__react-simple-code-editor__textarea",Smt=`
|
|
1394
1394
|
/**
|
|
1395
1395
|
* Reset the text fill color so that placeholder is visible
|
|
1396
1396
|
*/
|