react-semaphor 0.1.211 → 0.1.213
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-CnDq9Uh_.js → dashboard-controls-BcpwRqRu.js} +13 -8
- package/dist/chunks/{dashboard-controls-7KpXzAWL.js → dashboard-controls-DG0FT__o.js} +373 -359
- package/dist/chunks/{dashboard-json-dqey5VK0.js → dashboard-json-C1b81ShY.js} +1 -1
- package/dist/chunks/{dashboard-json-stWvjp2O.js → dashboard-json-F8qwUIWM.js} +1 -1
- package/dist/chunks/{dashboard-summary-settings-dialog-DuxhidK1.js → dashboard-summary-settings-dialog-CsjLFOn-.js} +1 -1
- package/dist/chunks/{dashboard-summary-settings-dialog-DPEe6XBC.js → dashboard-summary-settings-dialog-yytNDqsJ.js} +1 -1
- package/dist/chunks/{edit-dashboard-visual-D_XPr8f8.js → edit-dashboard-visual-B-qAacmt.js} +1 -1
- package/dist/chunks/{edit-dashboard-visual-CQAk_UsI.js → edit-dashboard-visual-C-Y0fhBE.js} +2 -2
- package/dist/chunks/{editor-action-buttons-D34_GSZu.js → editor-action-buttons-BddCK22U.js} +2 -2
- package/dist/chunks/{editor-action-buttons-CH7W6KdH.js → editor-action-buttons-Dr9s7Z0u.js} +1 -1
- package/dist/chunks/{index-BfiIPyeS.js → index-irqsC0zR.js} +1 -1
- package/dist/chunks/{index-BDS2sWhv.js → index-tdtX3LgC.js} +4 -4
- package/dist/chunks/{notification-bell-hijGST9g.js → notification-bell-CRzJdHm5.js} +2 -2
- package/dist/chunks/{notification-bell-Cu3qDd9V.js → notification-bell-Ci1RHooZ.js} +137 -135
- package/dist/chunks/{resource-management-panel-BvHqslqC.js → resource-management-panel-CaKSsCiq.js} +3 -3
- package/dist/chunks/{resource-management-panel-gK3a6OEj.js → resource-management-panel-cwMyqyn1.js} +1 -1
- package/dist/chunks/{use-role-aware-display-preferences-a5FH9Y0k.js → use-role-aware-display-preferences-CImfZXy5.js} +1 -1
- package/dist/chunks/{use-role-aware-display-preferences-BlR29aKQ.js → use-role-aware-display-preferences-D5eZpiQS.js} +1 -1
- package/dist/chunks/{use-visual-utils-ptPsQ3nC.js → use-visual-utils-0xqPjTL6.js} +1 -1
- package/dist/chunks/{use-visual-utils-B11AA2fd.js → use-visual-utils-BAVRApHw.js} +1 -1
- 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/dist/types/main.d.ts +3 -1
- package/package.json +1 -1
|
@@ -1096,7 +1096,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
1096
1096
|
|
|
1097
1097
|
`)},flush(e){e.enqueue(`data: [DONE]
|
|
1098
1098
|
|
|
1099
|
-
`)}})}});var Srt=pnt(()=>Hse(Ui([Sr({type:rn("text-start"),id:kt(),providerMetadata:Br.optional()}),Sr({type:rn("text-delta"),id:kt(),delta:kt(),providerMetadata:Br.optional()}),Sr({type:rn("text-end"),id:kt(),providerMetadata:Br.optional()}),Sr({type:rn("error"),errorText:kt()}),Sr({type:rn("tool-input-start"),toolCallId:kt(),toolName:kt(),providerExecuted:To().optional(),dynamic:To().optional()}),Sr({type:rn("tool-input-delta"),toolCallId:kt(),inputTextDelta:kt()}),Sr({type:rn("tool-input-available"),toolCallId:kt(),toolName:kt(),input:Va(),providerExecuted:To().optional(),providerMetadata:Br.optional(),dynamic:To().optional()}),Sr({type:rn("tool-input-error"),toolCallId:kt(),toolName:kt(),input:Va(),providerExecuted:To().optional(),providerMetadata:Br.optional(),dynamic:To().optional(),errorText:kt()}),Sr({type:rn("tool-output-available"),toolCallId:kt(),output:Va(),providerExecuted:To().optional(),dynamic:To().optional(),preliminary:To().optional()}),Sr({type:rn("tool-output-error"),toolCallId:kt(),errorText:kt(),providerExecuted:To().optional(),dynamic:To().optional()}),Sr({type:rn("reasoning-start"),id:kt(),providerMetadata:Br.optional()}),Sr({type:rn("reasoning-delta"),id:kt(),delta:kt(),providerMetadata:Br.optional()}),Sr({type:rn("reasoning-end"),id:kt(),providerMetadata:Br.optional()}),Sr({type:rn("source-url"),sourceId:kt(),url:kt(),title:kt().optional(),providerMetadata:Br.optional()}),Sr({type:rn("source-document"),sourceId:kt(),mediaType:kt(),title:kt(),filename:kt().optional(),providerMetadata:Br.optional()}),Sr({type:rn("file"),url:kt(),mediaType:kt(),providerMetadata:Br.optional()}),Sr({type:Lse(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:kt().optional(),data:Va(),transient:To().optional()}),Sr({type:rn("start-step")}),Sr({type:rn("finish-step")}),Sr({type:rn("start"),messageId:kt().optional(),messageMetadata:Va().optional()}),Sr({type:rn("finish"),finishReason:Ose(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:Va().optional()}),Sr({type:rn("abort")}),Sr({type:rn("message-metadata"),messageMetadata:Va()})])));function Crt(e){return e.type.startsWith("data-")}function Qse(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]=Qse(o,s):n[r]=s}return n}function Nrt(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 Jse(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await BS({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await BS({text:Nrt(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Hw(e){return e.type.startsWith("tool-")}function jrt(e){return e.type==="dynamic-tool"}function HM(e){return Hw(e)||jrt(e)}function a9(e){return e.type.split("-").slice(1).join("-")}function krt({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 Ert({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(S){const C=u.message.parts.filter(Hw).find(j=>j.toolCallId===S);if(C==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return C}function b(S){const C=u.message.parts.filter(j=>j.type==="dynamic-tool").find(j=>j.toolCallId===S);if(C==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return C}function x(S){var N;const C=u.message.parts.find(M=>Hw(M)&&M.toolCallId===S.toolCallId),j=S,E=C;C!=null?(C.state=S.state,E.input=j.input,E.output=j.output,E.errorText=j.errorText,E.rawInput=j.rawInput,E.preliminary=j.preliminary,E.providerExecuted=(N=j.providerExecuted)!=null?N:C.providerExecuted,j.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:`tool-${S.toolName}`,toolCallId:S.toolCallId,state:S.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(S){var N,C;const j=u.message.parts.find(k=>k.type==="dynamic-tool"&&k.toolCallId===S.toolCallId),E=S,M=j;j!=null?(j.state=S.state,M.toolName=S.toolName,M.input=E.input,M.output=E.output,M.errorText=E.errorText,M.rawInput=(N=E.rawInput)!=null?N:M.rawInput,M.preliminary=E.preliminary,M.providerExecuted=(C=E.providerExecuted)!=null?C:j.providerExecuted,E.providerMetadata!=null&&j.state==="input-available"&&(j.callProviderMetadata=E.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:S.toolName,toolCallId:S.toolCallId,state:S.state,input:E.input,output:E.output,errorText:E.errorText,preliminary:E.preliminary,providerExecuted:E.providerExecuted,...E.providerMetadata!=null?{callProviderMetadata:E.providerMetadata}:{}})}async function v(S){if(S!=null){const N=u.message.metadata!=null?Qse(u.message.metadata,S):S;t!=null&&await n9({value:N,schema:t}),u.message.metadata=N}}switch(a.type){case"text-start":{const S={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=S,u.message.parts.push(S),d();break}case"text-delta":{const S=u.activeTextParts[a.id];S.text+=a.delta,S.providerMetadata=(f=a.providerMetadata)!=null?f:S.providerMetadata,d();break}case"text-end":{const S=u.activeTextParts[a.id];S.state="done",S.providerMetadata=(h=a.providerMetadata)!=null?h:S.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const S={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=S,u.message.parts.push(S),d();break}case"reasoning-delta":{const S=u.activeReasoningParts[a.id];S.text+=a.delta,S.providerMetadata=(m=a.providerMetadata)!=null?m:S.providerMetadata,d();break}case"reasoning-end":{const S=u.activeReasoningParts[a.id];S.providerMetadata=(p=a.providerMetadata)!=null?p:S.providerMetadata,S.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 S=u.message.parts.filter(Hw);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:S.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const S=u.partialToolCalls[a.toolCallId];S.text+=a.inputTextDelta;const{value:N}=await Jse(S.text);S.dynamic?y({toolCallId:a.toolCallId,toolName:S.toolName,state:"input-streaming",input:N}):x({toolCallId:a.toolCallId,toolName:S.toolName,state:"input-streaming",input:N}),d();break}case"tool-input-available":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d();break}case"tool-output-available":{if(a.dynamic){const S=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:S.toolName,state:"output-available",input:S.input,output:a.output,preliminary:a.preliminary})}else{const S=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:a9(S),state:"output-available",input:S.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const S=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:S.toolName,state:"output-error",input:S.input,errorText:a.errorText,providerExecuted:a.providerExecuted})}else{const S=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:a9(S),state:"output-error",input:S.input,rawInput:S.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(Crt(a)){(n==null?void 0:n[a.type])!=null&&await n9({value:a.data,schema:n[a.type]});const S=a;if(S.transient){i==null||i(S);break}const N=S.id!=null?u.message.parts.find(C=>S.type===C.type&&S.id===C.id):void 0;N!=null?N.data=S.data:u.message.parts.push(S),i==null||i(S),d()}}c.enqueue(a)})}}))}async function _rt({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()}}A0({prefix:"aitxt",size:24});A0({prefix:"aiobj",size:24});var Trt=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()})}};A0({prefix:"aiobj",size:24});var Mrt={};frt(Mrt,{object:()=>Drt,text:()=>Irt});var Irt=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),Drt=({schema:e})=>{const t=urt(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await Jse(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 BS({text:n});if(!s.success)throw new o9({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 VO({value:s.value,schema:t});if(!o.success)throw new o9({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 Art(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 Rrt=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 Lh(this.body),c=await Lh(this.headers),u=await Lh(this.credentials),d={...$d(c),...$d(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?$d(f.headers):d,p=(f==null?void 0:f.body)!==void 0?f.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},g=(s=f==null?void 0:f.credentials)!=null?s:u,x=await((o=this.fetch)!=null?o:globalThis.fetch)(h,{method:"POST",headers:e9({"Content-Type":"application/json",...m},`ai-sdk/${i9}`,J8()),body:JSON.stringify(p),credentials:g,signal:e});if(!x.ok)throw new Error((i=await x.text())!=null?i:"Failed to fetch the chat response.");if(!x.body)throw new Error("The response body is empty.");return this.processResponseStream(x.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await Lh(this.body),a=await Lh(this.headers),c=await Lh(this.credentials),u={...$d(a),...$d(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?$d(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:e9(h,`ai-sdk/${i9}`,J8()),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)}},HO=class extends Rrt{constructor(e={}){super(e)}processResponseStream(e){return xnt({stream:e,schema:Srt}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},Prt=class{constructor({generateId:e=lnt,id:t=e(),transport:n=new HO,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:c,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new Trt,this.sendMessage=async(f,h)=>{var m,p,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(m=this.lastMessage)==null?void 0:m.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await Art(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:x=f,f.messageId!=null){const y=this.state.messages.findIndex(v=>v.id===f.messageId);if(y===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[y].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,y+1),this.state.replaceMessage(y,{...x,id:f.messageId,role:(p=x.role)!=null?p:"user",metadata:f.metadata})}else this.state.pushMessage({...x,id:(g=x.id)!=null?g:this.generateId(),role:(b=x.role)!=null?b:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const m=f==null?this.state.messages.length-1:this.state.messages.findIndex(p=>p.id===f);if(m===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[m].role==="assistant"?m:m+1),await this.makeRequest({trigger:"regenerate-message",messageId:f,...h})},this.resumeStream=async(f={})=>{await this.makeRequest({trigger:"resume-stream",...f})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolOutput=async({state:f="output-available",tool:h,toolCallId:m,output:p,errorText:g})=>this.jobExecutor.run(async()=>{var b,x;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(S=>HM(S)&&S.toolCallId===m?{...S,state:f,output:p,errorText:g}:S)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(S=>HM(S)&&S.toolCallId===m?{...S,state:f,output:p,errorText:g}:S)),this.status!=="streaming"&&this.status!=="submitted"&&((b=this.sendAutomaticallyWhen)!=null&&b.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(x=this.lastMessage)==null?void 0:x.id})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=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:krt({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};m.abortController.signal.addEventListener("abort",()=>{d=!0}),this.activeResponse=m;let p;if(e==="resume-stream"){const b=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(b==null){this.setStatus({status:"ready"});return}p=b}else p=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:m.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const g=b=>this.jobExecutor.run(()=>b({state:m.state,write:()=>{var x;this.setStatus({status:"streaming"}),m.state.message.id===((x=this.lastMessage)==null?void 0:x.id)?this.state.replaceMessage(this.state.messages.length-1,m.state.message):this.state.pushMessage(m.state.message)}}));await _rt({stream:Ert({stream:p,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:g,onError:b=>{throw b}}),onError:b=>{throw b}}),this.setStatus({status:"ready"})}catch(m){if(d||m.name==="AbortError")return d=!0,this.setStatus({status:"ready"}),null;h=!0,m instanceof TypeError&&(m.message.toLowerCase().includes("fetch")||m.message.toLowerCase().includes("network"))&&(f=!0),this.onError&&m instanceof Error&&this.onError(m),this.setStatus({status:"error",error:m})}finally{try{(i=this.onFinish)==null||i.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:d,isDisconnect:f,isError:h,finishReason:(o=this.activeResponse)==null?void 0:o.state.finishReason})}catch(m){console.error(m)}this.activeResponse=void 0}(a=this.sendAutomaticallyWhen)!=null&&a.call(this,{messages:this.state.messages})&&!h&&await this.makeRequest({trigger:"submit-message",messageId:(c=this.lastMessage)==null?void 0:c.id,metadata:t,headers:n,body:r})}};function Ort({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(HM).filter(s=>!s.providerExecuted);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function Frt(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 $rt=Frt;const Lrt=Qf($rt);var eoe=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},ar=(e,t,n)=>(eoe(e,t,"read from private field"),n?n.call(e):t.get(e)),$a=(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)},Yc=(e,t,n,r)=>(eoe(e,t,"write to private field"),t.set(e,n),n);function zrt(e,t){return t!=null?Lrt(e,t):e}var bi,Ww,qw,Cb,Nb,jb,qh,WM,qM,Brt=class{constructor(e=[]){$a(this,bi,void 0),$a(this,Ww,"ready"),$a(this,qw,void 0),$a(this,Cb,new Set),$a(this,Nb,new Set),$a(this,jb,new Set),this.pushMessage=t=>{Yc(this,bi,ar(this,bi).concat(t)),ar(this,qh).call(this)},this.popMessage=()=>{Yc(this,bi,ar(this,bi).slice(0,-1)),ar(this,qh).call(this)},this.replaceMessage=(t,n)=>{Yc(this,bi,[...ar(this,bi).slice(0,t),this.snapshot(n),...ar(this,bi).slice(t+1)]),ar(this,qh).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?zrt(t,n):t;return ar(this,Cb).add(r),()=>{ar(this,Cb).delete(r)}},this["~registerStatusCallback"]=t=>(ar(this,Nb).add(t),()=>{ar(this,Nb).delete(t)}),this["~registerErrorCallback"]=t=>(ar(this,jb).add(t),()=>{ar(this,jb).delete(t)}),$a(this,qh,()=>{ar(this,Cb).forEach(t=>t())}),$a(this,WM,()=>{ar(this,Nb).forEach(t=>t())}),$a(this,qM,()=>{ar(this,jb).forEach(t=>t())}),Yc(this,bi,e)}get status(){return ar(this,Ww)}set status(e){Yc(this,Ww,e),ar(this,WM).call(this)}get error(){return ar(this,qw)}set error(e){Yc(this,qw,e),ar(this,qM).call(this)}get messages(){return ar(this,bi)}set messages(e){Yc(this,bi,[...e]),ar(this,qh).call(this)}};bi=new WeakMap;Ww=new WeakMap;qw=new WeakMap;Cb=new WeakMap;Nb=new WeakMap;jb=new WeakMap;qh=new WeakMap;WM=new WeakMap;qM=new WeakMap;var Yh,l9=class extends Prt{constructor({messages:e,...t}){const n=new Brt(e);super({...t,state:n}),$a(this,Yh,void 0),this["~registerMessagesCallback"]=(r,s)=>ar(this,Yh)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>ar(this,Yh)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>ar(this,Yh)["~registerErrorCallback"](r),Yc(this,Yh,n)}};Yh=new WeakMap;function toe({experimental_throttle:e,resume:t=!1,...n}={}){const r=w.useRef("chat"in n?n.chat:new l9(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new l9(n));const o=w.useCallback(d=>r.current["~registerMessagesCallback"](d,e),[e,r.current.id]),i=w.useSyncExternalStore(o,()=>r.current.messages,()=>r.current.messages),a=w.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),c=w.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),u=w.useCallback(d=>{typeof d=="function"&&(d=d(r.current.messages)),r.current.messages=d},[r]);return w.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:i,setMessages:u,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:c,resumeStream:r.current.resumeStream,status:a,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput}}function Vrt(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function Urt(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function Hrt(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function Wrt(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function noe(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:Wrt(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function roe(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 qrt(){var b;const{authToken:e,tokenProps:t}=Je(),n=Q(x=>x.dashboard.aiScopeTables),r=(b=tC().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:c,addToolResult:u,error:d,stop:f,clearError:h}=toe({transport:new HO({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=Ia.getState();return{assistantId:"dashboard-assistant",assistantProfileId:r,aiContext:x.currentAIContext,reasoningEffort:x.reasoningEffort,showReasoning:x.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:x,body:y})=>({body:{...y,messages:WK(x)}})}),onToolCall:m,sendAutomaticallyWhen:Ort,onFinish({isAbort:x,isDisconnect:y,isError:v}){console.log(x?"[Dashboard Assistant] Stream aborted by user":y?"[Dashboard Assistant] Stream disconnected (network error)":v?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully")},onError(x){var y;if(x.name==="AbortError"||(y=x.message)!=null&&y.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)");return}console.error("[Dashboard Assistant] Stream error:",x)}});async function m({toolCall:x}){if(x.toolName==="getCurrentTableScope"&&u({tool:x.toolName,toolCallId:x.toolCallId,output:{tables:noe(n||[])}}),x.toolName==="getDashboardContext"){const y=Q.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const p=!["ready","error"].includes(c),g=roe(d);return{sendMessage:s,regenerate:a,isLoading:p,messages:o,setMessages:i,status:c,stop:f,errorMessage:g,clearError:h}}function soe(){var u;const{authToken:e,tokenProps:t}=Je(),n=(u=tC().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=Jt({queryKey:["assistant-profile",n],queryFn:()=>yr(`${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 ooe({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(J7,{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(re,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function VS(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return l.jsx(YI,{className:r});case"view":return l.jsx(Iu,{className:r});case"materialized view":return l.jsx(oue,{className:r});case"model":return l.jsx(aC,{className:r});case"file":return l.jsx(Fi,{className:r});case"dataset":return l.jsx(rl,{className:r});case"upload":return l.jsx(XI,{className:r});case"url":return l.jsx(oB,{className:r});default:return l.jsx(Ny,{className:r})}}const ioe=D.forwardRef(({className:e,...t},n)=>l.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[l.jsx(zo,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),l.jsx(oo.Input,{ref:n,className:X("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));ioe.displayName=oo.Input.displayName;const hw=e=>e.label||(e==null?void 0:e.name),c9=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function Yrt({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:c,onAddContext:u}){const{tokenProps:d}=Je(),f=(d==null?void 0:d.type)==="dashboard",[h,m]=w.useState(""),[p,g]=w.useState(""),b=s.filter(C=>{if(!h)return!0;const j=hw(C).toLowerCase(),E=c9(C).toLowerCase(),M=h.toLowerCase();return j.includes(M)||E.includes(M)});w.useEffect(()=>{e||(m(""),g(""))},[e]),w.useEffect(()=>{b.length>0&&!p&&g(hw(b[0]))},[b,p]);const x=()=>{if(!p)return;const C=b.find(j=>hw(j)===p);C&&(o.some(E=>"id"in C&&"id"in E?C.id===E.id:C.name===E.name&&C.connectionId===E.connectionId)||t(C),i(C),r())},y=C=>{(C.key==="Tab"||C.key==="Enter")&&(C.preventDefault(),x())};if(!e)return null;const v=C=>o.some(j=>"id"in C&&"id"in j?C.id===j.id:C.name===j.name&&C.connectionId===j.connectionId),S=o.length===s.length,N=o.length>0;return l.jsx(l.Fragment,{children:l.jsxs(Kp,{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(ioe,{placeholder:"Search entities...",value:h,onValueChange:m,className:"flex-1 border-0",autoFocus:!0}),!f&&l.jsxs(re,{onClick:C=>{C.preventDefault(),C.stopPropagation(),u==null||u()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[l.jsx(Rr,{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(re,{onClick:C=>{C.preventDefault(),C.stopPropagation(),a==null||a()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},disabled:S,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),N&&l.jsxs(re,{onClick:C=>{C.preventDefault(),C.stopPropagation(),c==null||c()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[l.jsx(Vt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),l.jsxs(Zp,{className:"min-h-60",children:[l.jsx(Xp,{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(re,{onClick:C=>{C.preventDefault(),C.stopPropagation(),u==null||u()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[l.jsx(Rr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),l.jsx(Qp,{children:b.map((C,j)=>{const E=v(C),M="id"in C?C.id:`${C.connectionId}-${C.name}`,k=hw(C);return l.jsxs(Jp,{value:k,onSelect:()=>{E?n==null||n(C):t(C)},onMouseDown:_=>{_.preventDefault(),_.stopPropagation()},className:X("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:VS(C.type)}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate font-medium",children:k}),l.jsx("div",{className:"truncate text-xs text-muted-foreground",children:c9(C)})]}),E&&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(Hr,{className:"h-3 w-3 text-background"})})]},M)})})]})]})})}const YM=e=>e.name||e.name,Grt=e=>{const t=YM(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 Krt({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r}){const[s,o]=w.useState(!1),i=e.length>0;e.length,t.length,e.length<t.length;const a=e.length>=3?e.slice(0,2):e,c=e.length>=3?e.slice(2):[],u=c.length>0;return l.jsx(nr,{children:l.jsx("div",{className:"space-y-2",children:i&&l.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.map((d,f)=>{const h="id"in d?d.id:`${d.connectionId}-${d.name}`;return l.jsxs(kn,{children:[l.jsx(En,{asChild:!0,children:l.jsxs(st,{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:[VS(d.type,{size:"h-3 w-3"}),l.jsx("span",{className:"max-w-24 truncate text-xs",children:YM(d)}),l.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(d),children:l.jsx(Vt,{className:"h-3 w-3"})})]})}),l.jsx(In,{side:"top",className:"max-w-xs",children:Grt(d)})]},h)}),u&&l.jsxs(kn,{open:s,onOpenChange:o,children:[l.jsx(En,{asChild:!0,children:l.jsxs(st,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>o(!0),children:[l.jsx(nB,{className:"h-3 w-3"}),l.jsxs("span",{className:"text-xs",children:[c.length," more"]}),l.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(c),children:l.jsx(Vt,{className:"h-3 w-3"})})]})}),l.jsx(In,{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:c.map(d=>{const f="id"in d?d.id:`${d.connectionId}-${d.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:VS(d.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:YM(d)}),l.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),l.jsx(re,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(d),c.length===1&&o(!1)},children:l.jsx(Vt,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function aoe(e){return e.type==="dataset"&&e.label||e.name}function Zrt(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 Xrt({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:l.jsxs("div",{className:"mb-4 space-y-2",children:[l.jsxs(de,{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(st,{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,"]"]}),aoe(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(Vt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function Qrt(e){const{tokenProps:t}=Je(),n=Q(c=>c.authToken)||e;Le(c=>c.selectedConnectionId),Le(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}=Jt({queryKey:["semantic-domains"],queryFn:()=>yr(`${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 Jrt(e,t){const{tokenProps:n}=Je(),r=Q(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:c}=Jt({queryKey:["datasets",e],queryFn:()=>yr(`${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 est(e){var g,b;const{tokenProps:t}=Je(),n=Q(x=>x.authToken)||e,{connections:r}=mi(e),s=Le(x=>{var y,v;return(v=(y=x==null?void 0:x.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(x=>x.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,c=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(x){var y;return!s||!x?!1:!!((y=o==null?void 0:o.capabilities)!=null&&y.path.includes("database"))}const{data:d,isPending:f,error:h,refetch:m}=Jt({queryKey:["databases",s],queryFn:()=>yr(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),p=(b=d==null?void 0:d.databases)==null?void 0:b.map(x=>({id:x.database_name,name:x.database_name}));return{isPending:f,error:h,databases:p||[],refetch:m,label:c}}function tst(e){var g;const{tokenProps:t}=Je(),n=Q(b=>b.authToken)||e,{connections:r}=mi(e),s=Le(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=Le(b=>{var x,y,v;return(v=(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(b=>b.id===s),a=i==null?void 0:i.capabilities,c=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){var b;return!(!s||!((b=i==null?void 0:i.capabilities)!=null&&b.path.includes("schema"))||!o)}const{data:d,isPending:f,error:h,refetch:m}=Jt({queryKey:["schemas",s,o],queryFn:()=>yr(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),p=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:p||[],refetch:m,label:c}}function loe(e){const{tokenProps:t}=Je(),n=Q(h=>h.authToken)||e,{connections:r}=mi(e),s=Le(h=>{var m,p;return(p=(m=h==null?void 0:h.card)==null?void 0:m.dataSource)==null?void 0:p.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:c,error:u,refetch:d}=Jt({queryKey:["dataModels",s],queryFn:()=>yr(`${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 nst(){var N,C,j;const e=Le(E=>E.card.dataSource);Le(E=>E.actions.updateDirectSource);const t=Le(E=>E.actions.updateDataSource),[n,r]=w.useState(""),{selectedConnection:s,error:o}=mi(),{databases:i,isPending:a,error:c,label:u}=est(),{schemas:d,isPending:f,error:h,label:m}=tst(),{error:p}=loe(),g=s==null?void 0:s.capabilities.path.includes("schema"),b=s==null?void 0:s.capabilities.path.includes("database"),x=u==null?void 0:u.toLowerCase(),y=m==null?void 0:m.toLowerCase(),v=E=>{e&&t({...e,dbSelection:{database:E,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},S=E=>{var k;if(!((k=e==null?void 0:e.dbSelection)!=null&&k.database))return;const M=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{...M,schema:E},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(re,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),l.jsxs("div",{className:"space-y-4",children:[b&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-sm font-medium",children:u}),l.jsxs(yt,{value:((N=e==null?void 0:e.dbSelection)==null?void 0:N.database)||"",onValueChange:v,disabled:a,children:[l.jsx(gt,{className:"w-full",children:l.jsxs("div",{className:"flex items-center gap-2",children:[a&&l.jsx(jn,{className:"h-4 w-4 animate-spin"}),l.jsx(St,{placeholder:c?`Error loading ${x}`:a?`Loading ${x}...`:`Select ${x}...`})]})}),l.jsx(bt,{children:i.map(E=>l.jsx(je,{className:"hover:bg-muted",value:E.id,children:E.name},E.id))})]})]}),((C=e==null?void 0:e.dbSelection)==null?void 0:C.database)&&g&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-sm font-medium",children:m}),l.jsxs(yt,{value:((j=e==null?void 0:e.dbSelection)==null?void 0:j.schema)||"",onValueChange:S,disabled:f,children:[l.jsx(gt,{className:"w-full",children:l.jsxs("div",{className:"flex items-center gap-2",children:[f&&l.jsx(jn,{className:"h-4 w-4 animate-spin"}),l.jsx(St,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),l.jsx(bt,{children:d.map(E=>l.jsx(je,{className:"hover:bg-muted",value:E.id,children:E.name},E.id))})]})]})]})]})}function rst(){const e=Le(c=>c.card.dataSource),t=Le(c=>c.actions.updateDataSource),[n,r]=w.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(de,{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(XI,{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(re,{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(de,{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(Fi,{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(re,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(c.id),children:l.jsx(Vt,{className:"h-3 w-3"})})]},c.id))})]})]})}function sst(){const e=Le(f=>f.card.dataSource),t=Le(f=>f.actions.updateDataSource),[n,r]=w.useState(""),[s,o]=w.useState(""),[i,a]=w.useState("api"),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(de,{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(de,{className:"text-xs text-gray-600",children:"Source Name"}),l.jsx(sn,{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(de,{className:"text-xs text-gray-600",children:"URL"}),l.jsx(sn,{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(de,{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(re,{onClick:c,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[l.jsx(Rr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs(de,{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(Ny,{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(re,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:l.jsx(Vt,{className:"h-3 w-3"})})]},f.id))})]})]})}function ost(e,t){var y,v;const{tokenProps:n}=Je(),r=Q(S=>S.authToken)||t,{connections:s}=mi(t),o=Le(S=>{var N,C;return(C=(N=S==null?void 0:S.card)==null?void 0:N.dataSource)==null?void 0:C.connectionId}),i=Le(S=>{var N,C,j;return(j=(C=(N=S==null?void 0:S.card)==null?void 0:N.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.database}),a=Le(S=>{var N,C,j;return(j=(C=(N=S==null?void 0:S.card)==null?void 0:N.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.schema}),c=s==null?void 0:s.find(S=>S.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 S=(u==null?void 0:u.path)||[];return!(S.includes("database")&&!i||S.includes("schema")&&!a)}const{data:h,isPending:m,isLoading:p,error:g,refetch:b}=Jt({queryKey:[e,o,i,a],queryFn:()=>yr(`${n.apiServiceUrl}/v1/${e}s`,(r==null?void 0:r.accessToken)||"",{connection_id:o,database_name:i,schema_name:a}),enabled:f()}),x=(v=h==null?void 0:h[`${e}s`])==null?void 0:v.map(S=>{var N;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:(N=S==null?void 0:S.table_type)==null?void 0:N.toLowerCase(),id:S[`${e}_name`],database:i,schema:a,name:S[`${e}_name`]}});return{isPending:m,isLoading:p,error:g,entities:x||[],refetch:b,label:d}}function US({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(wc,{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 ist({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=mi(),[i,a]=w.useState(""),[c,u]=w.useState(""),[d,f]=w.useState("tables"),{updateDataSource:h,setSelectedConnectionId:m}=vr(),{entities:p,isLoading:g,error:b}=ost("table"),{dataModels:x,isPending:y,error:v}=loe(),S=k=>{const _=s.find(P=>P.id===k);if(!_)return;const T=_.type==="upload"?"upload":_.type==="url"?"url":"database";h({...e,connectionId:k,connectionType:_.type,mode:T,dbSelection:{database:"",schema:"",entityType:"table"}}),m(k)},N=k=>{var O,R;const _=n||[],T=_.some($=>$.name===k.name&&$.type===k.type);let P;if(T)P=_.filter($=>!($.name===k.name&&$.type===k.type));else{const $={connectionId:e.connectionId,connectionType:e.connectionType,type:k.type,dbObjectType:k.dbObjectType,database:((O=e.dbSelection)==null?void 0:O.database)||"",schema:((R=e.dbSelection)==null?void 0:R.schema)||"",name:k.name,dialect:k.dialect};P=[..._,$]}t==null||t(P)},C=k=>{const _=n||[],T=_.some(O=>O.type==="model"&&O.name===k.name);let P;T?P=_.filter(O=>!(O.type==="model"&&O.name===k.name)):P=[..._,k],t==null||t(P)},j=p.filter(k=>k.name.toLowerCase().includes(i.toLowerCase())),E=x.filter(k=>k.name.toLowerCase().includes(c.toLowerCase())),M=w.useCallback(()=>{if(!t)return;const k=n||[];let _=[...k];if(d==="tables"){const P=j.filter(O=>!k.some(R=>R.name===O.name&&R.type==="table")).map(O=>{var R,$;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:O.dbObjectType,database:((R=e.dbSelection)==null?void 0:R.database)||"",schema:(($=e.dbSelection)==null?void 0:$.schema)||"",name:O.name,dialect:O.dialect}});_=[...k,...P]}else if(d==="datamodels"){const T=E.filter(P=>!k.some(O=>O.name===P.name&&O.type==="model"));_=[...k,...T]}t(_)},[d,j,E,n,e,t]);return w.useEffect(()=>{r&&r(M)},[r,M]),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"font-medium= text-sm",children:"Connection"}),l.jsxs(yt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:S,disabled:o,children:[l.jsx(gt,{className:"w-full",children:l.jsx(St,{placeholder:o?"Loading connections...":"Select connection..."})}),l.jsx(bt,{children:s.map(k=>l.jsx(je,{className:"hover:bg-muted",value:k.id,children:l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(rl,{className:"h-4 w-4 flex-shrink-0"}),l.jsx("span",{className:"truncate",children:k.name}),l.jsx(st,{variant:"secondary",className:"flex-shrink-0 text-xs",children:k.type})]})},k.id))})]})]}),(e==null?void 0:e.connectionId)&&l.jsxs(l.Fragment,{children:[e.connectionType==="upload"&&l.jsx(rst,{}),e.connectionType==="url"&&l.jsx(sst,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&l.jsxs(l.Fragment,{children:[l.jsx(nst,{}),l.jsx("div",{className:"space-y-4",children:l.jsx("div",{className:"space-y-2",children:l.jsxs(Os,{defaultValue:"tables",value:d,onValueChange:k=>f(k),className:"w-full",children:[l.jsxs(ws,{className:"grid w-full grid-cols-2",children:[l.jsxs(pn,{value:"tables",children:["Tables & Views (",j.length,")"]}),l.jsxs(pn,{value:"datamodels",children:["Data Models (",E.length,")"]})]}),l.jsxs(xr,{value:"tables",className:"space-y-2",children:[l.jsx(Ln,{placeholder:"Search tables and views...",value:i,onChange:k=>a(k.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..."}):b?l.jsx(US,{title:"Error loading tables",message:b.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(k=>{const _=n.some(T=>T.name===k.name&&T.type==="table");return l.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>N(k),children:[l.jsx(wn,{id:`table-${k.name}`,checked:_,onCheckedChange:()=>N(k),onClick:T=>T.stopPropagation(),disabled:g}),l.jsxs(de,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[k.name,k.dbObjectType==="view"&&l.jsx(st,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),k.dbObjectType==="materialized view"&&l.jsx(st,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},k.name)})})]}),l.jsxs(xr,{value:"datamodels",className:"space-y-2",children:[l.jsx(Ln,{placeholder:"Search data models...",value:c,onChange:k=>u(k.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(US,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):E.length===0?l.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):E.map(k=>{const _=n.some(T=>T.name===k.name&&T.type==="model");return l.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>C(k),children:[l.jsx(wn,{id:`dataModel-${k.name}`,checked:_,onCheckedChange:()=>C(k),onClick:T=>T.stopPropagation(),disabled:y}),l.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[l.jsx(de,{className:"cursor-pointer",children:k.name}),l.jsx("span",{className:"text-xs text-muted-foreground",children:k.description})]})]},k.name)})})]})]})})})]})]})]})}function ast({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:s=[],isRestricted:o=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var N;const[c,u]=w.useState(""),d=w.useCallback(C=>{const j={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:C};t({...j})},[e,t]);w.useEffect(()=>{i&&!(e!=null&&e.semanticDomainId)&&d(i)},[i,e==null?void 0:e.semanticDomainId,d]);const{semanticDomains:f,isPending:h,error:m}=Qrt(),p=o?f.filter(C=>s.includes(C.id)):f,{datasets:g,isPending:b,error:x}=Jrt(e==null?void 0:e.semanticDomainId),y=C=>{const j=r||[],E=j.some(k=>k.id===C.id&&k.type==="dataset");let M;if(E)M=j.filter(k=>!(k.id===C.id&&k.type==="dataset"));else{const k={id:C.id,datasetType:C.type,name:C.name||C.table,label:C.label,domainId:C.domainId,description:C.description,database:C.database,schema:C.schema,type:"dataset",connectionId:C.connectionId,connectionType:C.connectionType,dialect:C.dialect,datamodelId:C.datamodelId,sql:C.sql};M=[...j,k]}n==null||n(M)},v=g.filter(C=>C.name.toLowerCase().includes(c.toLowerCase())),S=w.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const C=r||[],E=v.filter(k=>!C.some(_=>_.id===k.id&&_.type==="dataset")).map(k=>({id:k.id,datasetType:k.type,name:k.name||k.table,label:k.label,domainId:k.domainId,description:k.description,database:k.database,schema:k.schema,type:"dataset",connectionId:k.connectionId,connectionType:k.connectionType,dialect:k.dialect,datamodelId:k.datamodelId,sql:k.sql})),M=[...C,...E];n(M)},[v,r,e==null?void 0:e.semanticDomainId,n]);return w.useEffect(()=>{a&&a(S)},[a,S]),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-sm font-medium",children:"Semantic Domain"}),l.jsxs(yt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:d,disabled:h||o&&!!i,children:[l.jsx(gt,{className:"w-full",children:l.jsx(St,{placeholder:h?"Loading semantic domains...":o&&i?"Loading domain...":"Select semantic domain...",children:((N=p.find(C=>C.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:N.label)||"Select semantic domain"})}),l.jsx(bt,{children:p.map(C=>l.jsx(je,{className:"hover:bg-muted",value:C.id,children:l.jsxs("div",{className:"flex flex-col items-start",children:[l.jsx("span",{className:"font-medium",children:C.label}),l.jsx("span",{className:"text-xs",children:C.description})]})},C.id))})]}),m&&l.jsx(US,{title:"Error loading semantic models",message:m.message})]}),(e==null?void 0:e.semanticDomainId)&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(Ln,{placeholder:"Search datasets...",value:c,onChange:C=>u(C.target.value),className:"h-8 text-sm",disabled:b}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:b?l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):x?l.jsx(US,{title:"Error loading datasets",message:x.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):v.length===0?l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:c?"No datasets match your search":"No datasets available"}):v.map(C=>{const j=r.some(E=>E.id===C.id&&E.type==="dataset");return l.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>y(C),children:[l.jsx(wn,{id:`dataset-${C.id}`,checked:j,onCheckedChange:()=>y(C),onClick:E=>E.stopPropagation(),disabled:b}),l.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[l.jsx(de,{className:"cursor-pointer font-medium",children:C.label||C.name}),l.jsx("span",{className:"text-xs text-gray-500",children:C.description})]})]},C.label||C.name)})})]})]})]})}function WO({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s}){const{tokenProps:o}=Je(),{allowedSemanticDomains:i}=o,[a,c]=w.useState([]),{updateDataSource:u}=vr(),d=Q(_=>_.isVisualEditing),f=Q(_=>_.dashboard.aiContext),{setAiContext:h}=un(),m=w.useRef(null),[p,g]=w.useState(!1),b=i&&i.length>0,x=!b,y=b&&i.length===1?i[0]:void 0,v=w.useCallback(_=>{const T=_;u({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:T,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...T!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,u]),S=w.useCallback(_=>{u({...n,..._})},[n,u]);w.useEffect(()=>{b&&n.mode!=="semanticDomain"&&v("semanticDomain")},[b,n.mode,v]),w.useEffect(()=>{y&&!n.semanticDomainId&&S({semanticDomainId:y})},[y,n.semanticDomainId,S]),w.useEffect(()=>{e?c(s||[]):(m.current=null,g(!1))},[e,n==null?void 0:n.selectedEntities,r,u,s,n]);const N=_=>{const T=a.filter(P=>!(P.name===_.name&&P.type===_.type));c(T)},C=()=>{c([])},j=w.useCallback(_=>{c(_)},[]),E=w.useCallback(()=>{m.current&&m.current()},[]),M=w.useCallback(_=>{m.current=_,g(!0)},[]);function k(){var _,T;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const P=(_=a==null?void 0:a[0])==null?void 0:_.connectionId,O=(T=a==null?void 0:a[0])==null?void 0:T.connectionType;u({...n,connectionId:P,connectionType:O,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return l.jsx(qr,{open:e,onOpenChange:t,children:l.jsx(Pr,{className:"flex max-w-2xl flex-col",children:l.jsxs("div",{children:[l.jsxs(Or,{className:"flex-shrink-0",children:[l.jsx(Fr,{children:r==="aiContext"?"Data Context":"Select Data Source"}),l.jsx(Jr,{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:[x&&l.jsx("div",{className:"space-y-2",children:l.jsx(Os,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:v,className:"w-full",children:l.jsxs(ws,{className:"grid w-full grid-cols-2",children:[l.jsx(pn,{value:"database",children:"Direct Source"}),l.jsx(pn,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&l.jsx(ast,{dataSource:n,onDataSourceUpdate:S,selectedEntities:a,onSelectionChange:j,allowedDomainIds:i||[],isRestricted:b,autoSelectedDomainId:y,onRegisterSelectAll:M}),(n==null?void 0:n.mode)==="database"&&x&&l.jsx(ist,{dataSource:n,onDataSourceUpdate:S,selectedEntities:a,onSelectionChange:j,onRegisterSelectAll:M})]})}),l.jsx(Xrt,{selectedEntities:a,onDeselectEntity:N}),l.jsx(vs,{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(re,{variant:"outline",onClick:E,disabled:!p,children:"Select All"}),l.jsx(re,{variant:"outline",onClick:C,disabled:a.length===0,children:"Clear All"}),l.jsxs(re,{variant:"outline",onClick:()=>t(!1),children:[l.jsx(Vt,{className:"mr-2 h-4 w-4"}),"Close"]}),l.jsxs(re,{onClick:k,children:[l.jsx(Hr,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function lst({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=w.useRef(null),o=async a=>{const c=Array.from(a.target.files||[]);if(c.length===0)return;const u=Hl-n;if(c.length>u){We.error(`You can only attach ${Hl} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=Nre(c);if(f.forEach(({file:h,error:m})=>{We.error(`${h.name}: ${m}`)}),d.length>0)try{const h=await Promise.all(d.map(m=>DO(m)));e(h)}catch(h){console.error("Failed to process files:",h),We.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return 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>=Hl}),l.jsx(re,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=Hl,title:n>=Hl?`Maximum ${Hl} files allowed`:"Attach files",children:l.jsx(VI,{className:"h-4 w-4 text-muted-foreground"})})]})}function cst({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=w.useState(!1),a=w.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),c=w.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),m=f.clientX,p=f.clientY;(m<h.left||m>=h.right||p<h.top||p>=h.bottom)&&i(!1)},[]),u=w.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=w.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const m=Hl-r;if(h.length>m){We.error(`You can only attach ${Hl} files per message. You have ${m} slot(s) remaining.`);return}const{valid:p,errors:g}=Nre(h);if(g.forEach(({file:b,error:x})=>{We.error(`${b.name}: ${x}`)}),p.length>0)try{const b=await Promise.all(p.map(x=>DO(x)));t(b),We.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),We.error("Failed to process one or more files")}},[n,r,t]);return l.jsxs("div",{className:X("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(XI,{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:[Hl-r," slot(s) available"]})]})})]})}const qO=w.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:c},u)=>{const[d,f]=w.useState(!1),[h,m]=w.useState(!1),[p,g]=w.useState(!1),b=w.useRef(null),x=tg();cEe(),lEe();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:S,setShowReasoning:N}=hN(),{queueMessage:C}=ng(),{addFileAttachment:j,removeFileAttachment:E,clearFileAttachments:M,getFileAttachments:k}=GA(),_=YA(c),T=Le(z=>z.card.dataSource),P=Q(z=>z.dashboard.aiContext),O=Q(z=>{var q;return(q=z.dashboard.aiContext)==null?void 0:q.selectedEntities});w.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const R=w.useCallback(()=>{const z=b.current;if(z){if(!e||e.length===0){z.style.height="10px";return}z.style.height="auto";const q=Math.min(Math.max(z.scrollHeight,10),200);z.style.height=`${q}px`}},[e]);w.useEffect(()=>{R()},[R]),w.useEffect(()=>{const z=setTimeout(()=>{R()},0);return()=>clearTimeout(z)},[R]);const $=()=>{const z=e.trim();!z&&_.length===0||(a!=="ready"?(C(c,z,_),t(""),M(c)):r({preventDefault:()=>{}}))},Y=z=>{z.key==="Enter"&&!z.shiftKey&&(z.preventDefault(),$()),z.key==="@"&&(B(),f(!0))},W=w.useCallback(z=>{const q=XZe(z.nativeEvent);q.length>0&&(z.preventDefault(),q.forEach(async Z=>{const ee=await DO(Z);j(c,ee)}))},[j,c]),H=w.useCallback(z=>{z.forEach(q=>{j(c,q)})},[j,c]),A=w.useCallback(z=>{z.forEach(q=>{j(c,q)})},[j,c]),L=w.useCallback(z=>{E(c,z)},[E,c]),F=z=>{if(x.selectedEntities.some(Z=>Z.id&&Z.id===z.id||Z.name===z.name)){const Z=x.selectedEntities.filter(ee=>!(ee.id&&ee.id===z.id||ee.name===z.name));y({selectedEntities:Z})}else{const Z=[...x.selectedEntities,z];y({selectedEntities:Z})}},I=z=>{F(z)},U=z=>{var ee;if(!x.selectedEntities.some(K=>K.id&&K.id===z.id||K.name===z.name)){const K=[...x.selectedEntities,z];y({selectedEntities:K})}const Z="label"in z?z.label:z.name;t(e+`@${Z} `),f(!1),(ee=b.current)==null||ee.focus()},V=z=>{const q=x.selectedEntities.filter(K=>!(K.id&&K.id===z.id||K.name===z.name));y({selectedEntities:q});const ee=`@${"label"in z?z.label:z.name}`;e.includes(ee)&&t(e.replace(ee,"").trim())},G=z=>{const q=new Set(z.map(K=>K.id||K.name)),Z=x.selectedEntities.filter(K=>!q.has(K.id||K.name));y({selectedEntities:Z});let ee=e;z.forEach(K=>{const ie=`@${"label"in K?K.label:K.name}`;ee=ee.replace(ie,"").trim()}),t(ee)},B=w.useCallback(()=>{x.selectedEntities.length===0&&y({selectedEntities:(P==null?void 0:P.selectedEntities)||[]})},[x.selectedEntities.length,P==null?void 0:P.selectedEntities,y]);return l.jsxs(cst,{onFilesDropped:H,currentFileCount:_.length,disabled:s,className:"space-y-4",children:[l.jsx(Krt,{entities:x.selectedEntities,availableEntities:O||[],onRemoveEntity:V,onRemoveEntities:G}),_.length>0&&l.jsx(QZe,{files:_,onRemove:L,showRemove:!s,className:"mb-2"}),l.jsxs("div",{className:"rounded-lg border border-border bg-background shadow-sm focus-within:ring-1 focus-within:ring-foreground/40",children:[l.jsx("textarea",{ref:b,value:e,onChange:n,onKeyDown:Y,onPaste:W,onFocus:()=>{R(),i==null||i()},placeholder:"Ask a question...",className:"max-h-[200px] min-h-[40px] w-full resize-none overflow-y-auto border-0 bg-transparent px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),l.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[c==="dashboard"&&l.jsxs(Is,{open:d,onOpenChange:z=>{z&&B(),f(z)},children:[l.jsx(Ds,{asChild:!0,children:l.jsx(re,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:l.jsx(nue,{className:"h-4 w-4 text-muted-foreground"})})}),l.jsx(As,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:z=>z.preventDefault(),children:l.jsx(Yrt,{isOpen:!0,onSelect:F,onDeselect:I,onClose:()=>{var z;f(!1),(z=b.current)==null||z.focus()},availableEntities:O||[],selectedEntities:x.selectedEntities,onTabComplete:U,onSelectAll:()=>{O&&y({selectedEntities:O})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),m(!0)}})})]}),l.jsx(lst,{onFilesSelected:A,disabled:s,currentFileCount:_.length})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[s&&l.jsx(re,{className:"rounded-full",size:"sm",onClick:o,children:l.jsx(pue,{className:"size-3.5 bg-background"})}),!s&&l.jsx(re,{disabled:!e.trim()&&_.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:$,title:a!=="ready"?"Message will be queued":void 0,children:l.jsx(WI,{className:"size-4"})})]})]})]}),l.jsx(WO,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:m,dataSource:T||gj,dialogMode:"aiContext"})]})});qO.displayName="ChatInputWithContext";function coe({assistantType:e,className:t}){const n=qK(e),{removeFromQueue:r}=ng();return n.length===0?null:l.jsxs("div",{className:X("space-y-2",t),children:[l.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[l.jsx(Sc,{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(re,{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(Vt,{className:"h-3 w-3"})})]})},s.id))})]})}function uoe({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=qK(e),{dequeueMessage:o}=ng();w.useEffect(()=>{if(t!=="ready"||n||!(s&&s.length>0))return;const a=o(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,s,o,r,e])}function doe(e,t={}){const{threshold:n=50,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=w.useRef(null),[a,c]=w.useState(!0),[u,d]=w.useState(!0),[f,h]=w.useState(!1),[m,p]=w.useState(0),g=w.useRef(0),b=w.useRef(!1),x=w.useRef(0),y=w.useRef(a),v=w.useRef(void 0),S=w.useRef({key:null,count:0,length:0}),N=w.useCallback(()=>{const M=i.current;return M?M.scrollHeight-M.scrollTop-M.clientHeight:0},[]),C=w.useCallback((M={})=>{if(!i.current)return;const{force:_=!1,instant:T=!1}=M;if(!_&&!y.current||!a&&!_)return;const P=T||r==="auto"||r==="instant"?"auto":r;v.current&&cancelAnimationFrame(v.current),b.current=!0,v.current=requestAnimationFrame(()=>{if(!_&&!y.current){b.current=!1,v.current=void 0;return}const O=i.current;if(!O){b.current=!1,v.current=void 0;return}const R=O.scrollHeight;P==="smooth"&&"scrollTo"in O?O.scrollTo({top:R,behavior:P}):O.scrollTop=R,g.current=O.scrollTop,d(!0),c(!0),y.current=!0,h(!1),p(0),b.current=!1,v.current=void 0})},[r,a]),j=w.useCallback(()=>{const M=i.current;if(!M)return;const k=g.current,_=M.scrollTop,T=_-k;if(g.current=_,T<-1){v.current&&(cancelAnimationFrame(v.current),v.current=void 0),b.current=!1,y.current=!1,c(!1),d(!1);return}if(b.current)return;const P=N()<=n;d(P),c(P),y.current=P,P&&(h(!1),p(0))},[N,n]),E=w.useCallback(()=>{p(0),h(!1)},[]);return w.useEffect(()=>{y.current=a},[a]),w.useEffect(()=>{const M=i.current;if(!M||!e||e.length===0){h(!1),p(0),S.current={key:null,count:0,length:0},g.current=M?M.scrollTop:0,x.current=M?M.scrollHeight:0;return}g.current=M.scrollTop,x.current=M.scrollHeight;const k=S.current,_=e[e.length-1],T=(_==null?void 0:_.id)??(_==null?void 0:_.messageId)??(_==null?void 0:_.createdAt)??(_==null?void 0:_.timestamp)??e.length,P=Array.isArray(_==null?void 0:_.parts)?_.parts.reduce((H,A)=>A?typeof A=="string"?H+A.length:typeof A.text=="string"?H+A.text.length:typeof A.content=="string"?H+A.content.length:typeof A.value=="string"?H+A.value.length:H:H,0):typeof(_==null?void 0:_.content)=="string"?_.content.length:typeof(_==null?void 0:_.text)=="string"?_.text.length:0,O=e.length>k.count,R=T!==k.key,$=P>k.length,Y=s&&(_==null?void 0:_.role)==="assistant"&&!O&&(R||$),W=o||Y;if(S.current={key:T,count:e.length,length:P},a&&(O||R||$||W)){C({force:!1,instant:W});return}if(!a&&O){const H=e.length-k.count;H>0&&(h(!0),p(A=>A+H))}else!a&&$&&(h(!0),p(H=>H>0?H:1))},[e,C,a,s,o]),w.useEffect(()=>{C({instant:!0})},[C]),w.useEffect(()=>{if(typeof ResizeObserver>"u")return;const M=i.current;if(!M)return;x.current=M.scrollHeight;const k=new ResizeObserver(()=>{const _=i.current;if(!_)return;const T=x.current,P=_.scrollHeight;x.current=P,!b.current&&y.current&&P>T&&C({force:!1,instant:!0})});return k.observe(M),()=>{k.disconnect()}},[C]),w.useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:u,hasNewMessages:f,newMessageCount:m,scrollToBottom:C,handleScroll:j,resetNewMessageCount:E}}function foe(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=w.useState(r),a=w.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),c=e.length>o,u=o>=e.length,d=w.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=w.useCallback(()=>{i(r)},[r]);return w.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:c,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}function hoe(e){var n;if(!e||e.length===0)return{hasActiveTools:!1};const t=e[e.length-1];if(!(t!=null&&t.parts))return{hasActiveTools:!1};for(const r of t.parts){if(r.type==="reasoning"&&"state"in r&&r.state==="streaming")return{hasActiveTools:!0,activeToolText:r.text||"Reasoning...",toolType:"reasoning"};if(((n=r.type)!=null&&n.startsWith("tool-")||r.type==="dynamic-tool")&&"state"in r&&["input-streaming","input-available"].includes(r.state)){const s=r,o=s.state;return{hasActiveTools:!0,activeToolText:jre(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const ust=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function dst({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=w.useState(!1),[a,c]=w.useState(aI),[u,d]=w.useState(!1),[f,h]=w.useState(!1),[m,p]=w.useState(!1),g=n??m,{isLocalDev:b,isConsoleMode:x}=Rp(),y=w.useRef(null);Q(Re=>Re.dashboard.aiScopeTables),Q(Re=>Re.isDashboardEditing);const v=Q(Re=>Re.selectedSheetId),{setDataSource:S}=vr(),{addFrame:N,setSelectedFrameId:C,setIsDashboardEditing:j}=un(),E=tg(),{setCurrentAIContext:M,updateSelectedEntities:k,setReasoningEffort:_,setShowReasoning:T}=hN(),{clearQueue:P}=ng(),{clearFileAttachments:O,getFileAttachments:R}=GA(),$=YA("dashboard"),Y=Q(Re=>Re.dashboard.aiContext),W=Le(Re=>Re.card.dataSource),{assistantProfile:H}=soe(),A=Q(Re=>Re.handleOpenAssistantProfile),{sendMessage:L,isLoading:F,messages:I,setMessages:U,status:V,stop:G,errorMessage:B,clearError:z}=qrt(),q=w.useCallback(Re=>{r==null||r(Re),n===void 0&&p(Re)},[n,r]),Z=w.useCallback(()=>{q(!g)},[g,q]);w.useEffect(()=>{if(!g)return;function Re(it){it.key==="Escape"&&q(!1)}return window.addEventListener("keydown",Re),()=>{window.removeEventListener("keydown",Re)}},[g,q]);const[ee,K]=w.useState(""),te=Re=>{K(Re.target.value)};function ie({sql:Re,cardTitle:it,connectionId:ye,cardType:tt,python:Ue,cardConfig:Qe,dataSource:Et,customVisualPreferences:Oe}){if(!v)return;const Ne={id:br(),title:it||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:tt==="horizontalBar"?"y":"x"}},type:tt,sql:Re,python:Ue,dataSource:Et,config:Qe,connectionId:ye,customCardPreferences:Oe?{url:Oe.url,componentName:Oe.componentName,pluginChartType:Oe.pluginChartType,settings:Oe.settings,type:"component"}:void 0},ze={id:br(),cards:[Ne],activeCardId:Ne.id};j(!0),N(v,ze,"end"),C(ze.id)}const ue=Re=>{Re.preventDefault();const it=ee.trim();if(!it&&$.length===0)return;const ye=[];it&&ye.push({type:"text",text:it}),$.forEach(tt=>{tt.data&&ye.push({type:"file",mediaType:tt.type,filename:tt.name,url:`data:${tt.type};base64,${tt.data}`})}),L({role:"user",parts:ye}),K(""),O("dashboard"),J({force:!0})};w.useEffect(()=>{var Re;e&&((Re=y.current)==null||Re.focus())},[e]),uoe({assistantType:"dashboard",status:V,isLoading:F,sendMessage:L});const{hasActiveTools:le}=hoe(I),{visibleMessages:we,hasMoreMessages:se,totalMessageCount:ke,loadMoreMessages:be,resetMessageWindow:Me}=foe(I,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Pe,isAtBottom:ge,hasNewMessages:$e,newMessageCount:ce,scrollToBottom:J,handleScroll:ae,resetNewMessageCount:ve}=doe(we,{threshold:50,behavior:"smooth",isStreaming:F});function Ce(Re){He();const it={role:"user",parts:[{type:"text",text:Re.title+" "+Re.subtitle}]};L(it)}function Ee(Re){He(),L({role:"user",parts:[{type:"text",text:Re}]})}function me(Re){He(),L({role:"user",parts:[{type:"text",text:Re}]}),J({force:!0})}const De=w.useCallback(async()=>{const Re=JSON.stringify(I??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Re),We.success("Conversation copied")}catch(it){console.error("Failed to copy conversation",it),We.error("Unable to copy conversation")}},[I]);function He(){E.selectedEntities.length===0&&M({selectedEntities:(Y==null?void 0:Y.selectedEntities)||[]})}const et=(ee==null?void 0:ee.length)===0&&(I==null?void 0:I.filter(Re=>Re.role==="user").length)===0;function Te(){return l.jsx("div",{"data-role":"header",children:l.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function Ye(){return l.jsxs(ah,{children:[l.jsx(lh,{asChild:!0,children:l.jsx(yu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:l.jsx(Ep,{className:"size-3.5"})})}),l.jsxs(Yu,{align:"end",children:[l.jsx(hm,{children:"Options"}),l.jsx(Rf,{}),l.jsx(Eb,{checked:o,onCheckedChange:i,children:"Token Usage"}),l.jsx(Eb,{checked:a,onCheckedChange:c,children:"Tool Invocations"}),l.jsx(Eb,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const nt=l.jsxs("div",{"data-role":"dashboard-assistant",className:X("flex h-full grow flex-col justify-between break-words px-6 py-4",g&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[l.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Te(),A&&l.jsx(re,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:A,children:(H==null?void 0:H.name)||"Default Profile"}),l.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[x&&Ye(),a&&l.jsx(re,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:De,children:"Copy Conversation"}),l.jsx(yu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:Z,children:g?l.jsx(BI,{className:"size-4"}):l.jsx(lC,{className:"size-4"})}),l.jsx(yu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{U([]),P("dashboard"),z(),Me()},children:l.jsx(uC,{className:"size-4"})}),l.jsx(yu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:l.jsx(Vt,{className:"size-4"})})]})]}),l.jsxs(kl,{"data-role":"dashboard-assistant-scroll-area",ref:Pe,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:ae,children:[l.jsxs("div",{className:"space-y-3 pb-4",children:[se&&l.jsx("div",{className:"flex justify-center py-2",children:l.jsxs(re,{variant:"outline",size:"sm",onClick:be,className:"text-xs",children:["Load ",Math.min(5,ke-we.length)," ","more messages (",ke-we.length," ","hidden)"]})}),l.jsx(Ere,{showTools:a,showSystemMessage:u,messages:we,onAddToDashboard:ie,onQuickReply:me,disableQuickReplies:F}),!le&&l.jsx(kre,{status:V,errorMessage:B})]}),l.jsx(Li,{orientation:"horizontal"})]}),e&&!ge&&l.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:l.jsxs(re,{onClick:()=>{J({force:!0}),ve()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[l.jsx(ur,{className:"h-4 w-4"}),$e&&ce>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:ce>9?"9+":ce})]})}),l.jsxs("div",{className:"space-y-3",children:[!H&&et&&l.jsx(_re,{onClick:Ce,placeholders:ust}),l.jsx("div",{children:et&&H&&l.jsx(ooe,{seedQuestions:H.seedQuestions||[],handleSeedQuestionClick:Ee})}),l.jsx(coe,{assistantType:"dashboard",className:"mb-3"}),l.jsx(qO,{ref:y,setInput:K,stop:G,input:ee,handleInputChange:te,handleSubmit:Re=>{He(),ue(Re),J({force:!0})},isLoading:F,status:V,assistantType:"dashboard",onFocus:()=>{}})]}),l.jsx(WO,{incomingSelectedEntities:(Y==null?void 0:Y.selectedEntities)||[],open:f,onOpenChange:h,dataSource:W||gj,dialogMode:"aiContext"})]});return g&&s?cr.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:nt})}),s):nt}function fst(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=un(),o=Q(d=>d.dashboard.sheets),a=Q(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),c=Q(d=>d.isDashboardEditing),u=Q(d=>d.isVisualEditing);w.useEffect(()=>{if(!c||u)return;async function d(m){const p=m.ctrlKey||m.metaKey;p&&m.key==="c"?(await f(),We.success("Card copied to clipboard"),m.preventDefault()):p&&m.key==="v"&&(await h(),m.preventDefault())}async function f(){try{const m=n();m&&await navigator.clipboard.writeText(JSON.stringify(m))}catch(m){console.error("Failed to copy text:",m)}}async function h(){if(!a)return null;try{const m=await navigator.clipboard.readText();try{const p=JSON.parse(m);if(p!=null&&p.id){const g=XJ(p),b=g.cards.findIndex(x=>x.id===g.activeCardId);b!==-1&&(g.cards[b].title=`${g.cards[b].title} (Copy)`),r(a,g),s(g.id),We.success("Card pasted from clipboard")}}catch(p){console.error("Failed to parse clipboard contents: ",p)}return m}catch(m){return console.error("Failed to paste text:",m),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[r,n,s,a,c,u,t])}function hst(e,t){switch(e.interactionMode){case"drillToDetail":mst(e,t);break;case"drillThrough":pst(e,t);break;case"drillToURL":gst(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 mst(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 pst(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 gst(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 bst({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return l.jsx(qr,{open:e,onOpenChange:t,children:l.jsxs(Pr,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[l.jsxs(Or,{children:[l.jsx(Fr,{children:i||"Insight Detail"}),l.jsx(Jr,{children:a||"View detailed insight data with applied filters"})]}),l.jsx(Wee,{filters:r,filterDefinitions:s,contextMode:o}),l.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?l.jsx(Zee,{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 xst(){const e=Xt(S=>S.interactionStates),t=Xt(S=>S.setInteractionState),n=Xt(S=>S.clearLastInteractionEvent),r=Xt(S=>S.replaceCardWithInsight),s=Xt(S=>S.setPendingDrillThrough),o=Xt(S=>S.pendingDrillThrough),i=Xt(S=>S.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:c}=un(),{selectDashboard:u}=jp(),d=Q(S=>S.dashboard),f=Q(S=>S.filterValues),{data:h,isLoading:m}=_U((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[p,g]=w.useState({open:!1,insightId:""}),b=Xee(p.insightId,{enabled:p.open&&!!p.insightId}),x=w.useRef(new Set),y=w.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:S,filters:N,contextMode:C})=>{g({open:!0,insightId:S,filters:N,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:C})},replaceCardContent:({cardId:S,insightId:N,filters:C,contextMode:j})=>{r(S,N,C,j)},getCurrentFilters:()=>f||[],navigateWithDrill:c,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:S,contextMode:N,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:E})=>{const k={sourceCardId:el,interactionMode:"clickFilter",filterGroups:[{filters:S}]},_={...ki(),appliedClickFilters:[k],contextMode:N,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:E};t(el,_)}}),[a,r,f,c,d,s,t]);w.useEffect(()=>{Object.entries(e).forEach(([S,N])=>{if(N!=null&&N.lastInteractionEvent){const C=N.lastInteractionEvent,j=`${S}-${C.interactionMode}-${C.sourceCardId}-${Date.now()}`;if(x.current.has(j))return;x.current.add(j);try{hst(C,y)}catch(E){console.error("Error executing interaction event:",E)}finally{n(S),setTimeout(()=>{x.current.delete(j)},5e3)}}})},[e,n,y]),w.useEffect(()=>{if(!(!o||!h||m))try{u(h),c(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(S){console.error("[DrillThrough] Error during automatic navigation:",S),i()}},[o,h,m,u,c,i]);const v=()=>{g({open:!1,insightId:""})};return l.jsxs(l.Fragment,{children:[l.jsx(bst,{open:p.open,onOpenChange:v,insightId:p.insightId,filters:p.filters,filterDefinitions:p.filterDefinitions,contextMode:p.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&m&&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-3 rounded-lg border bg-background p-6 shadow-lg",children:[l.jsx(jn,{className:"h-8 w-8 animate-spin text-primary"}),l.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function yst(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=vst(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function vst(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function wst(e){return e?`Back to ${e}`:"Back"}function Sst(){var x,y,v,S,N;const e=Xt(C=>C.interactionStates[el]),t=Q(C=>C.actions.goBackFromDrill),n=Q(C=>C.actions.clearDrillContext),{selectDashboard:r}=jp(),[s,o]=w.useState({x:16,y:16}),[i,a]=w.useState(!1),c=w.useRef({x:0,y:0});w.useEffect(()=>{if(!i)return;const C=E=>{o({x:E.clientX-c.current.x,y:E.clientY-c.current.y})},j=()=>{a(!1)};return document.addEventListener("mousemove",C),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",C),document.removeEventListener("mouseup",j)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((S=(v=(y=(x=e==null?void 0:e.appliedClickFilters)==null?void 0:x[0])==null?void 0:y.filterGroups)==null?void 0:v[0])==null?void 0:S.filters)||[],h=u?{id:u,title:d||"Previous Dashboard",description:"",isPrivate:!1,isPublic:!1,version:"",createdBy:null,createdByTenantUser:"",tenantId:"",projectId:"",createdAt:"",updatedAt:"",lastModified:"",lastModifiedBy:"",createdByUser:null,createdByTenantUserRel:{name:"",email:""},permissions:{canEdit:!0,canShare:!0,canDelete:!0},ownership:{status:"private",isOwner:!0,sharedCount:0,createdBy:{type:"user",userId:"",name:"",email:""}}}:null;if(!e||!((N=e.appliedClickFilters)!=null&&N.length))return null;const m=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(C){console.error("[DrillBack] Error during back navigation:",C)}},p=()=>{n()},g=C=>{C.target.closest("button")||(a(!0),c.current={x:C.clientX-s.x,y:C.clientY-s.y})};yst(f);const b=wst(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((C,j)=>{const E=C.field.label||C.field.name,M=String(C.value);return l.jsxs(st,{variant:"secondary",className:"pointer-events-none text-xs",children:[E," = ",M]},j)})})]}),l.jsx(re,{variant:"ghost",size:"sm",onClick:p,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:l.jsx(Vt,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:l.jsxs(re,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[l.jsx(H7,{className:"mr-2 h-4 w-4"}),b]})})]})})}function moe(){var ke;const{showAssistant:e,tokenProps:t}=Je(),{preferences:n,isConsoleMode:r}=Rp(),s=((ke=n==null?void 0:n.cardDisplay)==null?void 0:ke.mode)==="print",o=w.useRef(null),i=w.useRef(null),[a,c]=w.useState(!1),{handleDragStart:u,isDraggingRef:d,getStyle:f,getPositionClasses:h}=WVe({initialPosition:"bottom-right"}),m=wf(be=>be.setFullscreen),p=wf(be=>be.setPanelOpen),g=wf(be=>be.setContainer),b=VK("dashboard"),x=UK(),y=HK("dashboard"),v=b.isOpen,S=x==="dashboard",N=Q(be=>be.isVisualEditing),C=Q(be=>be.themeStyle),j=Q(be=>{var Me;return(Me=be.dashboard)==null?void 0:Me.sheets}),E=Q(be=>be.showFilters),M=Q(be=>be.isDashboardEditing),k=Q(be=>be.selectedSheetId),_=Q(be=>{var Me,Pe;return((Pe=(Me=be.dashboard)==null?void 0:Me.summary)==null?void 0:Pe.position)||"top"}),T=Q(be=>{var Me;return(Me=be.dashboard)==null?void 0:Me.id}),P=Q(be=>be.isDashboardPanelOpen),O=Q(be=>be.actions.setIsDashboardPanelOpen),{getDefaultSheetId:R,setDefaultSheetId:$,clearDefaultSheetId:Y}=L7(T),[W,H]=w.useState(null);NC(cn.DASHBOARD);const{setSelectedSheetId:A,setSheetTitle:L,addSheet:F,setSheets:I}=un();fst(i);const{setActiveAssistantType:U}=hN();w.useEffect(()=>{if(T){const be=R();H(be)}},[T,R]),w.useEffect(()=>{v?U("dashboard"):x==="dashboard"&&m(null)},[v,U,x,m]),w.useEffect(()=>{var be;v||(be=o.current)==null||be.resize(0)},[v]);function V(be){var Me,Pe;be?((Me=o.current)==null||Me.resize(40),p("dashboard",!0),U("dashboard")):(p("dashboard",!1),m(null),(Pe=o.current)==null||Pe.resize(0),U(null))}function G(){const be={id:br(),title:"New Sheet"};F(be),A(be.id)}function B(be,Me){if(!T)return;W===be?(Y(),H(null),We.success("Default sheet cleared")):($(be),H(be),We.success(`"${Me}" set as default sheet`))}function z(be){var Me;be<1?(p("dashboard",!1),m(null),U(null),(Me=o.current)==null||Me.resize(0)):(v||p("dashboard",!0),U("dashboard"))}function q(){return(C==null?void 0:C.canvasTheme)==="muted"||!(C!=null&&C.canvasTheme)?"hsl(var(--semaphor-muted))":(C==null?void 0:C.canvasTheme)==="clear"?"":C==null?void 0:C.canvasTheme}const Z=(be,Me)=>{be.dataTransfer.setData("tabIndex",Me.toString())},ee=be=>{be.preventDefault()},K=(be,Me)=>{const Pe=be.dataTransfer.getData("tabIndex");if(Pe===Me.toString())return;const ge=Array.from(j||[]),[$e]=ge.splice(parseInt(Pe),1);ge.splice(Me,0,$e),I(ge)},te=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail,ie=e===!0&&!s&&!v&&!N&&!E;function ue(){var be,Me;if(j&&j.length>1||M)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 border-b border-b-muted bg-transparent px-3",children:[r&&te&&!P&&l.jsx(re,{style:{borderRadius:C==null?void 0:C.controlInputRadius},variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{O(!P)},className:"h-8 shrink-0 p-2",children:P?l.jsx(X7,{className:"h-4 w-4"}):l.jsx(Q7,{className:"h-4 w-4"})}),j==null?void 0:j.map((Pe,ge)=>{const $e=k===Pe.id,ce=W===Pe.id;return l.jsxs(pn,{draggable:!0,onDragStart:J=>Z(J,ge),onDragOver:ee,onDrop:J=>K(J,ge),style:{borderRadius:C==null?void 0:C.controlInputRadius},onClick:()=>A(Pe.id),className:"flex shrink-0 items-center gap-1 border px-2 py-1",value:Pe.id,children:[l.jsx(fS,{enabled:M&&$e,text:Pe.title,onSave:J=>L(Pe.id,J),children:Pe.title},Pe.id),!M&&$e&&l.jsx("div",{title:ce?"Clear default sheet":"Set as default sheet",children:l.jsx(qI,{className:X("ml-1 size-3 cursor-pointer transition-all",ce?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:J=>{J.stopPropagation(),B(Pe.id,Pe.title||"Sheet")}})}),M&&$e&&j.length>1&&l.jsx(Vt,{className:"ml-1 size-3",onClick:()=>c(!0)})]},Pe.id)}),M&&l.jsx("div",{style:{borderRadius:(Me=(be=C==null?void 0:C.chart)==null?void 0:be.options)==null?void 0:Me.borderRadius},className:"flex h-7 shrink-0 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:G,children:l.jsx(Rr,{className:"size-3"})})]})}function le(){return l.jsx("div",{ref:i,style:{},className:"grow",children:j==null?void 0:j.map(be=>l.jsx(xr,{style:{backgroundColor:q()},className:X("mt-0",{}),value:be.id,children:l.jsx(pVe,{sheet:be})},be.id))})}function we(){var be;return l.jsxs(Os,{"data-role":"dashboard-tabs-container",className:X("relative flex h-full flex-col",C==null?void 0:C.dashboardTabsContainer),onValueChange:Me=>{A(Me)},value:k||((be=j==null?void 0:j[0])==null?void 0:be.id),children:[ue(),_==="top"&&l.jsx(hM,{}),l.jsx(kl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:le()}),_==="bottom"&&l.jsx(hM,{}),l.jsx(qVe,{open:a,setOpen:c})]})}const se=w.useCallback(be=>{g("dashboard",be)},[g]);return j?l.jsxs(l.Fragment,{children:[l.jsx(xst,{}),l.jsx(Sst,{}),l.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[l.jsxs(lne,{className:X("flex-1 basis-0 overflow-y-auto transition-opacity",S&&"pointer-events-none opacity-0"),direction:"horizontal",children:[l.jsx(SM,{children:we()}),e===!0&&l.jsxs(l.Fragment,{children:[l.jsx(HVe,{open:v,onTabClick:V,withHandle:!0,disabled:!v}),l.jsx(SM,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:z,defaultSize:v?40:0,ref:o,children:l.jsx("div",{className:"grow overflow-y-auto",children:l.jsx(dst,{open:v,setOpen:V,isFullscreen:S,onFullscreenChange:be=>m(be?"dashboard":null),fullscreenContainer:y})})})]})]}),l.jsx("div",{ref:se,className:X("absolute inset-0",!S&&"pointer-events-none")}),ie&&l.jsx("div",{className:X("absolute z-50 transition-all duration-300 ease-in-out",h().horizontal,h().vertical),style:f(),children:l.jsx(re,{size:"sm",variant:"outline",className:"h-12 w-12 cursor-grab rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted active:cursor-grabbing",onClick:()=>{d.current||V(!0)},onMouseDown:u,onTouchStart:u,title:"Open Assistant (drag to move)",children:l.jsx(jy,{className:"h-5 w-5"})})})]})]}):null}function YO({children:e}){return l.jsx(_a,{style:{height:"100%",width:"100%"},children:l.jsx(mce,{defaultTheme:"system",storageKey:"vite-ui-theme",children:l.jsx(nr,{delayDuration:0,children:e})})})}function poe({children:e,preferences:t}){const{currentUser:n}=ro(),r=w.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return l.jsx(oU.Provider,{value:r,children:l.jsx(qP,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function Cst(e=2e3,t=500){const n=Wce(),[r,s]=w.useState(!1),[o,i]=w.useState(!1),a=w.useRef(null);return w.useEffect(()=>{const c=setTimeout(()=>s(!0),e);return()=>clearTimeout(c)},[e]),w.useEffect(()=>{if(r){if(n>0){i(!1),a.current&&(clearTimeout(a.current),a.current=null);return}return a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i(!0)},t),()=>{a.current&&clearTimeout(a.current)}}},[r,n,t]),o}function GO({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=Cst(e,t);return w.useEffect(()=>(s&&(window.__SEMAPHOR_READY__={ready:!0,type:n,componentId:r||null,timestamp:Date.now()}),()=>{window.__SEMAPHOR_READY__={ready:!1,type:n,componentId:r||null,timestamp:Date.now()}}),[s,n,r]),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 goe(e){if(typeof window>"u")return null;const{preferences:t}=e;return l.jsx(Na,{FallbackComponent:BN,children:l.jsxs(_I,{dashboardProps:e,children:[l.jsx(GO,{componentType:"dashboard",componentId:e.id}),l.jsx(YO,{children:l.jsx(poe,{preferences:t,children:l.jsx("main",{className:"flex h-full flex-col",children:l.jsx(KA,{...e,type:"dashboard",children:l.jsx(moe,{})})})})})]})})}function u9(e,t){return e.map(n=>({...n,fieldScope:t}))}function Nst(e){const t=new Map;return e.forEach(n=>{const r=`${n.name}-${n.role||"unknown"}`;t.has(r)||t.set(r,n)}),Array.from(t.values())}function d9(e){if(Dc(e)||Wy(e))return e.expression}function KO(){const{columns:e,columnGroups:t,isLoading:n,hasError:r,error:s,refetch:o}=yA(),i=Le(g=>g.frame.calculatedFields),a=Le(g=>g.card.config),c=w.useMemo(()=>e.filter(g=>g.fieldScope==="domain"),[e]),u=w.useMemo(()=>e.filter(g=>g.fieldScope!=="domain"),[e]),d=w.useMemo(()=>i!=null&&i.length?u9(i,"dashboard"):[],[i]),f=w.useMemo(()=>{const g=new Map;return d.forEach(b=>{const x=`${b.name}-${b.role||"unknown"}`;g.set(x,b)}),g},[d]),h=w.useMemo(()=>{const g=((a==null?void 0:a.metricColumns)||[]).filter(Dc),b=((a==null?void 0:a.groupByColumns)||[]).filter(Wy),y=Nst([...g,...b]).filter(v=>{const S=`${v.name}-${v.role||"unknown"}`,N=f.get(S);if(!N)return!0;const C=d9(v),j=d9(N);return C&&j?C!==j:!0});return u9(y,"card").map(v=>({...v,id:`card-source-${v.id}`}))},[a==null?void 0:a.groupByColumns,a==null?void 0:a.metricColumns,f]),m=w.useMemo(()=>[...c,...d,...h,...u],[h,u,d,c]),p=w.useMemo(()=>t.filter(g=>g.entityId!==l7),[t]);return{columns:e,columnGroups:p,rawColumnGroups:t,columnFields:u,domainCalculatedFields:c,dashboardCalculatedFields:d,cardCalculatedFields:h,scopedFields:m,isLoading:n,hasError:r,error:s,refetch:o}}function ZO(e){const{tokenProps:t,authToken:n}=Je(),r=t==null?void 0:t.apiServiceUrl;return Jt({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return yr(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 boe(e,t,n){if(t==="source")return{isValid:!0};const r=Ar(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 xoe(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 jst(e,t){return(e||[]).map(n=>({...n,id:t(n),label:n.label!==void 0?n.label:n.name}))}const yoe=e=>{var O;const t=(O=e==null?void 0:e.dataSource)==null?void 0:O.semanticDomainId,{data:n}=ZO(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:c,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=vr(),h=Le(R=>R.card.type),m=e==null?void 0:e.id,p=(R,$)=>{if(R.id)return R.id;const Y=R.qualifiedEntityName||R.entityName||$;return`${$}-${Y}-${R.name}`},g=w.useCallback(R=>{if(!(e!=null&&e.config))return[];switch(R){case"groupBy":return(e.config.groupByColumns||[]).map($=>({...$,id:p($,"groupBy"),label:$.label!==void 0?$.label:$.name}));case"metrics":return(e.config.metricColumns||[]).map($=>({...$,id:p($,"metrics"),label:$.label!==void 0?$.label:$.name}));case"pivotBy":return(e.config.pivotByColumns||[]).map($=>({id:p($,"pivotBy"),name:$.name,dataType:$.dataType,label:$.label!==void 0?$.label:$.name,qualifiedEntityName:$.qualifiedEntityName,entityId:$.entityId,entityName:$.entityName,entityType:$.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map($=>({id:p($,"sortBy"),name:$.name,dataType:$.dataType,label:$.label!==void 0?$.label:$.name,qualifiedEntityName:$.qualifiedEntityName,entityId:$.entityId,entityName:$.entityName,entityType:$.entityType,direction:$.direction}));case"detailColumns":return jst(e.config.detailColumns,$=>p($,"detailColumns"));case"source":return[];default:return[]}},[e]),b=w.useCallback((R,$)=>{if(m)switch(R){case"groupBy":{r(m,{groupByColumns:$});break}case"metrics":{r(m,{metricColumns:$});break}case"pivotBy":{r(m,{pivotByColumns:$});break}case"sortBy":{r(m,{sortByColumns:$});break}case"detailColumns":{r(m,{detailColumns:$});break}}},[m,r]),x=w.useCallback((R,$,Y)=>{if(!m)return;const W=g(R),H=W[$];if(H)switch(R){case"groupBy":s(m,H.id,{label:Y});break;case"metrics":o(m,H.id,{label:Y});break;case"pivotBy":i(m,H.id,{label:Y});break;case"sortBy":a(m,H.id,{label:Y});break;case"detailColumns":{const A=W.map((L,F)=>F===$?{...L,label:Y}:L);r(m,{detailColumns:A});break}}},[m,g,s,o,i,a,r]),y=w.useCallback((R,$)=>{if(!m)return;const W=g("metrics")[R];W&&o(m,W.id,{aggregate:$,label:CY(W.name,$)})},[m,g,o]),v=w.useCallback((R,$,Y,W="groupBy")=>{if(!m)return;const H=g(W),A=H[R];if(!A)return;const L={dateFormat:$,customFormat:$==="custom"&&Y?Y:void 0};if(W==="detailColumns"){const F=H.map((I,U)=>U===R?{...I,...L}:I);r(m,{detailColumns:F});return}s(m,A.id,L)},[m,g,r,s]),S=w.useCallback((R,$)=>{if(!m)return;const W=g("groupBy")[R];W&&s(m,W.id,{granularity:$})},[m,g,s]),N=w.useCallback((R,$)=>{if(!m)return;const W=g("metrics")[R];W&&o(m,W.id,{aliasTemplate:$})},[m,g,o]),C=w.useCallback((R,$)=>{if(console.log("handleValueAliasesChange",R,$),!m)return;console.log("handleValueAliasesChange",R,$);const W=g("metrics")[R];W&&(console.log("handleValueAliasesChange",$),o(m,W.id,{valueAliases:$}))},[m,g,o]),j=w.useCallback((R,$)=>{if(!m)return;const W=g("metrics")[R];W&&o(m,W.id,{comparisonType:$,...$!=="target"?{targetValue:void 0}:{}})},[m,g,o]),E=w.useCallback(R=>{m&&r(m,{showTrendline:R})},[m,r]),M=w.useCallback(R=>{m&&r(m,{trendlineWindow:R})},[m,r]),k=w.useCallback(R=>{m&&r(m,{trendlineGranularity:R})},[m,r]),_=w.useCallback((R,$)=>{if(!m)return;const W=g("metrics")[R];W&&o(m,W.id,{targetValue:$})},[m,g,o]),T=w.useCallback(async R=>{var I;if(!m)return;const $=[...g("groupBy"),...g("pivotBy"),...g("metrics"),...g("sortBy"),...g("detailColumns")],Y=R,W=Oje(Y,$,{joinPlan:(I=e==null?void 0:e.config)==null?void 0:I.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!W.isValid){W.showError&&vY();return}const H=Lje(Y,$,h);if(!H){We.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const A=boe(Y,H,h);if(!A.isValid){We.error("Invalid Field Type",{description:A.reason,position:"top-center",duration:3e3});return}const L=g(H);if(wY(Y,L))return;const F=NY(Y,H,L);if(F){const U=[...L,F];b(H,U),H==="metrics"&&xoe(h,e==null?void 0:e.config,r,m,U)}},[m,e==null?void 0:e.config,g,b,t,n,h,r]),P=w.useCallback((R,$)=>{if(!m)return;const W=g(R)[$];if(W){if(R!=="sortBy"){const H=g("sortBy"),A=H.filter(L=>!(L.name===W.name&&L.qualifiedEntityName===W.qualifiedEntityName));A.length!==H.length&&r(m,{sortByColumns:A})}switch(R){case"groupBy":c(m,W.id);break;case"metrics":u(m,W.id);break;case"pivotBy":d(m,W.id);break;case"sortBy":f(m,W.id);break;case"detailColumns":{r(m,{detailColumns:(g("detailColumns")||[]).filter((H,A)=>A!==$)});break}}}},[m,g,c,u,d,f,r]);return{getFieldsForContainer:g,setFieldsForContainer:b,updateLabel:x,handleAggregationChange:y,handleDateFormatChange:v,handleGranularityChange:S,handleAliasTemplateChange:N,handleValueAliasesChange:C,removeField:P,handleFieldClick:T,handleMetricComparisonChange:j,handleKpiShowTrendlineChange:E,handleKpiTrendlineWindowChange:M,handleKpiTrendlineGranularityChange:k,handleMetricTargetValueChange:_,cardType:h}};function wj(e,t){var De,He,et,Te,Ye,nt,Re,it;const{tokenProps:n}=Je(),r=us(),s=Je().authToken||e,o=Le(ye=>ye.selectedConnectionId),i=Le(ye=>ye.card),{queryKey:a}=rbe(i),c=Le(ye=>ye.selectedDatamodelId),u=Le(ye=>ye.isDevMode),d=Le(ye=>ye.selectedDatabaseName),f=Le(ye=>ye.selectedSchemaName),h=Le(ye=>ye.selectedTableName),m=Le(ye=>ye.actions.setSelectedConnectionId),p=Le(ye=>ye.actions.setSelectedDatamodelId),g=Le(ye=>ye.actions.setSelectedDatabaseName),b=Le(ye=>ye.actions.setSelectedSchemaName),x=Le(ye=>ye.actions.setSelectedTableName);Le(ye=>ye.actions.setCardSql);const{setQueryConfig:y}=vr();function v(ye){var Oe;if(!o||!ye)return!1;const tt=((Oe=M==null?void 0:M.capabilities)==null?void 0:Oe.path)||[],Ue=tt.includes("database"),Qe=tt.includes("schema");return!(!tt.includes("table")||Ue&&(!d||d==="NA")||Qe&&!f)}function S(ye){var tt;return!o||!ye?!1:!!((tt=M==null?void 0:M.capabilities)!=null&&tt.path.includes("database"))}const{refetchConnections:N,connectionsData:C,isConnectionsLoading:j,isConnectionsError:E,selectedConnection:M}=mi(e),{refetch:k,data:_,isLoading:T,isError:P}=Jt({queryKey:["models",o],queryFn:()=>yr(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),O=M==null?void 0:M.type,R=((De=M==null?void 0:M.capabilities)==null?void 0:De.path.includes("schema"))??!1,$=((He=M==null?void 0:M.capabilities)==null?void 0:He.path.length)===1&&((et=M==null?void 0:M.capabilities)==null?void 0:et.path[0])==="table",Y=$,{data:W,isLoading:H,isFetching:A,isError:L,refetch:F}=Jt({queryKey:["databases",o],queryFn:()=>yr(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:S(O)}),{data:I,isLoading:U,isFetching:V,isError:G,refetch:B}=Jt({queryKey:["schemas",o,d],queryFn:()=>yr(`${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:q,isFetching:Z,isError:ee,refetch:K}=Jt({queryKey:["tables",o,d,f],queryFn:()=>yr(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(O)}),{columns:te,isColumnsLoading:ie,isColumnsFetching:ue,isColumnsError:le,refetchColumns:we}=jY(e);w.useEffect(()=>{$&&(g(""),b(""),p(""),O==="API"&&x("api"))},[O,x,g,b,p,$]);const se=(M==null?void 0:M.type)==="API"?(Te=M==null?void 0:M.type)==null?void 0:Te.toLowerCase():h||"",ke=R&&f||"";function be(ye){x(ye),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function Me(ye){b(ye),x("")}function Pe(ye){g(ye==="none"?"":ye),b(""),x(""),ye!=="none"&&ye!==""&&p("")}function ge(ye){m(ye)}function $e(ye){p(ye==="none"?"":ye),ye!=="none"&&ye!==""&&g("")}W&&((Ye=W==null?void 0:W.databases)==null?void 0:Ye.length)>0,I&&((nt=I==null?void 0:I.schemas)==null?void 0:nt.length)>0;const ce=C==null?void 0:C.connections.map(ye=>({id:ye.id,name:ye.name,type:ye.type})),J=(Re=_==null?void 0:_.datamodels)==null?void 0:Re.map(ye=>({id:ye.id,name:ye.name})),ae=W==null?void 0:W.databases.map(ye=>({id:ye.database_name,name:ye.database_name})),ve=I==null?void 0:I.schemas.map(ye=>({id:ye.schema_name,name:ye.schema_name})),Ce=z==null?void 0:z.tables.map(ye=>({id:ye.table_name,name:ye.table_name})),Ee=(it=_==null?void 0:_.datamodels.find(ye=>ye.id===c))==null?void 0:it.name,me=M!=null&&M.capabilities?Qw({schemaName:ke,tableName:se,modelName:Ee,databaseName:d||"",capabilities:M.capabilities}):se;return{connectionItems:ce,selectedConnectionId:o,selectedConnection:M,isConnectionsLoading:j,isConnectionsError:E,modelItems:J,selectedDatamodelId:c,selectedDatamodelName:Ee,isModelsLoading:T,isModelsError:P,selectedDatabaseName:d,databaseItems:ae,isDatabasesLoadingOrFetching:H||A,isDatabaseError:L,schemaItems:ve,selectedSchemaName:f,isSchemaLoadingOrFetching:U||V,isSchemaError:G,tableItems:Ce,selectedTableName:h,isTableLoadingOrFetching:q||Z,isTableError:ee,columns:te,isColumnsLoadingOrFetching:ie||ue,isColumnsError:le,isNonDbConnection:Y,connectionType:O,tableName:se,formattedTableName:me,schemaName:ke,refetchConnections:N,refetchModels:k,refetchDatabases:F,refetchSchemas:B,refetchTables:K,refetchColumns:we,handleConnectionChange:ge,handleDatamodelChange:$e,handleDatabaseChange:Pe,handleSchemaChange:Me,handleTableChange:be}}function mw(e){return`${e}-${br()}`}function f9(e,t){const n=li(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 kst(e,t){const n=li(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function XO(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 voe(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function woe(){const e=Le(j=>j.sqlGen),t=Le(j=>j.isDevMode),n=Le(j=>j.card.dataSource),r=Le(j=>{var E,M;return(M=(E=j.card)==null?void 0:E.queryConfig)==null?void 0:M.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=XO(n),a=voe(n),c=Le(j=>j.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:m,setIsShowingVisual:p}=vr(),{modelItems:g,selectedDatamodelName:b}=wj(),{selectedConnection:x}=mi(),y=x==null?void 0:x.capabilities,v=j=>({column_name:j.name,data_type:j.dataType,label:j.label,description:j.description});return{handleDevModeFieldClick:j=>{var M;if(!t)return;const E=v(j);if(t&&a&&s&&y){const k=hI(E,e);m(k);const _=(M=g==null?void 0:g.find(P=>P.id===c))==null?void 0:M.name,T=fI(k,o||"",s,_||"",i||"",y,j.qualifiedEntityName);T&&(f(T),h(!0))}else if(!t){if(vy(E.data_type))if(r&&r.length>0){const k={...E,role:"groupby",id:mw(E.column_name),name:E.column_name,type:E.data_type};d(k)}else{const k={...E,role:"metric",id:mw(E.column_name),name:E.column_name,label:f9(E.column_name,"COUNT"),type:E.data_type,aggregate:"COUNT"};u(k)}if(ya(E.data_type)){const k={...E,role:"groupby",id:mw(E.column_name),name:E.column_name,type:E.data_type,label:kst(E.column_name,"month"),granularity:"month"};d(k)}if(xa(E.data_type)){const k={...E,role:"metric",id:mw(E.column_name),name:E.column_name,label:f9(E.column_name,"SUM"),type:E.data_type,aggregate:"SUM"};u(k)}}},handleShowSample:()=>{if(!a||!s||!y){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const j=Qw({schemaName:o||"",tableName:s,modelName:b,databaseName:i||"",capabilities:y});p(!1);const M=(x==null?void 0:x.type)==="MSSQL"?`SELECT top 10 * FROM ${j}`:`SELECT * FROM ${j} LIMIT 10`;f(M),h(!0)},handleShowCount:()=>{if(!a||!s||!y){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const j=Qw({schemaName:o||"",tableName:s,modelName:b,databaseName:i||"",capabilities:y});f(`SELECT COUNT(*) as count FROM ${j}`),h(!0)},isNumberField:j=>xa(j.dataType)}}function Est(e){const t=e.qualifiedFieldName,r=(e.qualifiedEntityName||e.qualifiedFieldName.split(".").slice(0,-1).join(".")).split(".").map(o=>rx(o)).join("."),s=rx(e.name);return{qualifiedColumnName:t,qualifiedTableName:r,formattedColumnName:s}}function Soe(e){const t=e;return{name:e.name,qualifiedFieldName:e.qualifiedFieldName,qualifiedEntityName:e.qualifiedEntityName,entityName:e.entityName,entityId:e.entityId,entityType:e.entityType,dataType:e.dataType,role:e.role,expression:t.expression,calculatedFormula:t.calculatedFormula}}function Coe(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 Noe(e){var t,n;return e?!!(e.entityName===Ec||e.expression||(n=(t=e.calculatedFormula)==null?void 0:t.inputFields)!=null&&n.length):!1}function joe(){const e=Q(c=>c.dashboard.filters)||[],t=Q(c=>c.selectedSheetId),n=Q(c=>c.actions.addFilter),r=Q(c=>c.actions.removeFilter),{removeFilterValues:s}=un(),o=Le(c=>c.card.dataSource),{selectedConnection:i}=mi();function a(c,u="sheet"){const{qualifiedColumnName:d,qualifiedTableName:f,formattedColumnName:h}=Est(c);let m;if(u==="sheet"&&t?m=sMe(e,d,f,t):m=e==null?void 0:e.find(p=>cp(p.column)===cp(d)),m)s(m.id),r(m.id);else{const p=br(),g=Soe(c),b=Coe(o,{connectionId:i==null?void 0:i.id,connectionType:i==null?void 0:i.type}),x=Noe(g),y=u==="sheet"&&t?[t]:void 0;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:"in",applyToSheetIds:y,sql:x?"":qQ(c.dataType,f,h),fieldMeta:g,semanticContext:b}),p}}return{assignFilter:a}}function _st({column:e}){const[t,n]=w.useState(!1),r=Le(y=>y.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=XO(r),a=Le(y=>y.selectedDatamodelId),c=Le(y=>y.sqlGen),{modelItems:u,selectedConnection:d}=wj(),f=d==null?void 0:d.capabilities,h=Le(y=>y.actions.setSqlGen),m=Le(y=>y.actions.setCardSql),p=Le(y=>y.actions.setRunSql),g=voe(r);function b(y,v){var E,M;if(!g||!s){console.warn("Cannot generate SQL: missing table metadata");return}const S=hI(y,c,v),N=(E=u==null?void 0:u.find(k=>k.id===a))==null?void 0:E.name;if(h(S),!f){console.warn("Cannot generate SQL: missing connection capabilities");return}const C=(M=y.qualifiedFieldName)==null?void 0:M.split(".").slice(0,-1).join("."),j=fI(S,o||"",s,N||"",i||"",f,C);j&&(m(j),p(!0)),n(!1)}function x(){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 g?l.jsxs(Pp,{openDelay:0,open:t,onOpenChange:n,children:[l.jsx(Op,{asChild:!0,children:l.jsx(Ep,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),l.jsx(Fp,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:x()})]}):null}function Tst({field:e,fieldState:t}){return l.jsxs("div",{className:"w-64 bg-background p-0",children:[l.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[l.jsx("h3",{className:"text-sm font-medium text-foreground",children:e.label||e.name}),l.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:e.dataType})]}),e.description&&l.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:e.description}),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 pb-2 pt-2",children:l.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:e.name})})]})}function h9({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s,actions:o}){const i=Le(K=>K.isDevMode),a=t==="filter"||t==="inline-filter",c=i||a||(n==null?void 0:n.state)==="unreachable"&&!a,u=Q(K=>K.dashboard.filters),d=Q(K=>K.selectedSheetId),f=Q(K=>K.actions.removeFilter),{removeFilterValues:h}=un(),{assignFilter:m}=joe(),p=t==="filter"?Ac(u,d):u,g=t==="filter"?p==null?void 0:p.find(K=>{if(K.title===e.name)return!0;const te=cp(K.column||""),ie=cp(e.name);return te.endsWith(`.${ie}`)||te===ie}):void 0,b=!!g,x=t==="inline-filter"&&(s==null?void 0:s.some(K=>K.column===e.qualifiedFieldName||K.column===e.name)),y=b||x,v=g&&a?u==null?void 0:u.find(K=>K.id===g.id):void 0,S=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:S,selectedSheetId:d});const[N,C]=w.useState(!1),[j,E]=w.useState(null),{attributes:M,listeners:k,setNodeRef:_,transform:T,transition:P,isDragging:O}=_0({id:e.id,disabled:c}),[R,$]=w.useState(!1),Y=Le(K=>K.card),{handleFieldClick:W}=yoe(Y),{handleDevModeFieldClick:H,isNumberField:A}=woe(),L=()=>{v&&(console.log("[SourceField] Removing multi-sheet filter:",v.id),h(v.id),f(v.id)),E(null),C(!1)},F=()=>{if(t==="inline-filter"&&r){r(e);return}t==="filter"?y&&S?(E(e),C(!0)):m(e,"sheet"):i?H(e):W(e)},I={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},U={transform:Vi.Transform.toString(T),transition:P},V=()=>{if(!n||a)return{};const te={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[n.state]||{};return n.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",...te},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...te},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...te}}[n.state]||te};function G(K){return K==="domain"?{label:"Domain",Icon:Ny,className:"border-border bg-muted text-foreground"}:K==="dashboard"?{label:"Dashboard",Icon:$I,className:"border-border bg-muted/70 text-foreground"}:{label:"Card",Icon:uB,className:"border-border bg-muted/40 text-foreground"}}const B=V(),z=e.fieldScope,q=z?G(z):null,Z=L1(e),ee=Z&&Dc(e);return l.jsxs("div",{ref:_,style:U,...c?{}:M,...c?{}:k,className:X("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",O&&"scale-95 opacity-50",!O&&"border",B.borderColor||"border-transparent",B.bgColor||"",B.hoverBorderColor,B.hoverBgColor||"hover:bg-muted",B.opacity,B.cursor,b&&"border-accent-foreground/20 bg-accent",x&&"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:F,children:[l.jsxs("div",{className:"relative shrink-0",children:[bp(e.dataType),Z&&l.jsx("span",{className:X("absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 text-[7px] font-semibold uppercase italic leading-none shadow-sm",ee?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),l.jsx(nr,{children:l.jsxs(kn,{children:[l.jsx(En,{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(In,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:l.jsx(Tst,{field:e,fieldState:n})})]})}),t==="editor"&&q&&l.jsx("span",{title:q.label,className:X("shrink-0 rounded-full border p-1",q.className),children:l.jsx(q.Icon,{className:"h-3.5 w-3.5"})}),i&&!a&&A(e)&&l.jsx("div",{onClick:K=>K.stopPropagation(),children:l.jsx(_st,{column:I})}),o&&l.jsx("div",{className:"ml-auto flex items-center",onClick:K=>K.stopPropagation(),onPointerDown:K=>K.stopPropagation(),children:o})]}),R&&l.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:l.jsx(Lo,{className:"",children:l.jsxs(Oi,{className:"space-y-2 p-3",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(dB,{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(wue,{className:"h-4 w-4 text-muted-foreground"}),l.jsx("span",{className:"break-all",children:e.name})]}),l.jsx(st,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),l.jsx(ch,{open:N,onOpenChange:C,children:l.jsxs(Gu,{children:[l.jsxs(Ku,{children:[l.jsx(Xu,{children:"Remove Filter from Multiple Sheets?"}),l.jsx(Qu,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),l.jsxs(Zu,{children:[l.jsx(ed,{children:"Cancel"}),l.jsx(Ju,{onClick:L,children:"Remove Filter"})]})]})})]})}let koe=(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 iy=[{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}],zl=e=>e.trim().toLowerCase().replace(/\s+/g,"_"),Jl=e=>e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e;function m9(e,t,n,r,s,o,i,a,c,u){const d=iy.find(x=>x.id===t);if(!d)throw new Error(`Unknown operation: ${t}`);let f,h=[],m;if(t==="custom"){if(!(a!=null&&a.trim()))throw new Error("Custom expression is required");f=a.trim(),h=u||[]}else if(t==="scale"){if(!n)throw new Error("Metric A is required for scale operation");if(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]}const p={operation:t,inputFields:h,...m!==void 0&&{constant:m}},g=zl(e);return{id:i||`calc_${koe(10)}`,name:g,label:e,alias:g,qualifiedFieldName:g,dataType:"number",role:"metric",aggregate:"SUM",expression:f,calculatedFormula:p,entityId:o,entityName:Ec,entityType:"table",description:`Calculated field: ${e}`}}function Mst(e){var r,s;const t=iy.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 Ist(e,t,n,r,s,o){const i=zl(e);return{id:o||`calc_dim_${koe(10)}`,name:i,label:e.trim(),alias:i,qualifiedFieldName:i,dataType:r,role:"groupby",expression:t.trim(),calculatedFormula:{operation:"custom",inputFields:n.map(a=>a.role==="metric"?{...a,role:"metric"}:{...a,role:"groupby"})},entityId:s,entityName:Ec,entityType:"table",description:`Calculated field: ${e.trim()}`}}function Dst(){const{domainCalculatedFields:e}=KO(),t=w.useMemo(()=>e.filter(r=>r.role==="metric"),[e]),n=w.useMemo(()=>e.filter(r=>r.role==="groupby"),[e]);return{fields:e,metrics:t,dimensions:n}}function Ast({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(Os,{value:a,onValueChange:c=>t(c),className:"w-full",children:l.jsx(ws,{className:"grid h-9 w-full",style:{gridTemplateColumns:`repeat(${o.length}, minmax(0, 1fr))`},children:o.map(c=>l.jsx(pn,{value:c,disabled:i,className:"text-xs",children:c==="metric"?"Calculated Metric":"Calculated Dimension"},c))})})}function Rst({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 b of g){const x=u(p,b);if(x!==p)return x}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(zo,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),l.jsx(Ln,{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(Vt,{className:"size-3.5"})})]}),l.jsx(kl,{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(Hx,{type:"multiple",defaultValue:c,className:"space-y-2",children:e.map(f=>l.jsxs(ku,{value:f.id,className:"border-none",children:[l.jsx(Eu,{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(st,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:f.fields.length})]})}),l.jsx(_u,{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",b=d(h,f.label);return l.jsxs("button",{type:"button",onClick:()=>h.isCompatible&&!o&&r(h),className:X("group/container flex w-full items-center gap-3 rounded-lg border border-transparent px-2 py-2 text-left transition-all",p?"cursor-not-allowed opacity-50":"hover:bg-muted",m&&"border-border bg-muted"),disabled:p,children:[l.jsxs("div",{className:"relative shrink-0",children:[bp(h.dataType),h.isCalculated&&l.jsx("span",{className:X("absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 text-[7px] font-semibold uppercase italic leading-none shadow-sm",g?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),l.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:l.jsx("span",{className:X("block truncate text-sm text-foreground/80",!p&&"group-hover/container:text-foreground"),children:b})}),m&&l.jsx(st,{variant:"secondary",className:"shrink-0 text-[10px]",children:"Selected"})]},h.id)})})})]},f.id))})})]})}function Pst({value:e,onChange:t,allowCustom:n,disabled:r}){const s=iy.filter(c=>n?!0:c.id!=="custom"),i=!s.some(c=>c.id==="custom")&&e==="custom"?[...s,iy.find(c=>c.id==="custom")]:s,a=i.find(c=>c.id===e);return l.jsxs("div",{className:"space-y-2",children:[l.jsxs(yt,{value:e,onValueChange:c=>t(c),disabled:r,children:[l.jsx(gt,{children:l.jsx(St,{})}),l.jsx(bt,{children:l.jsxs(BA,{children:[l.jsx(cN,{children:"OPERATIONS"}),i.map(c=>l.jsx(je,{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 Ost={COUNT:"Count",DISTINCT:"Count Distinct",SUM:"Sum",AVG:"Average",MIN:"Minimum",MAX:"Maximum",MEDIAN:"Median"};function Fst({value:e,onChange:t,disabled:n,fieldDataType:r,allowMedian:s}){const i=(r?Ar(r):"number")==="number",a=["SUM","AVG","COUNT","DISTINCT","MIN","MAX"],c=i?s?[...a,"MEDIAN"]:a:["COUNT","DISTINCT"];return l.jsxs(yt,{value:e,onValueChange:u=>t(u),disabled:n,children:[l.jsx(gt,{className:"h-9",children:l.jsx(St,{})}),l.jsx(bt,{children:c.map(u=>l.jsx(je,{value:u,children:Ost[u]},u))})]})}const $st=e=>{const n=(e.name||e.baseLabel||e.label||e.tokenLabel||"").trim();return n.includes(".")&&n.split(".").pop()||n};function p9({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:X("flex items-center gap-2 rounded-md border border-border px-2 py-2",a&&!u&&"cursor-pointer",u&&"opacity-60"),onClick:u?void 0:a,children:[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(yt,{value:d,onValueChange:h=>{const m=f.find(p=>p.id===h);m&&s(m)},disabled:u,children:[l.jsx(gt,{className:"h-9 flex-1",children:l.jsx(St,{placeholder:"Select field"})}),l.jsx(bt,{children:f.map(h=>l.jsx(je,{value:h.id,children:$st(h)},h.id))})]}),l.jsx("div",{className:"w-36",children:l.jsx(Fst,{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(re,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:h=>{h.stopPropagation(),i()},disabled:u,children:l.jsx(Vt,{className:"h-3.5 w-3.5"})})]})}const g9=w.forwardRef(function({value:t,onChange:n,onGenerate:r,showGenerate:s,disabled:o},i){return l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("span",{className:"text-sm font-medium",children:"Expression"}),s&&l.jsxs(re,{type:"button",size:"sm",variant:"outline",onClick:r,disabled:o,className:"h-7 gap-2 text-xs",children:[l.jsx(jy,{className:"h-3.5 w-3.5"}),"Generate with AI"]})]}),l.jsx(pp,{ref:i,value:t,onChange:a=>n(a.target.value),disabled:o,placeholder:"CASE WHEN {Amount} > 100 THEN 'Large' ELSE 'Small' END",className:"min-h-[140px] font-mono text-xs"})]})});function Lst({result:e}){const t=e.errors.length>0;return l.jsxs("div",{className:X("rounded-md border px-3 py-2 text-xs",t?"border-destructive/40 bg-destructive/10 text-destructive":"border-emerald-500/30 bg-emerald-500/10 text-emerald-700"),children:[l.jsx("div",{className:"font-medium",children:t?"Validation Failed":"Validation Passed"}),e.tokens.length>0&&l.jsxs("div",{className:"mt-2 space-y-1",children:[l.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Tokens Found"}),e.tokens.map(n=>l.jsx("div",{children:n.field?`{${n.token}} -> ${n.field.qualifiedFieldName||n.field.name}`:`{${n.token}}`},n.token))]}),e.errors.length>0&&l.jsxs("div",{className:"mt-2 space-y-1",children:[l.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Errors"}),e.errors.map((n,r)=>l.jsxs("div",{children:[n.message,n.suggestion?` (${n.suggestion})`:""]},`${n.code}-${r}`))]}),e.warnings.length>0&&l.jsxs("div",{className:"mt-2 space-y-1",children:[l.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Warnings"}),e.warnings.map((n,r)=>l.jsxs("div",{children:[n.message," ",n.suggestion]},`${n.code}-${r}`))]}),e.inferredDataType&&l.jsxs("div",{className:"mt-2 text-[11px] text-muted-foreground",children:["Inferred Output Type: ",e.inferredDataType]})]})}function b9({onValidate:e,isValidating:t,validationResult:n,fallbackResult:r,error:s,showFallback:o,disabled:i}){return l.jsxs("div",{className:"space-y-2",children:[l.jsx(re,{type:"button",variant:"outline",onClick:e,disabled:t||i,className:"h-8",children:t?"Validating...":"Validate Expression"}),s&&l.jsx("div",{className:"text-xs text-destructive",children:s}),(n||o)&&l.jsx(Lst,{result:n||r})]})}function zst({scope:e,onChange:t,showDashboardScope:n,showDomainScope:r,error:s,disabled:o}){return l.jsxs("div",{className:"space-y-3 border-t border-border pt-4",children:[l.jsx(de,{children:"Availability"}),l.jsxs(Ts,{value:e,onValueChange:i=>t(i),className:"space-y-2",disabled:o,children:[l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx(Cn,{id:"scope-card",value:"card"}),l.jsx(de,{htmlFor:"scope-card",className:"text-sm font-normal",children:"This card only"})]}),n&&l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx(Cn,{id:"scope-dashboard",value:"dashboard"}),l.jsx(de,{htmlFor:"scope-dashboard",className:"text-sm font-normal",children:"All cards in this dashboard"})]}),r&&l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx(Cn,{id:"scope-domain",value:"domain"}),l.jsx(de,{htmlFor:"scope-domain",className:"text-sm font-normal",children:"Save to domain"})]})]}),s&&l.jsx("p",{className:"text-xs text-red-500",children:s})]})}function Bst({description:e,tags:t,onDescriptionChange:n,onTagsChange:r,descriptionError:s,disabled:o}){return l.jsxs("div",{className:"space-y-3 rounded-md border border-muted bg-muted/30 p-3",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{htmlFor:"domain-description",children:"Description"}),l.jsx(Ma,{id:"domain-description",value:e,onChange:i=>n(i.target.value),placeholder:"Explain what this metric represents",className:X("text-sm",s&&"border-red-500"),rows:3,disabled:o}),s&&l.jsx("p",{className:"text-xs text-red-500",children:s})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{htmlFor:"domain-tags",children:"Tags (optional)"}),l.jsx(sn,{id:"domain-tags",value:t,onChange:i=>r(i.target.value),placeholder:"profitability, kpi",disabled:o})]}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"This field will be visible to all dashboards using this domain."})]})}function Vst({endpoint:e,availableFields:t,fieldType:n,dialect:r}){const{authToken:s}=Je(),[o,i]=w.useState(!1),[a,c]=w.useState(null);return{generateExpression:w.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})),fieldType:n},options:{dialect:r}},m=await ls(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((h==null?void 0:h.error)||(h==null?void 0:h.message)||"AI generation failed"),null}finally{i(!1)}},[e,t,n,r,s==null?void 0:s.accessToken]),isGenerating:o,error:a}}function Ust({open:e,onOpenChange:t,availableFields:n,fieldType:r,onExpressionGenerated:s,endpoint:o,dialect:i}){const[a,c]=w.useState(""),[u,d]=w.useState(""),[f,h]=w.useState(""),{generateExpression:m,isGenerating:p,error:g}=Vst({endpoint:o,availableFields:n,fieldType:r,dialect:i}),b=w.useMemo(()=>{const C=f.trim().toLowerCase();return C?n.filter(j=>[j.label,j.baseLabel,j.name,j.tokenLabel,j.entityName,j.qualifiedEntityName].filter(Boolean).join(" ").toLowerCase().includes(C)):n},[n,f]),x=C=>{const E=(C.name||C.baseLabel||C.label||C.tokenLabel||"").trim();return E.includes(".")&&E.split(".").pop()||E},y=C=>{const j=C.entityName||C.qualifiedEntityName||"";return j?j==="SEMAPHOR_CALCULATED_FIELD"?"Calculated":j.includes(".")&&j.split(".").pop()||j:"—"},v=async()=>{const C=await m(a.trim());C&&d(C)},S=()=>{u.trim()&&(s(u.trim()),c(""),d(""),t(!1))},N=()=>{c(""),d(""),h(""),t(!1)};return l.jsx(qr,{open:e,onOpenChange:C=>{C?t(!0):N()},children:l.jsxs(Pr,{className:"max-w-3xl",children:[l.jsxs(Or,{children:[l.jsx(Fr,{children:"Generate Expression with AI"}),l.jsx(Jr,{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(de,{htmlFor:"ai-prompt",children:"Describe what you want to calculate"}),l.jsx(pp,{id:"ai-prompt",value:a,onChange:C=>c(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(re,{size:"sm",onClick:v,disabled:p||!a.trim(),children:p?"Generating...":u?"Regenerate":"Generate"})]}),g&&l.jsx("p",{className:"text-xs text-destructive",children:g})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{children:"Available fields"}),l.jsxs("div",{className:"relative",children:[l.jsx(zo,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),l.jsx(sn,{value:f,onChange:C=>h(C.target.value),placeholder:"Search fields...",className:"pl-9"})]}),l.jsx("div",{className:"overflow-hidden rounded-lg border border-border",children:l.jsx("div",{className:"max-h-48 overflow-y-auto",children:l.jsxs("table",{className:"w-full text-sm",children:[l.jsx("thead",{className:"sticky top-0 z-10 border-b bg-muted",children:l.jsxs("tr",{children:[l.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Field"}),l.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Type"}),l.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Category"})]})}),l.jsx("tbody",{className:"divide-y",children:b.length===0?l.jsx("tr",{children:l.jsx("td",{colSpan:3,className:"py-6 text-center text-xs text-muted-foreground",children:"No fields match your search."})}):b.map(C=>l.jsxs("tr",{className:"hover:bg-muted/30",children:[l.jsx("td",{className:"px-3 py-1.5 font-mono text-xs",children:x(C)}),l.jsx("td",{className:"px-3 py-1.5",children:l.jsx(st,{variant:"secondary",className:"px-1.5 py-0 text-[11px]",children:C.dataType})}),l.jsx("td",{className:"px-3 py-1.5 text-sm text-muted-foreground",children:y(C)})]},C.id))})]})})})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{children:"Generated expression"}),l.jsx(pp,{value:u,readOnly:!0,rows:2,className:"font-mono text-sm"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Review the generated expression before using it."})]})]}),l.jsxs(vs,{className:"gap-2",children:[l.jsx(re,{variant:"ghost",onClick:N,children:"Cancel"}),l.jsx(re,{onClick:S,disabled:!u.trim(),children:"Use Expression"})]})]})})}const Hst=/\{([^}]+)\}/g;function Sj(e){return e.trim().toLowerCase()}function HS(e){return Array.from(e.matchAll(Hst)).map(t=>t[1]).filter(Boolean)}function Wst(e){const t=new Set,n=[];return e.forEach(r=>{const s=Sj(r);t.has(s)||(t.add(s),n.push(r))}),n}function QO(e){const t=new Map,n=(r,s)=>{const o=Sj(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 Zg(e,t){const n=HS(e),r=Wst(n),s=QO(t),o=r.map(a=>{const c=s.get(Sj(a))||[];return c.length===1?c[0]:null}),i=r.filter((a,c)=>!o[c]);return{orderedTokens:r,orderedFields:o,unresolvedTokens:i}}function x9(e,t){return t.reduce((n,r,s)=>{const o=new RegExp(`\\{${qst(r)}\\}`,"gi");return n.replace(o,`{field_${s}}`)},e)}function qst(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Yst=e=>e.entityName===Bm||e.entityName===Ec?"Calculated Fields":e.qualifiedEntityName?ox(e.entityName||e.qualifiedEntityName):ox(e.entityName||"Other"),Gst=e=>Ar(e.dataType||"")==="number";function Kst(e,t,n){const r=new Set((n||[]).map(s=>Jl(s)));return e.filter(s=>{const o=Jl(s.id);return o&&r.has(o)?!1:t==="dimension"?s.role!=="metric":!0})}function Zst(e){const t=new Map,n=new Map;return e.forEach(r=>{let o=r.entityName&&r.entityName!==Ec?`${r.entityName}.${r.name}`:r.name;const i=o.toLowerCase(),a=n.get(i)||0;a>0&&(o=`${o} ${a+1}`),n.set(i,a+1),t.set(r.id,o)}),t}function Xst(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||Gst(o);return{...o,isCompatible:i}}).filter(o=>r)}function Qst(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 Jst(e){const t=new Map;return e.forEach(n=>{var s;const r=n.qualifiedEntityName||n.entityName||"Other";t.has(r)||t.set(r,{id:r,label:Yst(n),fields:[]}),(s=t.get(r))==null||s.fields.push(n)}),Array.from(t.values())}function eot({fields:e,mode:t,searchTerm:n,excludeFieldIds:r,selectedAggregate:s,showIncompatible:o}){const i=w.useMemo(()=>Kst(e,t,r),[e,t,r]),a=w.useMemo(()=>Zst(i),[i]),c=w.useMemo(()=>i.map(m=>{const p=m.label||m.name,g=m.role==="metric"&&Dc(m)||m.role==="groupby"&&Wy(m);return{...m,baseLabel:p,tokenLabel:a.get(m.id)||p,isCalculated:g,isCompatible:!0}}),[i,a]),u=w.useMemo(()=>QO(c),[c]),d=w.useMemo(()=>Xst(c,t,s,o),[c,t,s,o]),f=w.useMemo(()=>Qst(d,n),[d,n]),h=w.useMemo(()=>Jst(f),[f]);return{allFields:c,filteredFields:f,groups:h,tokenCandidates:u}}const tot=e=>{let t=0;for(const n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0},not=(e,t)=>{const n=e.toLowerCase(),r=t.toLowerCase();if(n===r)return 0;if(!n.length)return r.length;if(!r.length)return n.length;const s=[];for(let o=0;o<=r.length;o+=1)s[o]=[o];for(let o=0;o<=n.length;o+=1)s[0][o]=o;for(let o=1;o<=r.length;o+=1)for(let i=1;i<=n.length;i+=1)r.charAt(o-1)===n.charAt(i-1)?s[o][i]=s[o-1][i-1]:s[o][i]=Math.min(s[o-1][i-1]+1,s[o][i-1]+1,s[o-1][i]+1);return s[r.length][n.length]},rot=(e,t)=>t.map(r=>({candidate:r,distance:not(e,r)})).filter(r=>r.distance>0&&r.distance<=3).sort((r,s)=>r.distance-s.distance).slice(0,3).map(r=>r.candidate),sot=(e,t)=>{var r;const n=e.trim();if(n){if(/\bDATE_TRUNC\b/i.test(n))return"date";if(/\bTIMESTAMP\b/i.test(n))return"datetime";if(/\bDATE\b/i.test(n)&&!/\bUPDATE\b/i.test(n))return"date";if(/['"]/.test(n))return"string";if(/[+\-*/]/.test(n))return"number";if(t.length===1){const s=((r=t[0])==null?void 0:r.dataType)||"";if(/date|timestamp/i.test(s))return"date";if(/int|decimal|float|double|num|real/i.test(s))return"number";if(/boolean/i.test(s))return"boolean"}return"string"}},oot=e=>e.map(t=>({id:t.id,name:t.name,label:t.tokenLabel,dataType:t.dataType,entityName:t.entityName,role:t.role}));function iot({expression:e,availableFields:t,excludeFieldIds:n,validationEndpoint:r,connectionId:s,dialect:o}){const{authToken:i}=Je(),[a,c]=w.useState(null),[u,d]=w.useState(!1),[f,h]=w.useState(null),m=w.useMemo(()=>QO(t),[t]),p=w.useMemo(()=>{const x=[],y=[],v=e.trim();v||x.push({code:"SYNTAX_ERROR",message:"Expression is required"}),v&&!tot(v)&&x.push({code:"SYNTAX_ERROR",message:"Unbalanced parentheses in expression"});const N=HS(e).map(j=>{const E=m.get(Sj(j))||[];if(!E.length){const _=Array.from(m.keys()),T=rot(j,_),P=T.length?`Did you mean {${T[0]}}?`:void 0;return x.push({code:"UNKNOWN_TOKEN",message:`Unknown field token: {${j}}`,suggestion:P}),{token:j,field:null,error:"Unknown token"}}if(E.length>1)return x.push({code:"UNKNOWN_TOKEN",message:`Token {${j}} matches multiple fields. Use a disambiguated label.`}),{token:j,field:null,error:"Ambiguous token"};const M=E[0];return(n||[]).map(Jl).includes(Jl(M.id))?(x.push({code:"SELF_REFERENCE",message:"Cannot reference the field being edited"}),{token:j,field:null,error:"Self reference"}):{token:j,field:M}});/\bCASE\b/i.test(e)&&!/\bELSE\b/i.test(e)&&y.push({code:"MISSING_ELSE",message:"CASE expression missing ELSE clause",suggestion:"Add an ELSE branch to handle default values."}),/\//.test(e)&&!/NULLIF\s*\(/i.test(e)&&y.push({code:"DIVISION_BY_ZERO",message:"Division may result in divide-by-zero errors",suggestion:"Wrap the denominator in NULLIF(..., 0)."});const C=N.map(j=>j.field).filter(Boolean);return{isValid:x.length===0,tokens:N,errors:x,warnings:y,inferredDataType:sot(e,C)}},[e,n,m]),g=w.useCallback(async()=>{var v;if(h(null),!r||!p.isValid)return c(p),p;const x=r,y={type:"calculated-field-expression",value:e,context:{availableFields:oot(t),connectionId:s,excludeFieldIds:n,dialect:o}};d(!0);try{const S=await ls(x,(i==null?void 0:i.accessToken)||"",y),N=S.errors||[],C=S.warnings||[],j={...p,isValid:S.valid&&N.length===0,errors:N,warnings:C,inferredDataType:((v=S.metadata)==null?void 0:v.inferredType)||p.inferredDataType};return c(j),j}catch(S){return h((S==null?void 0:S.error)||"Validation failed"),c(p),p}finally{d(!1)}},[r,p,e,t,s,n,o,i==null?void 0:i.accessToken]),b=w.useCallback(()=>{c(null),h(null)},[]);return{clientResult:p,validationResult:a,isValidating:u,serverError:f,validateExpression:g,resetValidation:b}}const y9=[{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"}],EE=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})`},Eoe=e=>Ar(e.dataType||"")==="number",Gh=e=>Eoe(e)?"SUM":"COUNT",_E=(e,t)=>Eoe(e)||t==="COUNT"||t==="DISTINCT"?t:Gh(e);function TE(e,t){if(e.role==="metric"){const n=e;return Dc(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 zh(e,t){const n=e.role==="metric"&&Dc(e);return{field:e,aggregate:n&&e.aggregate||t,isCalculatedField:n}}function _oe({open:e,onOpenChange:t,availableFields:n,existingField:r,existingFieldScope:s,onSave:o,onSaveToDashboard:i,onPromoteMetricToDomain:a,onPromoteDimensionToDomain:c,cardId:u,domainId:d,initialFieldType:f="metric",allowedFieldTypes:h}){var Ve;const{tokenProps:m}=Je(),{selectedConnection:p}=xY(),g=(p==null?void 0:p.dialect)==="bigquery"||(p==null?void 0:p.dialect)==="snowflake",[b,x]=w.useState(f),[y,v]=w.useState(""),[S,N]=w.useState("ratio"),[C,j]=w.useState(null),[E,M]=w.useState(null),[k,_]=w.useState(1),[T,P]=w.useState(""),[O,R]=w.useState(null),[$,Y]=w.useState("card"),[W,H]=w.useState(""),[A,L]=w.useState(""),[F,I]=w.useState({}),[U,V]=w.useState("A"),[G,B]=w.useState(""),[z,q]=w.useState(!1),[Z,ee]=w.useState(null),[K,te]=w.useState(!1),[ie,ue]=w.useState(!1),[le,we]=w.useState(!1),se=w.useRef(null),ke=w.useRef(!1),be=w.useRef(null),{userContext:Me}=ro(),{metrics:Pe,dimensions:ge}=Dst(),$e=(Me==null?void 0:Me.type)==="organization",ce=!$e,J=!!d&&$e,ae=J&&!!a,ve=J&&!!c,Ce=!!(i||ae||ve),Ee=!!i,me=b==="metric"?ae:ve,De=(Ve=m==null?void 0:m.apiServiceUrl)==null?void 0:Ve.replace(/\/$/,""),He=De?`${De}/v1/validate`:"/v1/validate",et=De?`${De}/v1/ai/generate`:"/v1/ai/generate",Te=w.useMemo(()=>{var xt;const pe=[...n];return(((xt=r==null?void 0:r.calculatedFormula)==null?void 0:xt.inputFields)||[]).forEach(Se=>{pe.some(ct=>ct.id===Se.id||ct.qualifiedFieldName===Se.qualifiedFieldName||ct.name===Se.name)||pe.push(Se)}),pe},[n,r]),Ye=U==="A"?C:E,nt=b==="metric"&&S!=="custom"?Ye==null?void 0:Ye.aggregate:void 0,{allFields:Re,groups:it}=eot({fields:Te,mode:b,searchTerm:G,excludeFieldIds:r?[r.id]:void 0,selectedAggregate:nt,showIncompatible:!0}),ye=Re,{clientResult:tt,validationResult:Ue,validateExpression:Qe,isValidating:Et,serverError:Oe,resetValidation:Ne}=iot({expression:T,availableFields:ye,excludeFieldIds:r?[r.id]:void 0,validationEndpoint:He,connectionId:p==null?void 0:p.id,dialect:p==null?void 0:p.dialect}),ze=(Ue==null?void 0:Ue.inferredDataType)||tt.inferredDataType,ft=O||ze||"string",lt=iy.find(pe=>pe.id===S),fe=w.useMemo(()=>{if(!y.trim())return!1;const pe=zl(y),rt=s==="domain"&&(r!=null&&r.name)?zl(r.name):null;return(b==="metric"?Pe:ge).some(Se=>{const Ge=zl(Se.name);return rt&&Ge===rt?!1:Ge===pe})},[ge,Pe,r,s,b,y]),qe=w.useMemo(()=>{if(b==="metric"&&S==="custom"){const{orderedFields:rt}=Zg(T,ye);return rt.filter(xt=>!!xt).map(xt=>xt.id)}const pe=[];return C!=null&&C.field.id&&pe.push(C.field.id),E!=null&&E.field.id&&pe.push(E.field.id),pe},[ye,T,b,C,E,S]),at=pe=>{ce||(x(pe),pe==="dimension"&&$==="domain"&&!ve&&Y("card"),pe==="metric"&&$==="domain"&&!ae&&Y("card"))},Pt=pe=>{ce||(N(pe),pe==="scale"&&M(null),pe==="custom"&&(j(null),M(null)))},$t=()=>{v(""),N("ratio"),j(null),M(null),_(1),P(""),R(null),Y("card"),H(""),L(""),I({}),B(""),q(!1),ee(null),te(!1),we(!1),Ne(),t(!1)},Tn=w.useCallback(pe=>Te.find(rt=>rt.qualifiedFieldName===pe.qualifiedFieldName||rt.name===pe.name)||pe,[Te]),or=w.useCallback(pe=>{if(!pe.calculatedFormula)return;const rt=pe.calculatedFormula;if(N(rt.operation),P(""),rt.operation==="scale"){const Ge=rt.inputFields[0];Ge&&j(zh(Tn(Ge),Ge.aggregate||"SUM")),_(rt.constant===void 0?1:rt.constant);return}if(rt.operation==="custom"){P(ss(pe.expression||"",rt.inputFields||[])),j(null),M(null);return}const[xt,Se]=rt.inputFields;xt&&j(zh(Tn(xt),xt.aggregate||"SUM")),Se&&M(zh(Tn(Se),Se.aggregate||"SUM"))},[Tn]),ss=w.useCallback((pe,rt)=>pe.replace(/\{field_(\d+)\}/g,(xt,Se)=>{var mt;const Ge=rt[Number(Se)];return Ge?`{${((mt=ye.find(Ct=>Ct.id===Ge.id))==null?void 0:mt.tokenLabel)||Ge.label||Ge.name}}`:xt}),[ye]);w.useEffect(()=>{var xt;if(!e){ke.current=!1,be.current=null;return}const pe=r?`${r.role}-${r.id||r.name}`:"new";if(ke.current&&be.current===pe)return;if(ke.current=!0,be.current=pe,I({}),B(""),we(!1),Ne(),r){const Se=r.tags||[];if(r.role==="metric"){x("metric"),v(r.label||r.name),Y(s||"card"),H(r.description||""),L(Se.join(", ")),or(r);return}x("dimension");const Ge=r;v(Ge.label||Ge.name),Y(s||"card"),P(ss(Ge.expression||"",((xt=Ge.calculatedFormula)==null?void 0:xt.inputFields)||[]));const ct=y9.some(mt=>mt.value===Ge.dataType)?Ge.dataType:"string";R(ct),H(Ge.description||""),L(Se.join(", "));return}const rt=h&&h.length>0?h.includes(f)?f:h[0]:f;x(rt),v(""),N("ratio"),j(null),M(null),_(1),P(""),R(null),Y("card"),H(""),L("")},[e,r,s,f,h,or,ss,Ne]);const Fs=pe=>{const rt=`{${pe}}`,xt=se.current;if(!xt){P(mt=>mt+rt);return}const Se=xt.selectionStart||0,Ge=xt.selectionEnd||0,ct=`${T.slice(0,Se)}${rt}${T.slice(Ge)}`;P(ct),requestAnimationFrame(()=>{xt.focus();const mt=Se+rt.length;xt.setSelectionRange(mt,mt)})},Ki=pe=>{if(ce)return;if(b==="dimension"||S==="custom"){Fs(pe.tokenLabel||pe.label||pe.name);return}const rt=_E(pe,U==="A"?(C==null?void 0:C.aggregate)||Gh(pe):(E==null?void 0:E.aggregate)||Gh(pe)),xt=zh(pe,rt);if(U==="A"){j(xt),E||V("B");return}M(xt),C||V("A")},Ss=(pe,rt)=>{if(!ce){if(pe==="A"&&C){j({...C,aggregate:rt});return}pe==="B"&&E&&M({...E,aggregate:rt})}},jo=async()=>{const pe={};if(y.trim()||(pe.name="Name is required"),S==="custom")T.trim()||(pe.expression="Expression is required"),HS(T).length===0&&(pe.expression=pe.expression||"Expression must include field tokens"),Zg(T,ye).unresolvedTokens.length>0&&(pe.expression=pe.expression||"Expression contains unknown or ambiguous tokens"),pe.expression||(await Qe()).isValid||(pe.expression="Fix validation errors before saving");else if(S==="scale")C||(pe.inputA="Please select a metric for input A"),Number.isNaN(k)&&(pe.constant="Please enter a valid multiplication factor");else{if(C||(pe.inputA="Please select a metric for input A"),E||(pe.inputB="Please select a metric for input B"),C&&E){const rt=C.field.id===E.field.id,xt=C.aggregate===E.aggregate;rt&&xt&&(pe.inputs="Inputs A and B must be different metrics")}if(r&&r.role==="metric"){const rt=Jl(r.id);(Jl(C==null?void 0:C.field.id)===rt||Jl(E==null?void 0:E.field.id)===rt)&&(pe.inputs="Cannot reference the field being edited")}}return Ce&&($==="domain"&&!ae&&(pe.scope="You do not have permission to save to domain"),$==="domain"&&!W.trim()&&(pe.description="Description is required for domain fields"),$==="domain"&&fe&&(pe.name="A domain field with this name already exists")),I(pe),Object.keys(pe).length===0},Tl=async()=>{const pe={};return y.trim()||(pe.name="Name is required"),T.trim()||(pe.expression="Expression is required"),HS(T).length===0&&(pe.expression=pe.expression||"Expression must include field tokens"),Zg(T,ye).unresolvedTokens.length>0&&(pe.expression=pe.expression||"Expression contains unknown or ambiguous tokens"),pe.expression||(await Qe()).isValid||(pe.expression="Fix validation errors before saving"),Ce&&($==="domain"&&!ve&&(pe.scope="You do not have permission to save to domain"),$==="domain"&&!W.trim()&&(pe.description="Description is required for domain fields"),$==="domain"&&fe&&(pe.name="A domain field with this name already exists")),I(pe),Object.keys(pe).length===0},Ml=()=>{const{orderedTokens:pe,orderedFields:rt}=Zg(T,ye),xt=rt.filter(ct=>!!ct),Se=x9(T,pe),Ge=Ist(y,Se,xt,ft,u,r==null?void 0:r.id);return r&&r.role==="groupby"?{...r,...Ge}:Ge},Il=()=>{var Se;if(S==="custom"){const{orderedTokens:Ge,orderedFields:ct}=Zg(T,ye),mt=ct.filter(Ft=>!!Ft),Ct=(r==null?void 0:r.role)==="metric"?((Se=r.calculatedFormula)==null?void 0:Se.inputFields)||[]:[],Mt=new Map;Ct.forEach(Ft=>{const Pn=Jl(Ft.id);Pn&&Mt.set(Pn,Ft),Ft.qualifiedFieldName&&Mt.set(Ft.qualifiedFieldName,Ft),Ft.name&&Mt.set(Ft.name,Ft)});const zr=mt.map(Ft=>{const Pn=Jl(Ft.id),Uo=Pn&&Mt.get(Pn)||Ft.qualifiedFieldName&&Mt.get(Ft.qualifiedFieldName)||Mt.get(Ft.name),wh=((Uo==null?void 0:Uo.role)==="metric"?Uo.aggregate:void 0)||(Ft.role==="metric"?Ft.aggregate:void 0)||Gh(Ft);return TE(Ft,wh)}),Bt=x9(T,Ge),Ot=m9(y,S,null,null,{},u,r==null?void 0:r.id,Bt,void 0,zr);return r&&r.role==="metric"?{...r,...Ot}:Ot}const pe=C?TE(C.field,C.aggregate):null,rt=E?TE(E.field,E.aggregate):null,xt=m9(y,S,pe,rt,{},u,r==null?void 0:r.id,void 0,S==="scale"?k:void 0);return r&&r.role==="metric"?{...r,...xt}:xt},Dl=async pe=>{var xt,Se,Ge;if(b==="dimension"){const ct=Ml();if(pe==="dashboard"){if(!i){I(mt=>({...mt,scope:"Dashboard scope is not available"}));return}i(ct),$t();return}if(pe==="domain"){if(!c){I(Ot=>({...Ot,scope:"Domain scope is not available"}));return}const mt=((xt=ct.calculatedFormula)==null?void 0:xt.inputFields)||[],Ct=new Map,Mt=mt.map(Ot=>{const Ft=zl(Ot.label||Ot.name),Pn=Ct.get(Ft)||0;return Ct.set(Ft,Pn+1),Pn===0?Ft:`${Ft}_${Pn+1}`}),zr=((Se=ct.expression)==null?void 0:Se.replace(/\{field_(\d+)\}/g,(Ot,Ft)=>`{${Mt[Number(Ft)]||Ft}}`))||"",Bt=Mt.reduce((Ot,Ft,Pn)=>{const Uo=mt[Pn];return Wy(Uo)?Ot[Ft]={dimension:Uo.name}:Ot[Ft]={dataset:Uo.entityName,field:Uo.name},Ot},{});try{await c({name:zl(y),label:y.trim(),description:W.trim(),expression:zr,inputs:Bt,dataType:ft,tags:A.split(",").map(Ot=>Ot.trim()).filter(Boolean),overwrite:s==="domain",previousName:s==="domain"?r==null?void 0:r.name:void 0})}catch(Ot){I(Ft=>({...Ft,scope:(Ot==null?void 0:Ot.message)||"Failed to save to domain"}));return}$t();return}o(ct),$t();return}const rt=Il();if(pe==="dashboard"){if(!i){I(ct=>({...ct,scope:"Dashboard scope is not available"}));return}i(rt),$t();return}if(pe==="domain"){if(!a){I(Bt=>({...Bt,scope:"Domain scope is not available"}));return}if(!rt.calculatedFormula){I(Bt=>({...Bt,scope:"Calculated formula missing"}));return}const ct=rt.calculatedFormula.inputFields,mt=new Map,Ct=ct.map(Bt=>{const Ot=zl(Bt.label||Bt.name),Ft=mt.get(Ot)||0;return mt.set(Ot,Ft+1),Ft===0?Ot:`${Ot}_${Ft+1}`}),Mt=((Ge=rt.expression)==null?void 0:Ge.replace(/\{field_(\d+)\}/g,(Bt,Ot)=>`{${Ct[Number(Ot)]||Ot}}`))||"",zr=Ct.reduce((Bt,Ot,Ft)=>{const Pn=ct[Ft];return Pn.role==="metric"?Dc(Pn)?Bt[Ot]={metric:Pn.name}:Bt[Ot]={dataset:Pn.entityName,field:Pn.name,aggregate:Pn.aggregate}:Bt[Ot]={dataset:Pn.entityName,field:Pn.name},Bt},{});try{await a({name:zl(y),label:y.trim(),description:W.trim(),expression:Mt,inputs:zr,tags:A.split(",").map(Bt=>Bt.trim()).filter(Boolean),overwrite:s==="domain",previousName:s==="domain"?r==null?void 0:r.name:void 0})}catch(Bt){I(Ot=>({...Ot,scope:(Bt==null?void 0:Bt.message)||"Failed to save to domain"}));return}$t();return}o(rt),$t()},pt=async()=>{if(ce)return;if(I({}),b==="metric"){if(!await jo())return}else if(!await Tl())return;const pe=Ce?$:s||"card";if(b==="metric"&&pe!=="domain"&&fe&&!r){ee(pe),te(!0);return}ue(!0);try{await Dl(pe)}finally{ue(!1)}},he=w.useMemo(()=>{if(!lt||S==="custom")return"";if(S==="scale"){const pe=Number.isFinite(k)?k:1;return`${EE(C)} x ${pe}`}return`${EE(C)||"A"} ${lt.symbol} ${EE(E)||"B"}`},[lt,S,C,E,k]);return l.jsxs(l.Fragment,{children:[l.jsxs(qr,{modal:!1,open:e,onOpenChange:pe=>{pe?t(!0):$t()},children:[e&&l.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),l.jsxs(Pr,{className:"max-w-5xl max-h-[90vh] overflow-hidden",onInteractOutside:pe=>{pe.preventDefault()},children:[l.jsxs(Or,{children:[l.jsxs(Fr,{children:[r?"Edit":"Create"," Calculated Field"]}),l.jsx(Jr,{children:"Build calculated metrics and dimensions using expressions."})]}),l.jsxs("div",{className:"grid h-[70vh] min-h-0 grid-cols-[320px_1fr] gap-6",children:[l.jsx(Rst,{groups:it,searchTerm:G,onSearchTermChange:B,onFieldClick:Ki,selectedFieldIds:qe,disabled:ce}),l.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-4 overflow-y-auto pr-2",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{children:"Field Type"}),l.jsx(Ast,{value:b,onChange:at,disabled:ce||!!r,options:h||["metric","dimension"]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{htmlFor:"calculated-name",children:"Name"}),l.jsx(sn,{id:"calculated-name",value:y,onChange:pe=>v(pe.target.value),placeholder:"e.g., Profit Margin",className:F.name?"border-red-500":"",disabled:ce}),F.name&&l.jsx("p",{className:"text-xs text-red-500",children:F.name})]}),b==="metric"&&l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{children:"Operation"}),l.jsx(Pst,{value:S,onChange:Pt,allowCustom:!0,disabled:ce}),F.operation&&l.jsx("p",{className:"text-xs text-red-500",children:F.operation})]}),S==="custom"?l.jsxs("div",{className:"space-y-4",children:[l.jsx(g9,{ref:se,value:T,onChange:pe=>{P(pe),we(!1)},onGenerate:()=>q(!0),showGenerate:!!et&&!ce,disabled:ce}),l.jsx(b9,{onValidate:async()=>{we(!0),await Qe()},isValidating:Et,validationResult:Ue,fallbackResult:tt,error:Oe,showFallback:le,disabled:ce}),F.expression&&l.jsx("p",{className:"text-xs text-red-500",children:F.expression})]}):l.jsxs("div",{className:"space-y-3",children:[l.jsx(de,{children:"Inputs"}),l.jsx(p9,{label:"A",input:C,availableFields:ye,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:pe=>{const rt=_E(pe,(C==null?void 0:C.aggregate)||Gh(pe));j(zh(pe,rt))},onAggregateChange:pe=>Ss("A",pe),onRemove:()=>j(null),onActivate:()=>V("A"),allowMedian:g,disabled:ce}),F.inputA&&l.jsx("p",{className:"text-xs text-red-500",children:F.inputA}),S!=="scale"&&l.jsxs(l.Fragment,{children:[l.jsx(p9,{label:"B",input:E,availableFields:ye,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:pe=>{const rt=_E(pe,(E==null?void 0:E.aggregate)||Gh(pe));M(zh(pe,rt))},onAggregateChange:pe=>Ss("B",pe),onRemove:()=>M(null),onActivate:()=>V("B"),allowMedian:g,disabled:ce}),F.inputB&&l.jsx("p",{className:"text-xs text-red-500",children:F.inputB})]}),S==="scale"&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{htmlFor:"constantFactor",children:"Multiplication Factor"}),l.jsx(sn,{id:"constantFactor",type:"number",step:"any",value:Number.isNaN(k)?"":k,onChange:pe=>_(pe.target.value===""?Number.NaN:Number(pe.target.value)),className:F.constant?"border-red-500":"",placeholder:"e.g., 0.15",disabled:ce}),F.constant&&l.jsx("p",{className:"text-xs text-red-500",children:F.constant})]}),l.jsx("div",{className:"rounded-md border border-border bg-muted/40 p-3 text-sm font-mono",children:he||"Select inputs to preview formula"}),F.inputs&&l.jsxs(_N,{variant:"destructive",children:[l.jsx(wc,{className:"h-4 w-4"}),l.jsx(TN,{children:F.inputs})]})]})]}),b==="dimension"&&l.jsxs("div",{className:"space-y-4",children:[l.jsx(g9,{ref:se,value:T,onChange:pe=>{P(pe),we(!1)},onGenerate:()=>q(!0),showGenerate:!!et&&!ce,disabled:ce}),l.jsx(b9,{onValidate:async()=>{we(!0),await Qe()},isValidating:Et,validationResult:Ue,fallbackResult:tt,error:Oe,showFallback:le,disabled:ce}),F.expression&&l.jsx("p",{className:"text-xs text-red-500",children:F.expression}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{children:"Output Type"}),l.jsxs(yt,{value:ft,onValueChange:pe=>R(pe),disabled:ce,children:[l.jsx(gt,{className:"h-9 w-full",children:l.jsx(St,{placeholder:"Select output type"})}),l.jsx(bt,{children:y9.map(pe=>l.jsx(je,{value:pe.value,children:pe.label},pe.value))})]}),ze&&!O&&l.jsxs("p",{className:"text-xs text-muted-foreground",children:["Suggested type: ",ze]})]})]}),Ce&&(Ee||me)&&l.jsxs("div",{className:"space-y-3",children:[l.jsx(zst,{scope:$,onChange:Y,showDashboardScope:Ee,showDomainScope:me,error:F.scope,disabled:ce}),$==="domain"&&l.jsx(Bst,{description:W,tags:A,onDescriptionChange:H,onTagsChange:L,descriptionError:F.description,disabled:ce})]})]})]}),l.jsxs(vs,{children:[l.jsx(re,{variant:"outline",onClick:$t,children:"Cancel"}),l.jsxs(re,{onClick:pt,disabled:ie||ce,children:[r?"Update":"Create"," ",b==="metric"?"Metric":"Dimension"]})]})]})]}),l.jsx(Ust,{open:z,onOpenChange:q,availableFields:ye,fieldType:b,onExpressionGenerated:async pe=>{P(pe),we(!1),Ne()},endpoint:et,dialect:p==null?void 0:p.dialect}),l.jsx(ch,{open:K,onOpenChange:te,children:l.jsxs(Gu,{children:[l.jsxs(Ku,{children:[l.jsx(Xu,{children:"Name Conflict"}),l.jsxs(Qu,{children:['A domain metric named "',y.trim(),'" already exists. Your local version will override it in this'," ",Z==="dashboard"?"dashboard":"card",". Continue?"]})]}),l.jsxs(Zu,{children:[l.jsx(ed,{onClick:()=>{ee(null)},children:"Choose Different Name"}),l.jsx(Ju,{onClick:async()=>{if(Z){te(!1),ue(!0);try{await Dl(Z)}finally{ue(!1),ee(null)}}},children:"Continue"})]})]})})]})}function Toe({domainId:e}){const{authToken:t,tokenProps:n}=Je(),[r,s]=w.useState(!1),[o,i]=w.useState(null),a=w.useMemo(()=>{var m;if(!e)return null;const f=(m=n==null?void 0:n.apiServiceUrl)==null?void 0:m.replace(/\/$/,""),h=`/v1/domains/${e}/calculated-metrics`;return f?`${f}${h}`:h},[e,n==null?void 0:n.apiServiceUrl]),c=w.useMemo(()=>{var m;if(!e)return null;const f=(m=n==null?void 0:n.apiServiceUrl)==null?void 0:m.replace(/\/$/,""),h=`/v1/domains/${e}/calculated-dimensions`;return f?`${f}${h}`:h},[e,n==null?void 0:n.apiServiceUrl]),u=w.useCallback(async f=>{if(!a){const h="Domain promotion is not available";throw i(h),new Error(h)}if(!(t!=null&&t.accessToken)){const h="Missing authentication token";throw i(h),new Error(h)}s(!0),i(null);try{return await ls(a,t.accessToken,f)}catch(h){const m=(h==null?void 0:h.error)||(h==null?void 0:h.message)||"Failed to save to domain";throw i(m),new Error(m)}finally{s(!1)}},[a,t==null?void 0:t.accessToken]),d=w.useCallback(async f=>{if(!c){const h="Domain promotion is not available";throw i(h),new Error(h)}if(!(t!=null&&t.accessToken)){const h="Missing authentication token";throw i(h),new Error(h)}s(!0),i(null);try{return await ls(c,t.accessToken,f)}catch(h){const m=(h==null?void 0:h.error)||(h==null?void 0:h.message)||"Failed to save to domain";throw i(m),new Error(m)}finally{s(!1)}},[c,t==null?void 0:t.accessToken]);return{promoteMetric:u,promoteDimension:d,isPromoting:r,error:o}}const Moe=w.memo(function({context:t="editor",onFieldSelect:n,inlineFilters:r}={}){var Ne,ze,ft,lt;const[s,o]=w.useState(""),[i,a]=w.useState("all"),[c,u]=w.useState(!1),[d,f]=w.useState(null),[h,m]=w.useState("card"),[p,g]=w.useState("metric");Le(fe=>fe.isDevMode);const b=Le(fe=>fe.card.dataSource),x=Le(fe=>fe.card.config),y=Le(fe=>fe.card),v=Le(fe=>fe.frame),S=Le(fe=>fe.actions.updateCardConfig),N=Le(fe=>fe.actions.updateFrame),{userContext:C}=ro(),{autoJoinMetadata:j}=pl(y),{columns:E,rawColumnGroups:M,scopedFields:k,dashboardCalculatedFields:_,cardCalculatedFields:T,isLoading:P,error:O,refetch:R}=KO(),$=(b==null?void 0:b.mode)==="semanticDomain"?b.semanticDomainId:void 0,{data:Y}=ZO($),{promoteMetric:W,promoteDimension:H}=Toe({domainId:$}),A=w.useMemo(()=>[...(x==null?void 0:x.groupByColumns)||[],...(x==null?void 0:x.metricColumns)||[],...(x==null?void 0:x.detailColumns)||[]],[x==null?void 0:x.groupByColumns,x==null?void 0:x.metricColumns,x==null?void 0:x.detailColumns]);(ze=(Ne=x==null?void 0:x.joinPlan)==null?void 0:Ne.baseEntity)==null||ze.name,(lt=(ft=j==null?void 0:j.resolvedJoinPlan)==null?void 0:ft.baseEntity)==null||lt.name,woe();const L=t==="editor",F=(C==null?void 0:C.type)==="organization",I=L?k:E,U=M,V=s.toLowerCase(),G=(x==null?void 0:x.metricColumns)||[],B=(x==null?void 0:x.groupByColumns)||[],z=w.useCallback(async fe=>{await W(fe),R()},[W,R]),q=w.useCallback(async fe=>{await H(fe),R()},[H,R]),Z=fe=>fe.name.toLowerCase().includes(V)||fe.dataType.toLowerCase().includes(V)||fe.label&&fe.label.toLowerCase().includes(V)||fe.qualifiedEntityName&&fe.qualifiedEntityName.toLowerCase().includes(V),ee=fe=>(fe.label||fe.name).toLowerCase().trim(),K=(fe,qe)=>ee(fe).localeCompare(ee(qe),void 0,{numeric:!0,sensitivity:"base"}),te=I.filter(Z).sort(K),ie=fe=>{if(fe.role==="metric"&&Dc(fe)||fe.role==="groupby"&&fe.expression)return"calculated";if(fe.dataType==="number"||fe.dataType==="integer"||fe.dataType==="float"||fe.dataType==="decimal"||fe.dataType==="currency")return"metrics";const qe=Ar(fe.dataType);return["date","string","boolean"].includes(qe)?"dimensions":qe==="number"?"metrics":"dimensions"},ue=fe=>{const qe=fe.filter(Z);return i==="all"?qe:qe.filter(at=>ie(at)===i)},le=i==="all"?te:te.filter(fe=>ie(fe)===i),we=L?[..._,...T]:[],se=L?ue(we).sort(K):[],be=ue(E).sort(K).reduce((fe,qe)=>{const at=qe.qualifiedEntityName||"Other Fields";return fe[at]||(fe[at]={label:ox(qe.entityName),fields:[]}),fe[at].fields.push(qe),fe},{}),Me=w.useMemo(()=>Object.entries(be).map(([fe,qe])=>{const at=U.find($t=>$t.entityName===fe)||{entityName:fe,label:qe.label},Pt=fe===Bm?"Domain Calculated Fields":at.label||at.entityName;return{groupName:fe,groupLabel:Pt,fields:[...qe.fields].sort(K)}}).sort((fe,qe)=>fe.groupLabel.localeCompare(qe.groupLabel,void 0,{numeric:!0,sensitivity:"base"})),[be,U]),Pe=fe=>fe.id||`${fe.entityName}-${fe.qualifiedEntityName}-${fe.name}-${fe.role||"field"}`,ge=w.useMemo(()=>{const fe=new Map;return(L?k:E).forEach(at=>{fe.set(Pe(at),vA(at,{joinabilityMap:(Y==null?void 0:Y.joinabilityMap)||null,selectedFields:A,cardConfig:x,autoJoinMetadata:j}))}),fe},[L,k,E,Y==null?void 0:Y.joinabilityMap,A,x,j]),$e=L?[{key:"scope-calculated",label:"Calculated Fields",fields:se}].filter(fe=>fe.fields.length>0):[],J=[...$e.map(fe=>fe.key),...Me.map(fe=>fe.groupName)],ae=te.filter(fe=>ie(fe)==="dimensions").length,ve=te.filter(fe=>ie(fe)==="metrics").length,Ce=te.filter(fe=>ie(fe)==="calculated").length,Ee=te.length>0&&t!=="inline-filter",me=t==="inline-filter"?"w-full":"w-[290px]";if(P)return l.jsx("div",{className:X("flex h-full flex-col items-center justify-center py-8",me),children:l.jsx(_c,{size:"md",color:"muted","aria-label":"Loading data"})});if(O)return l.jsxs("div",{className:X("flex h-full flex-col items-center justify-center py-8",me),children:[l.jsx(rl,{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:O.message||"Failed to load column data"})]});if(!b||!b.selectedEntities||b.selectedEntities.length===0)return l.jsxs("div",{className:X("flex flex-col items-center justify-center py-8 text-center",me),children:[l.jsx(rl,{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 De=t==="inline-filter"?"px-3 pb-3":"px-6 pb-6",He=t==="inline-filter"?"overflow-hidden":"",et=fe=>fe!=null&&fe.startsWith("card-source-")?fe.replace("card-source-",""):fe,Te=(fe,qe,at)=>{const Pt=et(fe.id),$t=et(qe.id);return Pt&&$t&&Pt===$t?!0:!Pt||!$t||at!=null&&at.allowNameFallback?fe.name===qe.name&&fe.role===qe.role:!1},Ye=(fe,qe,at)=>fe.findIndex(Pt=>Te(Pt,qe,at)),nt=fe=>{if(!v)return fe;const qe=v.calculatedFields||[],at=Ye(qe,fe),Pt=at>=0&&qe[at].id!==fe.id?{...fe,id:qe[at].id}:fe,$t=at>=0?qe.map((Tn,or)=>or===at?Pt:Tn):[...qe,Pt];return N({calculatedFields:$t}),Pt},Re=(fe,qe,at,Pt)=>{var Tn;const $t=Ye(fe,at||qe,Pt);if($t>=0){const or=(Tn=fe[$t])==null?void 0:Tn.id,ss=or&&or!==qe.id?{...qe,id:or}:qe;return fe.map((Fs,Ki)=>Ki===$t?ss:Fs)}return[...fe,qe]},it=fe=>{if(fe.role==="metric")return G.find(qe=>Te(qe,fe));if(fe.role==="groupby")return B.find(qe=>Te(qe,fe))},ye=fe=>{var qe;return(qe=v==null?void 0:v.calculatedFields)==null?void 0:qe.find(at=>Te(at,fe))},tt=fe=>{if(fe.role==="metric"){S(y.id,{metricColumns:G.filter(qe=>!Te(qe,fe,{allowNameFallback:fe.fieldScope==="dashboard"}))});return}fe.role==="groupby"&&S(y.id,{groupByColumns:B.filter(qe=>!Te(qe,fe,{allowNameFallback:fe.fieldScope==="dashboard"}))})},Ue=fe=>{if(!v)return;const qe=(v.calculatedFields||[]).filter(at=>!Te(at,fe));N({calculatedFields:qe})},Qe=fe=>{if(!F)return;if(fe.fieldScope==="domain"){f(fe),m("domain"),g(fe.role==="metric"?"metric":"dimension"),u(!0);return}if(fe.fieldScope==="dashboard"){const at=ye(fe);if(!at)return;f(at),m("dashboard"),g(at.role==="metric"?"metric":"dimension"),u(!0);return}const qe=it(fe);qe&&(f(qe),m("card"),g(qe.role==="metric"?"metric":"dimension"),u(!0))},Et=fe=>{if(F&&fe.fieldScope!=="domain"){if(fe.fieldScope==="dashboard"){Ue(fe),tt(fe);return}tt(fe)}},Oe=fe=>{if(!F)return null;const qe=fe.fieldScope==="domain";return l.jsxs(ah,{children:[l.jsx(lh,{asChild:!0,children:l.jsx(re,{variant:"ghost",size:"icon",className:"h-6 w-6","aria-label":"Calculated field actions",children:l.jsx(nB,{className:"h-4 w-4"})})}),l.jsxs(Yu,{align:"end",className:"w-40",children:[l.jsx(Ro,{onClick:()=>Qe(fe),children:"Edit"}),l.jsx(Ro,{disabled:qe,onClick:()=>Et(fe),children:"Delete"})]})]})};return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:X("mt-2 flex h-full w-full grow flex-col gap-2",De,He),children:[l.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[I.length>0&&l.jsxs("div",{className:"relative",children:[l.jsx(zo,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),l.jsx(Ln,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:s,onChange:fe=>o(fe.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(Vt,{className:"size-3.5"})})]}),Ee&&l.jsx(Os,{defaultValue:"all",value:i,onValueChange:fe=>a(fe),className:"mb-4",children:l.jsxs(ws,{className:"grid h-9 w-full grid-cols-4",children:[l.jsxs(pn,{value:"all",className:"text-xs",children:["All",l.jsx("span",{className:"ml-2 text-xs font-semibold",children:te.length})]}),l.jsxs(pn,{value:"dimensions",className:"text-xs",children:[l.jsx(aC,{className:"size-4 shrink-0"}),l.jsx("span",{className:"ml-2 text-xs font-semibold",children:ae})]}),l.jsxs(pn,{value:"metrics",className:"text-xs",children:[l.jsx(kp,{className:"size-4 shrink-0"}),l.jsx("span",{className:"ml-2 text-xs font-semibold",children:ve})]}),l.jsxs(pn,{value:"calculated",className:"text-xs",children:[l.jsx(TI,{className:"size-4 shrink-0"}),l.jsx("span",{className:"ml-2 text-xs font-semibold",children:Ce})]})]})}),t==="editor"&&i==="calculated"&&F&&l.jsx("div",{className:"flex items-center justify-end gap-2",children:l.jsxs(re,{size:"sm",variant:"outline",className:"w-full",onClick:()=>{f(null),m("card"),g("dimension"),u(!0)},children:[l.jsx(Rr,{className:"mr-2 h-3.5 w-3.5"}),"Add calculated field"]})})]}),l.jsxs(kl,{className:"min-h-0 flex-1",children:[l.jsxs(Hx,{type:"multiple",defaultValue:J,className:"space-y-2",children:[$e.map(fe=>l.jsxs(ku,{value:fe.key,className:"border-none",children:[l.jsx(Eu,{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:fe.label}),l.jsx(st,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:fe.fields.length})]})}),l.jsx(_u,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:fe.fields.map(qe=>{const at=ge.get(Pe(qe)),Pt=t==="editor"&&i==="calculated";return l.jsx(h9,{field:qe,context:t,fieldState:at,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0,actions:Pt?Oe(qe):void 0},qe.id)})})})]},fe.key)),Me.map(({groupName:fe,groupLabel:qe,fields:at})=>l.jsxs(ku,{value:fe,className:"border-none",children:[l.jsx(Eu,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{title:qe,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:qe}),l.jsx(st,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:at.length})]})}),l.jsx(_u,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:at.map(Pt=>{const $t=ge.get(Pe(Pt));return l.jsx(h9,{field:Pt,context:t,fieldState:$t,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0},Pt.id)})})})]},fe))]}),I.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"})]}),I.length>0&&le.length===0&&l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),l.jsx(Li,{orientation:"horizontal"}),l.jsx(Li,{orientation:"vertical"})]})]}),l.jsx(_oe,{open:c,onOpenChange:fe=>{u(fe),fe||(f(null),m("card"))},availableFields:k,existingField:d??void 0,existingFieldScope:h,initialFieldType:p,onSave:fe=>{if(fe.role==="metric"){if(d&&h==="card"){S(y.id,{metricColumns:Re(G,fe,d)});return}S(y.id,{metricColumns:Re(G,fe)});return}if(d&&h==="card"){S(y.id,{groupByColumns:Re(B,fe,d)});return}S(y.id,{groupByColumns:Re(B,fe)})},onSaveToDashboard:fe=>{const qe=!!(d&&h==="dashboard"),at=qe?d:void 0;if(fe.role==="metric"){const $t=nt(fe);S(y.id,{metricColumns:Re(G,$t,at,{allowNameFallback:qe})});return}const Pt=nt(fe);S(y.id,{groupByColumns:Re(B,Pt,at,{allowNameFallback:qe})})},cardId:y.id,onPromoteMetricToDomain:$?z:void 0,onPromoteDimensionToDomain:$?q:void 0,domainId:$})]})}),Ioe=w.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(Moe,{context:t})," "]})});function Doe(){const e=Le(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=vr();w.useEffect(()=>{var m;if(!e)return;const{tableName:i,schemaName:a,databaseName:c,connectionId:u}=XO(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 aot(){Doe();const e=Q(c=>c.selectedSheetId),t=Q(c=>c.selectedFrameId),n=Q(c=>c.dashboard),r=Q(c=>c.actions.getSelectedFrame),{setSelectedFrameId:s}=un(),{setCard:o}=vr(),i=Le(c=>c.card.dataSource);return w.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 lot(){const e=Q(o=>o.dashboard.filterLayout),{setFilterLayout:t}=un(),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(Is,{children:[l.jsx(Ds,{asChild:!0,children:l.jsx(re,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0","aria-label":"Filter display settings",children:l.jsx(hc,{className:"h-4 w-4"})})}),l.jsx(As,{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(Ts,{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(Cn,{value:"canvas",id:"canvas",className:"mt-0.5"}),l.jsxs("div",{className:"grid gap-0.5",children:[l.jsx(de,{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(Cn,{value:"toolbar",id:"toolbar",className:"mt-0.5"}),l.jsxs("div",{className:"grid gap-0.5",children:[l.jsx(de,{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(wn,{id:"wrap",checked:r,onCheckedChange:o=>t({toolbarWrap:o===!0})}),l.jsx(de,{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(wn,{id:"download",checked:s,onCheckedChange:o=>t({showDownloadButton:o===!0})}),l.jsx(de,{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 cot(){const e=Q(n=>n.actions.setShowFilters),{hasEntities:t}=aot();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(de,{className:"px-2 text-base",children:"Dashboard Filters"}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(lot,{}),l.jsx(re,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:l.jsx(Jee,{})})]})]}),!t&&l.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[l.jsx(rl,{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(k0,{collisionDetection:C0,children:l.jsx(E0,{items:[],strategy:rO,children:l.jsx(Ioe,{context:"filter"})})})})]})}function uot(){const e=Q(r=>r.dashboard.filters),t=Q(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?l.jsx("div",{className:X("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>l.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[l.jsx(ZP,{filter:r}),l.jsx(hg,{filter:r})]},r.id))}):null}function dot(){const e=Q(r=>r.showFilters),t=Q(r=>r.isVisualEditing),n=Q(r=>r.isDashboardEditing);return l.jsxs("div",{role:"dashboard-plus-main",className:X("",{"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(uot,{}),l.jsx(moe,{})]}),e&&l.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:l.jsx(cot,{})})]})}const fot=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-CnDq9Uh_.js"))),hot=w.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-D_XPr8f8.js"))),mot=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-stWvjp2O.js"))),pot=w.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-gK3a6OEj.js")).then(e=>({default:e.ResourceManagementPanel})));function got({showControls:e=!1,showFooter:t=!0,...n}){const r=Q(c=>c.isDashboardPanelOpen),s=Q(c=>c.isVisualEditing),o=Q(c=>c.showDashboardJSON),i=Q(c=>c.actions.setIsDashboardPanelOpen),{preferences:a}=n;return l.jsx(Na,{FallbackComponent:BN,children:l.jsxs(_I,{dashboardProps:n,children:[l.jsx(spe,{}),l.jsx(GO,{componentType:"surfboard",componentId:n.id}),l.jsx(YO,{children:l.jsxs(poe,{preferences:a,children:[o&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(mot,{})}),l.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(fot,{})}),l.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(pot,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),l.jsx("div",{className:"flex min-w-0 flex-1",children:l.jsxs(KA,{...n,type:"dashboard",children:[s&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(hot,{})}),l.jsx(dot,{})]})})]})]})]})})]})})}const Aoe=D.forwardRef(({className:e,...t},n)=>l.jsx(T0,{className:X("peer inline-flex h-[22px] w-[36px] shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:n,children:l.jsx(oO,{className:X("pointer-events-none block size-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));Aoe.displayName=T0.displayName;var bot=Object.defineProperty,xot=(e,t,n)=>t in e?bot(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,pw=(e,t,n)=>xot(e,typeof t!="symbol"?t+"":t,n);const yot={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},vot={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}},wot={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function Sot(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function Roe(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const Cot={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=Roe(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},Not={stringify:e=>`${e}`,parse:e=>parseFloat(e)},jot={stringify:e=>e,parse:e=>e},ME={string:jot,number:Not,boolean:yot,function:vot,method:Cot,json:wot},Xg=Symbol.for("r2wc.render"),gw=Symbol.for("r2wc.connected"),Dd=Symbol.for("r2wc.context"),Yo=Symbol.for("r2wc.props");function kot(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=Sot(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(),pw(this,o,!0),pw(this,s),pw(this,r,{}),pw(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[Yo].container=this.container;for(const p of i){const g=d[p],b=this.getAttribute(g),x=c[p],y=x?ME[x]:null;if(x==="method"){const v=Roe(g);Object.defineProperty(this[Yo].container,v,{enumerable:!0,configurable:!0,get(){return this[Yo][v]},set(S){this[Yo][v]=S,this[Xg]()}}),this[Yo][p]=y.parse(b,g,this)}y!=null&&y.parse&&b&&(this[Yo][p]=y.parse(b,g,this))}for(const p of a)this[Yo][p]=g=>{const b=p.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[p]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[gw]=!0,this[Xg]()}disconnectedCallback(){this[gw]=!1,this[Dd]&&n.unmount(this[Dd]),delete this[Dd]}attributeChangedCallback(p,g,b){const x=f[p],y=c[x],v=y?ME[y]:null;x in c&&v!=null&&v.parse&&b&&(this[Yo][x]=v.parse(b,p,this),this[Xg]())}[(o=gw,s=Dd,r=Yo,Xg)](){this[gw]&&(this[Dd]?n.update(this[Dd],this[Yo]):this[Dd]=n.mount(this.container,e,this[Yo]))}}for(const m of i){const p=d[m],g=c[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[Yo][m]},set(b){this[Yo][m]=b;const x=g?ME[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,p,this);this.getAttribute(p)!==y&&this.setAttribute(p,y)}else this[Xg]()}})}return h}function Eot(e,t,n){const r=Iie.createRoot(e),s=w.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function _ot({root:e,ReactComponent:t},n){const r=w.createElement(t,n);e.render(r)}function Tot({root:e}){e.unmount()}function Mot(e,t={}){return kot(e,t,{mount:Eot,update:_ot,unmount:Tot})}const Iot={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",currentTheme:"string",customCards:"json",customStyle:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},Dot=Mot(goe,{props:Iot});function v9(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Aot(e){if(Array.isArray(e))return e}function Rot(e,t,n){return(t=Bot(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Pot(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,s,o,i,a=[],c=!0,u=!1;try{if(o=(n=n.call(e)).next,t!==0)for(;!(c=(r=o.call(n)).done)&&(a.push(r.value),a.length!==t);c=!0);}catch(d){u=!0,s=d}finally{try{if(!c&&n.return!=null&&(i=n.return(),Object(i)!==i))return}finally{if(u)throw s}}return a}}function Oot(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
1099
|
+
`)}})}});var Srt=pnt(()=>Hse(Ui([Sr({type:rn("text-start"),id:kt(),providerMetadata:Br.optional()}),Sr({type:rn("text-delta"),id:kt(),delta:kt(),providerMetadata:Br.optional()}),Sr({type:rn("text-end"),id:kt(),providerMetadata:Br.optional()}),Sr({type:rn("error"),errorText:kt()}),Sr({type:rn("tool-input-start"),toolCallId:kt(),toolName:kt(),providerExecuted:To().optional(),dynamic:To().optional()}),Sr({type:rn("tool-input-delta"),toolCallId:kt(),inputTextDelta:kt()}),Sr({type:rn("tool-input-available"),toolCallId:kt(),toolName:kt(),input:Va(),providerExecuted:To().optional(),providerMetadata:Br.optional(),dynamic:To().optional()}),Sr({type:rn("tool-input-error"),toolCallId:kt(),toolName:kt(),input:Va(),providerExecuted:To().optional(),providerMetadata:Br.optional(),dynamic:To().optional(),errorText:kt()}),Sr({type:rn("tool-output-available"),toolCallId:kt(),output:Va(),providerExecuted:To().optional(),dynamic:To().optional(),preliminary:To().optional()}),Sr({type:rn("tool-output-error"),toolCallId:kt(),errorText:kt(),providerExecuted:To().optional(),dynamic:To().optional()}),Sr({type:rn("reasoning-start"),id:kt(),providerMetadata:Br.optional()}),Sr({type:rn("reasoning-delta"),id:kt(),delta:kt(),providerMetadata:Br.optional()}),Sr({type:rn("reasoning-end"),id:kt(),providerMetadata:Br.optional()}),Sr({type:rn("source-url"),sourceId:kt(),url:kt(),title:kt().optional(),providerMetadata:Br.optional()}),Sr({type:rn("source-document"),sourceId:kt(),mediaType:kt(),title:kt(),filename:kt().optional(),providerMetadata:Br.optional()}),Sr({type:rn("file"),url:kt(),mediaType:kt(),providerMetadata:Br.optional()}),Sr({type:Lse(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:kt().optional(),data:Va(),transient:To().optional()}),Sr({type:rn("start-step")}),Sr({type:rn("finish-step")}),Sr({type:rn("start"),messageId:kt().optional(),messageMetadata:Va().optional()}),Sr({type:rn("finish"),finishReason:Ose(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:Va().optional()}),Sr({type:rn("abort")}),Sr({type:rn("message-metadata"),messageMetadata:Va()})])));function Crt(e){return e.type.startsWith("data-")}function Qse(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]=Qse(o,s):n[r]=s}return n}function Nrt(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 Jse(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await BS({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await BS({text:Nrt(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Hw(e){return e.type.startsWith("tool-")}function jrt(e){return e.type==="dynamic-tool"}function HM(e){return Hw(e)||jrt(e)}function a9(e){return e.type.split("-").slice(1).join("-")}function krt({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 Ert({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(S){const C=u.message.parts.filter(Hw).find(j=>j.toolCallId===S);if(C==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return C}function b(S){const C=u.message.parts.filter(j=>j.type==="dynamic-tool").find(j=>j.toolCallId===S);if(C==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return C}function x(S){var N;const C=u.message.parts.find(M=>Hw(M)&&M.toolCallId===S.toolCallId),j=S,E=C;C!=null?(C.state=S.state,E.input=j.input,E.output=j.output,E.errorText=j.errorText,E.rawInput=j.rawInput,E.preliminary=j.preliminary,E.providerExecuted=(N=j.providerExecuted)!=null?N:C.providerExecuted,j.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:`tool-${S.toolName}`,toolCallId:S.toolCallId,state:S.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(S){var N,C;const j=u.message.parts.find(k=>k.type==="dynamic-tool"&&k.toolCallId===S.toolCallId),E=S,M=j;j!=null?(j.state=S.state,M.toolName=S.toolName,M.input=E.input,M.output=E.output,M.errorText=E.errorText,M.rawInput=(N=E.rawInput)!=null?N:M.rawInput,M.preliminary=E.preliminary,M.providerExecuted=(C=E.providerExecuted)!=null?C:j.providerExecuted,E.providerMetadata!=null&&j.state==="input-available"&&(j.callProviderMetadata=E.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:S.toolName,toolCallId:S.toolCallId,state:S.state,input:E.input,output:E.output,errorText:E.errorText,preliminary:E.preliminary,providerExecuted:E.providerExecuted,...E.providerMetadata!=null?{callProviderMetadata:E.providerMetadata}:{}})}async function v(S){if(S!=null){const N=u.message.metadata!=null?Qse(u.message.metadata,S):S;t!=null&&await n9({value:N,schema:t}),u.message.metadata=N}}switch(a.type){case"text-start":{const S={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=S,u.message.parts.push(S),d();break}case"text-delta":{const S=u.activeTextParts[a.id];S.text+=a.delta,S.providerMetadata=(f=a.providerMetadata)!=null?f:S.providerMetadata,d();break}case"text-end":{const S=u.activeTextParts[a.id];S.state="done",S.providerMetadata=(h=a.providerMetadata)!=null?h:S.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const S={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=S,u.message.parts.push(S),d();break}case"reasoning-delta":{const S=u.activeReasoningParts[a.id];S.text+=a.delta,S.providerMetadata=(m=a.providerMetadata)!=null?m:S.providerMetadata,d();break}case"reasoning-end":{const S=u.activeReasoningParts[a.id];S.providerMetadata=(p=a.providerMetadata)!=null?p:S.providerMetadata,S.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 S=u.message.parts.filter(Hw);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:S.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const S=u.partialToolCalls[a.toolCallId];S.text+=a.inputTextDelta;const{value:N}=await Jse(S.text);S.dynamic?y({toolCallId:a.toolCallId,toolName:S.toolName,state:"input-streaming",input:N}):x({toolCallId:a.toolCallId,toolName:S.toolName,state:"input-streaming",input:N}),d();break}case"tool-input-available":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d();break}case"tool-output-available":{if(a.dynamic){const S=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:S.toolName,state:"output-available",input:S.input,output:a.output,preliminary:a.preliminary})}else{const S=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:a9(S),state:"output-available",input:S.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const S=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:S.toolName,state:"output-error",input:S.input,errorText:a.errorText,providerExecuted:a.providerExecuted})}else{const S=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:a9(S),state:"output-error",input:S.input,rawInput:S.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(Crt(a)){(n==null?void 0:n[a.type])!=null&&await n9({value:a.data,schema:n[a.type]});const S=a;if(S.transient){i==null||i(S);break}const N=S.id!=null?u.message.parts.find(C=>S.type===C.type&&S.id===C.id):void 0;N!=null?N.data=S.data:u.message.parts.push(S),i==null||i(S),d()}}c.enqueue(a)})}}))}async function _rt({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()}}A0({prefix:"aitxt",size:24});A0({prefix:"aiobj",size:24});var Trt=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()})}};A0({prefix:"aiobj",size:24});var Mrt={};frt(Mrt,{object:()=>Drt,text:()=>Irt});var Irt=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),Drt=({schema:e})=>{const t=urt(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await Jse(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 BS({text:n});if(!s.success)throw new o9({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 VO({value:s.value,schema:t});if(!o.success)throw new o9({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 Art(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 Rrt=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 Lh(this.body),c=await Lh(this.headers),u=await Lh(this.credentials),d={...$d(c),...$d(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?$d(f.headers):d,p=(f==null?void 0:f.body)!==void 0?f.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},g=(s=f==null?void 0:f.credentials)!=null?s:u,x=await((o=this.fetch)!=null?o:globalThis.fetch)(h,{method:"POST",headers:e9({"Content-Type":"application/json",...m},`ai-sdk/${i9}`,J8()),body:JSON.stringify(p),credentials:g,signal:e});if(!x.ok)throw new Error((i=await x.text())!=null?i:"Failed to fetch the chat response.");if(!x.body)throw new Error("The response body is empty.");return this.processResponseStream(x.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await Lh(this.body),a=await Lh(this.headers),c=await Lh(this.credentials),u={...$d(a),...$d(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?$d(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:e9(h,`ai-sdk/${i9}`,J8()),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)}},HO=class extends Rrt{constructor(e={}){super(e)}processResponseStream(e){return xnt({stream:e,schema:Srt}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},Prt=class{constructor({generateId:e=lnt,id:t=e(),transport:n=new HO,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:c,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new Trt,this.sendMessage=async(f,h)=>{var m,p,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(m=this.lastMessage)==null?void 0:m.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await Art(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:x=f,f.messageId!=null){const y=this.state.messages.findIndex(v=>v.id===f.messageId);if(y===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[y].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,y+1),this.state.replaceMessage(y,{...x,id:f.messageId,role:(p=x.role)!=null?p:"user",metadata:f.metadata})}else this.state.pushMessage({...x,id:(g=x.id)!=null?g:this.generateId(),role:(b=x.role)!=null?b:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const m=f==null?this.state.messages.length-1:this.state.messages.findIndex(p=>p.id===f);if(m===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[m].role==="assistant"?m:m+1),await this.makeRequest({trigger:"regenerate-message",messageId:f,...h})},this.resumeStream=async(f={})=>{await this.makeRequest({trigger:"resume-stream",...f})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolOutput=async({state:f="output-available",tool:h,toolCallId:m,output:p,errorText:g})=>this.jobExecutor.run(async()=>{var b,x;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(S=>HM(S)&&S.toolCallId===m?{...S,state:f,output:p,errorText:g}:S)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(S=>HM(S)&&S.toolCallId===m?{...S,state:f,output:p,errorText:g}:S)),this.status!=="streaming"&&this.status!=="submitted"&&((b=this.sendAutomaticallyWhen)!=null&&b.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(x=this.lastMessage)==null?void 0:x.id})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=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:krt({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};m.abortController.signal.addEventListener("abort",()=>{d=!0}),this.activeResponse=m;let p;if(e==="resume-stream"){const b=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(b==null){this.setStatus({status:"ready"});return}p=b}else p=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:m.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const g=b=>this.jobExecutor.run(()=>b({state:m.state,write:()=>{var x;this.setStatus({status:"streaming"}),m.state.message.id===((x=this.lastMessage)==null?void 0:x.id)?this.state.replaceMessage(this.state.messages.length-1,m.state.message):this.state.pushMessage(m.state.message)}}));await _rt({stream:Ert({stream:p,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:g,onError:b=>{throw b}}),onError:b=>{throw b}}),this.setStatus({status:"ready"})}catch(m){if(d||m.name==="AbortError")return d=!0,this.setStatus({status:"ready"}),null;h=!0,m instanceof TypeError&&(m.message.toLowerCase().includes("fetch")||m.message.toLowerCase().includes("network"))&&(f=!0),this.onError&&m instanceof Error&&this.onError(m),this.setStatus({status:"error",error:m})}finally{try{(i=this.onFinish)==null||i.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:d,isDisconnect:f,isError:h,finishReason:(o=this.activeResponse)==null?void 0:o.state.finishReason})}catch(m){console.error(m)}this.activeResponse=void 0}(a=this.sendAutomaticallyWhen)!=null&&a.call(this,{messages:this.state.messages})&&!h&&await this.makeRequest({trigger:"submit-message",messageId:(c=this.lastMessage)==null?void 0:c.id,metadata:t,headers:n,body:r})}};function Ort({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(HM).filter(s=>!s.providerExecuted);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function Frt(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 $rt=Frt;const Lrt=Qf($rt);var eoe=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},ar=(e,t,n)=>(eoe(e,t,"read from private field"),n?n.call(e):t.get(e)),$a=(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)},Yc=(e,t,n,r)=>(eoe(e,t,"write to private field"),t.set(e,n),n);function zrt(e,t){return t!=null?Lrt(e,t):e}var bi,Ww,qw,Cb,Nb,jb,qh,WM,qM,Brt=class{constructor(e=[]){$a(this,bi,void 0),$a(this,Ww,"ready"),$a(this,qw,void 0),$a(this,Cb,new Set),$a(this,Nb,new Set),$a(this,jb,new Set),this.pushMessage=t=>{Yc(this,bi,ar(this,bi).concat(t)),ar(this,qh).call(this)},this.popMessage=()=>{Yc(this,bi,ar(this,bi).slice(0,-1)),ar(this,qh).call(this)},this.replaceMessage=(t,n)=>{Yc(this,bi,[...ar(this,bi).slice(0,t),this.snapshot(n),...ar(this,bi).slice(t+1)]),ar(this,qh).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?zrt(t,n):t;return ar(this,Cb).add(r),()=>{ar(this,Cb).delete(r)}},this["~registerStatusCallback"]=t=>(ar(this,Nb).add(t),()=>{ar(this,Nb).delete(t)}),this["~registerErrorCallback"]=t=>(ar(this,jb).add(t),()=>{ar(this,jb).delete(t)}),$a(this,qh,()=>{ar(this,Cb).forEach(t=>t())}),$a(this,WM,()=>{ar(this,Nb).forEach(t=>t())}),$a(this,qM,()=>{ar(this,jb).forEach(t=>t())}),Yc(this,bi,e)}get status(){return ar(this,Ww)}set status(e){Yc(this,Ww,e),ar(this,WM).call(this)}get error(){return ar(this,qw)}set error(e){Yc(this,qw,e),ar(this,qM).call(this)}get messages(){return ar(this,bi)}set messages(e){Yc(this,bi,[...e]),ar(this,qh).call(this)}};bi=new WeakMap;Ww=new WeakMap;qw=new WeakMap;Cb=new WeakMap;Nb=new WeakMap;jb=new WeakMap;qh=new WeakMap;WM=new WeakMap;qM=new WeakMap;var Yh,l9=class extends Prt{constructor({messages:e,...t}){const n=new Brt(e);super({...t,state:n}),$a(this,Yh,void 0),this["~registerMessagesCallback"]=(r,s)=>ar(this,Yh)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>ar(this,Yh)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>ar(this,Yh)["~registerErrorCallback"](r),Yc(this,Yh,n)}};Yh=new WeakMap;function toe({experimental_throttle:e,resume:t=!1,...n}={}){const r=w.useRef("chat"in n?n.chat:new l9(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new l9(n));const o=w.useCallback(d=>r.current["~registerMessagesCallback"](d,e),[e,r.current.id]),i=w.useSyncExternalStore(o,()=>r.current.messages,()=>r.current.messages),a=w.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),c=w.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),u=w.useCallback(d=>{typeof d=="function"&&(d=d(r.current.messages)),r.current.messages=d},[r]);return w.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:i,setMessages:u,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:c,resumeStream:r.current.resumeStream,status:a,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput}}function Vrt(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function Urt(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function Hrt(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function Wrt(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function noe(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:Wrt(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function roe(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 qrt(){var b;const{authToken:e,tokenProps:t}=Je(),n=Q(x=>x.dashboard.aiScopeTables),r=(b=tC().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:c,addToolResult:u,error:d,stop:f,clearError:h}=toe({transport:new HO({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=Ia.getState();return{assistantId:"dashboard-assistant",assistantProfileId:r,aiContext:x.currentAIContext,reasoningEffort:x.reasoningEffort,showReasoning:x.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:x,body:y})=>({body:{...y,messages:WK(x)}})}),onToolCall:m,sendAutomaticallyWhen:Ort,onFinish({isAbort:x,isDisconnect:y,isError:v}){console.log(x?"[Dashboard Assistant] Stream aborted by user":y?"[Dashboard Assistant] Stream disconnected (network error)":v?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully")},onError(x){var y;if(x.name==="AbortError"||(y=x.message)!=null&&y.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)");return}console.error("[Dashboard Assistant] Stream error:",x)}});async function m({toolCall:x}){if(x.toolName==="getCurrentTableScope"&&u({tool:x.toolName,toolCallId:x.toolCallId,output:{tables:noe(n||[])}}),x.toolName==="getDashboardContext"){const y=Q.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const p=!["ready","error"].includes(c),g=roe(d);return{sendMessage:s,regenerate:a,isLoading:p,messages:o,setMessages:i,status:c,stop:f,errorMessage:g,clearError:h}}function soe(){var u;const{authToken:e,tokenProps:t}=Je(),n=(u=tC().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=Jt({queryKey:["assistant-profile",n],queryFn:()=>yr(`${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 ooe({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(J7,{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(re,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function VS(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return l.jsx(YI,{className:r});case"view":return l.jsx(Iu,{className:r});case"materialized view":return l.jsx(oue,{className:r});case"model":return l.jsx(aC,{className:r});case"file":return l.jsx(Fi,{className:r});case"dataset":return l.jsx(rl,{className:r});case"upload":return l.jsx(XI,{className:r});case"url":return l.jsx(oB,{className:r});default:return l.jsx(Ny,{className:r})}}const ioe=D.forwardRef(({className:e,...t},n)=>l.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[l.jsx(zo,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),l.jsx(oo.Input,{ref:n,className:X("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));ioe.displayName=oo.Input.displayName;const hw=e=>e.label||(e==null?void 0:e.name),c9=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function Yrt({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:c,onAddContext:u}){const{tokenProps:d}=Je(),f=(d==null?void 0:d.type)==="dashboard",[h,m]=w.useState(""),[p,g]=w.useState(""),b=s.filter(C=>{if(!h)return!0;const j=hw(C).toLowerCase(),E=c9(C).toLowerCase(),M=h.toLowerCase();return j.includes(M)||E.includes(M)});w.useEffect(()=>{e||(m(""),g(""))},[e]),w.useEffect(()=>{b.length>0&&!p&&g(hw(b[0]))},[b,p]);const x=()=>{if(!p)return;const C=b.find(j=>hw(j)===p);C&&(o.some(E=>"id"in C&&"id"in E?C.id===E.id:C.name===E.name&&C.connectionId===E.connectionId)||t(C),i(C),r())},y=C=>{(C.key==="Tab"||C.key==="Enter")&&(C.preventDefault(),x())};if(!e)return null;const v=C=>o.some(j=>"id"in C&&"id"in j?C.id===j.id:C.name===j.name&&C.connectionId===j.connectionId),S=o.length===s.length,N=o.length>0;return l.jsx(l.Fragment,{children:l.jsxs(Kp,{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(ioe,{placeholder:"Search entities...",value:h,onValueChange:m,className:"flex-1 border-0",autoFocus:!0}),!f&&l.jsxs(re,{onClick:C=>{C.preventDefault(),C.stopPropagation(),u==null||u()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[l.jsx(Rr,{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(re,{onClick:C=>{C.preventDefault(),C.stopPropagation(),a==null||a()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},disabled:S,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),N&&l.jsxs(re,{onClick:C=>{C.preventDefault(),C.stopPropagation(),c==null||c()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[l.jsx(Vt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),l.jsxs(Zp,{className:"min-h-60",children:[l.jsx(Xp,{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(re,{onClick:C=>{C.preventDefault(),C.stopPropagation(),u==null||u()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[l.jsx(Rr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),l.jsx(Qp,{children:b.map((C,j)=>{const E=v(C),M="id"in C?C.id:`${C.connectionId}-${C.name}`,k=hw(C);return l.jsxs(Jp,{value:k,onSelect:()=>{E?n==null||n(C):t(C)},onMouseDown:_=>{_.preventDefault(),_.stopPropagation()},className:X("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:VS(C.type)}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate font-medium",children:k}),l.jsx("div",{className:"truncate text-xs text-muted-foreground",children:c9(C)})]}),E&&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(Hr,{className:"h-3 w-3 text-background"})})]},M)})})]})]})})}const YM=e=>e.name||e.name,Grt=e=>{const t=YM(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 Krt({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r}){const[s,o]=w.useState(!1),i=e.length>0;e.length,t.length,e.length<t.length;const a=e.length>=3?e.slice(0,2):e,c=e.length>=3?e.slice(2):[],u=c.length>0;return l.jsx(nr,{children:l.jsx("div",{className:"space-y-2",children:i&&l.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.map((d,f)=>{const h="id"in d?d.id:`${d.connectionId}-${d.name}`;return l.jsxs(kn,{children:[l.jsx(En,{asChild:!0,children:l.jsxs(st,{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:[VS(d.type,{size:"h-3 w-3"}),l.jsx("span",{className:"max-w-24 truncate text-xs",children:YM(d)}),l.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(d),children:l.jsx(Vt,{className:"h-3 w-3"})})]})}),l.jsx(In,{side:"top",className:"max-w-xs",children:Grt(d)})]},h)}),u&&l.jsxs(kn,{open:s,onOpenChange:o,children:[l.jsx(En,{asChild:!0,children:l.jsxs(st,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>o(!0),children:[l.jsx(nB,{className:"h-3 w-3"}),l.jsxs("span",{className:"text-xs",children:[c.length," more"]}),l.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(c),children:l.jsx(Vt,{className:"h-3 w-3"})})]})}),l.jsx(In,{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:c.map(d=>{const f="id"in d?d.id:`${d.connectionId}-${d.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:VS(d.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:YM(d)}),l.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),l.jsx(re,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(d),c.length===1&&o(!1)},children:l.jsx(Vt,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function aoe(e){return e.type==="dataset"&&e.label||e.name}function Zrt(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 Xrt({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:l.jsxs("div",{className:"mb-4 space-y-2",children:[l.jsxs(de,{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(st,{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,"]"]}),aoe(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(Vt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function Qrt(e){const{tokenProps:t}=Je(),n=Q(c=>c.authToken)||e;Le(c=>c.selectedConnectionId),Le(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}=Jt({queryKey:["semantic-domains"],queryFn:()=>yr(`${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 Jrt(e,t){const{tokenProps:n}=Je(),r=Q(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:c}=Jt({queryKey:["datasets",e],queryFn:()=>yr(`${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 est(e){var g,b;const{tokenProps:t}=Je(),n=Q(x=>x.authToken)||e,{connections:r}=mi(e),s=Le(x=>{var y,v;return(v=(y=x==null?void 0:x.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(x=>x.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,c=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(x){var y;return!s||!x?!1:!!((y=o==null?void 0:o.capabilities)!=null&&y.path.includes("database"))}const{data:d,isPending:f,error:h,refetch:m}=Jt({queryKey:["databases",s],queryFn:()=>yr(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),p=(b=d==null?void 0:d.databases)==null?void 0:b.map(x=>({id:x.database_name,name:x.database_name}));return{isPending:f,error:h,databases:p||[],refetch:m,label:c}}function tst(e){var g;const{tokenProps:t}=Je(),n=Q(b=>b.authToken)||e,{connections:r}=mi(e),s=Le(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=Le(b=>{var x,y,v;return(v=(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(b=>b.id===s),a=i==null?void 0:i.capabilities,c=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){var b;return!(!s||!((b=i==null?void 0:i.capabilities)!=null&&b.path.includes("schema"))||!o)}const{data:d,isPending:f,error:h,refetch:m}=Jt({queryKey:["schemas",s,o],queryFn:()=>yr(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),p=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:p||[],refetch:m,label:c}}function loe(e){const{tokenProps:t}=Je(),n=Q(h=>h.authToken)||e,{connections:r}=mi(e),s=Le(h=>{var m,p;return(p=(m=h==null?void 0:h.card)==null?void 0:m.dataSource)==null?void 0:p.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:c,error:u,refetch:d}=Jt({queryKey:["dataModels",s],queryFn:()=>yr(`${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 nst(){var N,C,j;const e=Le(E=>E.card.dataSource);Le(E=>E.actions.updateDirectSource);const t=Le(E=>E.actions.updateDataSource),[n,r]=w.useState(""),{selectedConnection:s,error:o}=mi(),{databases:i,isPending:a,error:c,label:u}=est(),{schemas:d,isPending:f,error:h,label:m}=tst(),{error:p}=loe(),g=s==null?void 0:s.capabilities.path.includes("schema"),b=s==null?void 0:s.capabilities.path.includes("database"),x=u==null?void 0:u.toLowerCase(),y=m==null?void 0:m.toLowerCase(),v=E=>{e&&t({...e,dbSelection:{database:E,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},S=E=>{var k;if(!((k=e==null?void 0:e.dbSelection)!=null&&k.database))return;const M=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{...M,schema:E},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(re,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),l.jsxs("div",{className:"space-y-4",children:[b&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-sm font-medium",children:u}),l.jsxs(yt,{value:((N=e==null?void 0:e.dbSelection)==null?void 0:N.database)||"",onValueChange:v,disabled:a,children:[l.jsx(gt,{className:"w-full",children:l.jsxs("div",{className:"flex items-center gap-2",children:[a&&l.jsx(jn,{className:"h-4 w-4 animate-spin"}),l.jsx(St,{placeholder:c?`Error loading ${x}`:a?`Loading ${x}...`:`Select ${x}...`})]})}),l.jsx(bt,{children:i.map(E=>l.jsx(je,{className:"hover:bg-muted",value:E.id,children:E.name},E.id))})]})]}),((C=e==null?void 0:e.dbSelection)==null?void 0:C.database)&&g&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-sm font-medium",children:m}),l.jsxs(yt,{value:((j=e==null?void 0:e.dbSelection)==null?void 0:j.schema)||"",onValueChange:S,disabled:f,children:[l.jsx(gt,{className:"w-full",children:l.jsxs("div",{className:"flex items-center gap-2",children:[f&&l.jsx(jn,{className:"h-4 w-4 animate-spin"}),l.jsx(St,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),l.jsx(bt,{children:d.map(E=>l.jsx(je,{className:"hover:bg-muted",value:E.id,children:E.name},E.id))})]})]})]})]})}function rst(){const e=Le(c=>c.card.dataSource),t=Le(c=>c.actions.updateDataSource),[n,r]=w.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(de,{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(XI,{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(re,{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(de,{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(Fi,{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(re,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(c.id),children:l.jsx(Vt,{className:"h-3 w-3"})})]},c.id))})]})]})}function sst(){const e=Le(f=>f.card.dataSource),t=Le(f=>f.actions.updateDataSource),[n,r]=w.useState(""),[s,o]=w.useState(""),[i,a]=w.useState("api"),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(de,{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(de,{className:"text-xs text-gray-600",children:"Source Name"}),l.jsx(sn,{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(de,{className:"text-xs text-gray-600",children:"URL"}),l.jsx(sn,{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(de,{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(re,{onClick:c,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[l.jsx(Rr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs(de,{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(Ny,{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(re,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:l.jsx(Vt,{className:"h-3 w-3"})})]},f.id))})]})]})}function ost(e,t){var y,v;const{tokenProps:n}=Je(),r=Q(S=>S.authToken)||t,{connections:s}=mi(t),o=Le(S=>{var N,C;return(C=(N=S==null?void 0:S.card)==null?void 0:N.dataSource)==null?void 0:C.connectionId}),i=Le(S=>{var N,C,j;return(j=(C=(N=S==null?void 0:S.card)==null?void 0:N.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.database}),a=Le(S=>{var N,C,j;return(j=(C=(N=S==null?void 0:S.card)==null?void 0:N.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.schema}),c=s==null?void 0:s.find(S=>S.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 S=(u==null?void 0:u.path)||[];return!(S.includes("database")&&!i||S.includes("schema")&&!a)}const{data:h,isPending:m,isLoading:p,error:g,refetch:b}=Jt({queryKey:[e,o,i,a],queryFn:()=>yr(`${n.apiServiceUrl}/v1/${e}s`,(r==null?void 0:r.accessToken)||"",{connection_id:o,database_name:i,schema_name:a}),enabled:f()}),x=(v=h==null?void 0:h[`${e}s`])==null?void 0:v.map(S=>{var N;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:(N=S==null?void 0:S.table_type)==null?void 0:N.toLowerCase(),id:S[`${e}_name`],database:i,schema:a,name:S[`${e}_name`]}});return{isPending:m,isLoading:p,error:g,entities:x||[],refetch:b,label:d}}function US({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(wc,{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 ist({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=mi(),[i,a]=w.useState(""),[c,u]=w.useState(""),[d,f]=w.useState("tables"),{updateDataSource:h,setSelectedConnectionId:m}=vr(),{entities:p,isLoading:g,error:b}=ost("table"),{dataModels:x,isPending:y,error:v}=loe(),S=k=>{const _=s.find(P=>P.id===k);if(!_)return;const T=_.type==="upload"?"upload":_.type==="url"?"url":"database";h({...e,connectionId:k,connectionType:_.type,mode:T,dbSelection:{database:"",schema:"",entityType:"table"}}),m(k)},N=k=>{var O,R;const _=n||[],T=_.some($=>$.name===k.name&&$.type===k.type);let P;if(T)P=_.filter($=>!($.name===k.name&&$.type===k.type));else{const $={connectionId:e.connectionId,connectionType:e.connectionType,type:k.type,dbObjectType:k.dbObjectType,database:((O=e.dbSelection)==null?void 0:O.database)||"",schema:((R=e.dbSelection)==null?void 0:R.schema)||"",name:k.name,dialect:k.dialect};P=[..._,$]}t==null||t(P)},C=k=>{const _=n||[],T=_.some(O=>O.type==="model"&&O.name===k.name);let P;T?P=_.filter(O=>!(O.type==="model"&&O.name===k.name)):P=[..._,k],t==null||t(P)},j=p.filter(k=>k.name.toLowerCase().includes(i.toLowerCase())),E=x.filter(k=>k.name.toLowerCase().includes(c.toLowerCase())),M=w.useCallback(()=>{if(!t)return;const k=n||[];let _=[...k];if(d==="tables"){const P=j.filter(O=>!k.some(R=>R.name===O.name&&R.type==="table")).map(O=>{var R,$;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:O.dbObjectType,database:((R=e.dbSelection)==null?void 0:R.database)||"",schema:(($=e.dbSelection)==null?void 0:$.schema)||"",name:O.name,dialect:O.dialect}});_=[...k,...P]}else if(d==="datamodels"){const T=E.filter(P=>!k.some(O=>O.name===P.name&&O.type==="model"));_=[...k,...T]}t(_)},[d,j,E,n,e,t]);return w.useEffect(()=>{r&&r(M)},[r,M]),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"font-medium= text-sm",children:"Connection"}),l.jsxs(yt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:S,disabled:o,children:[l.jsx(gt,{className:"w-full",children:l.jsx(St,{placeholder:o?"Loading connections...":"Select connection..."})}),l.jsx(bt,{children:s.map(k=>l.jsx(je,{className:"hover:bg-muted",value:k.id,children:l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(rl,{className:"h-4 w-4 flex-shrink-0"}),l.jsx("span",{className:"truncate",children:k.name}),l.jsx(st,{variant:"secondary",className:"flex-shrink-0 text-xs",children:k.type})]})},k.id))})]})]}),(e==null?void 0:e.connectionId)&&l.jsxs(l.Fragment,{children:[e.connectionType==="upload"&&l.jsx(rst,{}),e.connectionType==="url"&&l.jsx(sst,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&l.jsxs(l.Fragment,{children:[l.jsx(nst,{}),l.jsx("div",{className:"space-y-4",children:l.jsx("div",{className:"space-y-2",children:l.jsxs(Os,{defaultValue:"tables",value:d,onValueChange:k=>f(k),className:"w-full",children:[l.jsxs(ws,{className:"grid w-full grid-cols-2",children:[l.jsxs(pn,{value:"tables",children:["Tables & Views (",j.length,")"]}),l.jsxs(pn,{value:"datamodels",children:["Data Models (",E.length,")"]})]}),l.jsxs(xr,{value:"tables",className:"space-y-2",children:[l.jsx(Ln,{placeholder:"Search tables and views...",value:i,onChange:k=>a(k.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..."}):b?l.jsx(US,{title:"Error loading tables",message:b.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(k=>{const _=n.some(T=>T.name===k.name&&T.type==="table");return l.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>N(k),children:[l.jsx(wn,{id:`table-${k.name}`,checked:_,onCheckedChange:()=>N(k),onClick:T=>T.stopPropagation(),disabled:g}),l.jsxs(de,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[k.name,k.dbObjectType==="view"&&l.jsx(st,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),k.dbObjectType==="materialized view"&&l.jsx(st,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},k.name)})})]}),l.jsxs(xr,{value:"datamodels",className:"space-y-2",children:[l.jsx(Ln,{placeholder:"Search data models...",value:c,onChange:k=>u(k.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(US,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):E.length===0?l.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):E.map(k=>{const _=n.some(T=>T.name===k.name&&T.type==="model");return l.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>C(k),children:[l.jsx(wn,{id:`dataModel-${k.name}`,checked:_,onCheckedChange:()=>C(k),onClick:T=>T.stopPropagation(),disabled:y}),l.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[l.jsx(de,{className:"cursor-pointer",children:k.name}),l.jsx("span",{className:"text-xs text-muted-foreground",children:k.description})]})]},k.name)})})]})]})})})]})]})]})}function ast({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:s=[],isRestricted:o=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var N;const[c,u]=w.useState(""),d=w.useCallback(C=>{const j={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:C};t({...j})},[e,t]);w.useEffect(()=>{i&&!(e!=null&&e.semanticDomainId)&&d(i)},[i,e==null?void 0:e.semanticDomainId,d]);const{semanticDomains:f,isPending:h,error:m}=Qrt(),p=o?f.filter(C=>s.includes(C.id)):f,{datasets:g,isPending:b,error:x}=Jrt(e==null?void 0:e.semanticDomainId),y=C=>{const j=r||[],E=j.some(k=>k.id===C.id&&k.type==="dataset");let M;if(E)M=j.filter(k=>!(k.id===C.id&&k.type==="dataset"));else{const k={id:C.id,datasetType:C.type,name:C.name||C.table,label:C.label,domainId:C.domainId,description:C.description,database:C.database,schema:C.schema,type:"dataset",connectionId:C.connectionId,connectionType:C.connectionType,dialect:C.dialect,datamodelId:C.datamodelId,sql:C.sql};M=[...j,k]}n==null||n(M)},v=g.filter(C=>C.name.toLowerCase().includes(c.toLowerCase())),S=w.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const C=r||[],E=v.filter(k=>!C.some(_=>_.id===k.id&&_.type==="dataset")).map(k=>({id:k.id,datasetType:k.type,name:k.name||k.table,label:k.label,domainId:k.domainId,description:k.description,database:k.database,schema:k.schema,type:"dataset",connectionId:k.connectionId,connectionType:k.connectionType,dialect:k.dialect,datamodelId:k.datamodelId,sql:k.sql})),M=[...C,...E];n(M)},[v,r,e==null?void 0:e.semanticDomainId,n]);return w.useEffect(()=>{a&&a(S)},[a,S]),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-sm font-medium",children:"Semantic Domain"}),l.jsxs(yt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:d,disabled:h||o&&!!i,children:[l.jsx(gt,{className:"w-full",children:l.jsx(St,{placeholder:h?"Loading semantic domains...":o&&i?"Loading domain...":"Select semantic domain...",children:((N=p.find(C=>C.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:N.label)||"Select semantic domain"})}),l.jsx(bt,{children:p.map(C=>l.jsx(je,{className:"hover:bg-muted",value:C.id,children:l.jsxs("div",{className:"flex flex-col items-start",children:[l.jsx("span",{className:"font-medium",children:C.label}),l.jsx("span",{className:"text-xs",children:C.description})]})},C.id))})]}),m&&l.jsx(US,{title:"Error loading semantic models",message:m.message})]}),(e==null?void 0:e.semanticDomainId)&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(Ln,{placeholder:"Search datasets...",value:c,onChange:C=>u(C.target.value),className:"h-8 text-sm",disabled:b}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:b?l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):x?l.jsx(US,{title:"Error loading datasets",message:x.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):v.length===0?l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:c?"No datasets match your search":"No datasets available"}):v.map(C=>{const j=r.some(E=>E.id===C.id&&E.type==="dataset");return l.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>y(C),children:[l.jsx(wn,{id:`dataset-${C.id}`,checked:j,onCheckedChange:()=>y(C),onClick:E=>E.stopPropagation(),disabled:b}),l.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[l.jsx(de,{className:"cursor-pointer font-medium",children:C.label||C.name}),l.jsx("span",{className:"text-xs text-gray-500",children:C.description})]})]},C.label||C.name)})})]})]})]})}function WO({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s}){const{tokenProps:o}=Je(),{allowedSemanticDomains:i}=o,[a,c]=w.useState([]),{updateDataSource:u}=vr(),d=Q(_=>_.isVisualEditing),f=Q(_=>_.dashboard.aiContext),{setAiContext:h}=un(),m=w.useRef(null),[p,g]=w.useState(!1),b=i&&i.length>0,x=!b,y=b&&i.length===1?i[0]:void 0,v=w.useCallback(_=>{const T=_;u({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:T,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...T!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,u]),S=w.useCallback(_=>{u({...n,..._})},[n,u]);w.useEffect(()=>{b&&n.mode!=="semanticDomain"&&v("semanticDomain")},[b,n.mode,v]),w.useEffect(()=>{y&&!n.semanticDomainId&&S({semanticDomainId:y})},[y,n.semanticDomainId,S]),w.useEffect(()=>{e?c(s||[]):(m.current=null,g(!1))},[e,n==null?void 0:n.selectedEntities,r,u,s,n]);const N=_=>{const T=a.filter(P=>!(P.name===_.name&&P.type===_.type));c(T)},C=()=>{c([])},j=w.useCallback(_=>{c(_)},[]),E=w.useCallback(()=>{m.current&&m.current()},[]),M=w.useCallback(_=>{m.current=_,g(!0)},[]);function k(){var _,T;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const P=(_=a==null?void 0:a[0])==null?void 0:_.connectionId,O=(T=a==null?void 0:a[0])==null?void 0:T.connectionType;u({...n,connectionId:P,connectionType:O,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return l.jsx(qr,{open:e,onOpenChange:t,children:l.jsx(Pr,{className:"flex max-w-2xl flex-col",children:l.jsxs("div",{children:[l.jsxs(Or,{className:"flex-shrink-0",children:[l.jsx(Fr,{children:r==="aiContext"?"Data Context":"Select Data Source"}),l.jsx(Jr,{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:[x&&l.jsx("div",{className:"space-y-2",children:l.jsx(Os,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:v,className:"w-full",children:l.jsxs(ws,{className:"grid w-full grid-cols-2",children:[l.jsx(pn,{value:"database",children:"Direct Source"}),l.jsx(pn,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&l.jsx(ast,{dataSource:n,onDataSourceUpdate:S,selectedEntities:a,onSelectionChange:j,allowedDomainIds:i||[],isRestricted:b,autoSelectedDomainId:y,onRegisterSelectAll:M}),(n==null?void 0:n.mode)==="database"&&x&&l.jsx(ist,{dataSource:n,onDataSourceUpdate:S,selectedEntities:a,onSelectionChange:j,onRegisterSelectAll:M})]})}),l.jsx(Xrt,{selectedEntities:a,onDeselectEntity:N}),l.jsx(vs,{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(re,{variant:"outline",onClick:E,disabled:!p,children:"Select All"}),l.jsx(re,{variant:"outline",onClick:C,disabled:a.length===0,children:"Clear All"}),l.jsxs(re,{variant:"outline",onClick:()=>t(!1),children:[l.jsx(Vt,{className:"mr-2 h-4 w-4"}),"Close"]}),l.jsxs(re,{onClick:k,children:[l.jsx(Hr,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function lst({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=w.useRef(null),o=async a=>{const c=Array.from(a.target.files||[]);if(c.length===0)return;const u=Hl-n;if(c.length>u){We.error(`You can only attach ${Hl} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=Nre(c);if(f.forEach(({file:h,error:m})=>{We.error(`${h.name}: ${m}`)}),d.length>0)try{const h=await Promise.all(d.map(m=>DO(m)));e(h)}catch(h){console.error("Failed to process files:",h),We.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return 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>=Hl}),l.jsx(re,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=Hl,title:n>=Hl?`Maximum ${Hl} files allowed`:"Attach files",children:l.jsx(VI,{className:"h-4 w-4 text-muted-foreground"})})]})}function cst({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=w.useState(!1),a=w.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),c=w.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),m=f.clientX,p=f.clientY;(m<h.left||m>=h.right||p<h.top||p>=h.bottom)&&i(!1)},[]),u=w.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=w.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const m=Hl-r;if(h.length>m){We.error(`You can only attach ${Hl} files per message. You have ${m} slot(s) remaining.`);return}const{valid:p,errors:g}=Nre(h);if(g.forEach(({file:b,error:x})=>{We.error(`${b.name}: ${x}`)}),p.length>0)try{const b=await Promise.all(p.map(x=>DO(x)));t(b),We.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),We.error("Failed to process one or more files")}},[n,r,t]);return l.jsxs("div",{className:X("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(XI,{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:[Hl-r," slot(s) available"]})]})})]})}const qO=w.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:c},u)=>{const[d,f]=w.useState(!1),[h,m]=w.useState(!1),[p,g]=w.useState(!1),b=w.useRef(null),x=tg();cEe(),lEe();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:S,setShowReasoning:N}=hN(),{queueMessage:C}=ng(),{addFileAttachment:j,removeFileAttachment:E,clearFileAttachments:M,getFileAttachments:k}=GA(),_=YA(c),T=Le(z=>z.card.dataSource),P=Q(z=>z.dashboard.aiContext),O=Q(z=>{var q;return(q=z.dashboard.aiContext)==null?void 0:q.selectedEntities});w.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const R=w.useCallback(()=>{const z=b.current;if(z){if(!e||e.length===0){z.style.height="10px";return}z.style.height="auto";const q=Math.min(Math.max(z.scrollHeight,10),200);z.style.height=`${q}px`}},[e]);w.useEffect(()=>{R()},[R]),w.useEffect(()=>{const z=setTimeout(()=>{R()},0);return()=>clearTimeout(z)},[R]);const $=()=>{const z=e.trim();!z&&_.length===0||(a!=="ready"?(C(c,z,_),t(""),M(c)):r({preventDefault:()=>{}}))},Y=z=>{z.key==="Enter"&&!z.shiftKey&&(z.preventDefault(),$()),z.key==="@"&&(B(),f(!0))},W=w.useCallback(z=>{const q=XZe(z.nativeEvent);q.length>0&&(z.preventDefault(),q.forEach(async Z=>{const ee=await DO(Z);j(c,ee)}))},[j,c]),H=w.useCallback(z=>{z.forEach(q=>{j(c,q)})},[j,c]),A=w.useCallback(z=>{z.forEach(q=>{j(c,q)})},[j,c]),L=w.useCallback(z=>{E(c,z)},[E,c]),F=z=>{if(x.selectedEntities.some(Z=>Z.id&&Z.id===z.id||Z.name===z.name)){const Z=x.selectedEntities.filter(ee=>!(ee.id&&ee.id===z.id||ee.name===z.name));y({selectedEntities:Z})}else{const Z=[...x.selectedEntities,z];y({selectedEntities:Z})}},I=z=>{F(z)},U=z=>{var ee;if(!x.selectedEntities.some(K=>K.id&&K.id===z.id||K.name===z.name)){const K=[...x.selectedEntities,z];y({selectedEntities:K})}const Z="label"in z?z.label:z.name;t(e+`@${Z} `),f(!1),(ee=b.current)==null||ee.focus()},V=z=>{const q=x.selectedEntities.filter(K=>!(K.id&&K.id===z.id||K.name===z.name));y({selectedEntities:q});const ee=`@${"label"in z?z.label:z.name}`;e.includes(ee)&&t(e.replace(ee,"").trim())},G=z=>{const q=new Set(z.map(K=>K.id||K.name)),Z=x.selectedEntities.filter(K=>!q.has(K.id||K.name));y({selectedEntities:Z});let ee=e;z.forEach(K=>{const ie=`@${"label"in K?K.label:K.name}`;ee=ee.replace(ie,"").trim()}),t(ee)},B=w.useCallback(()=>{x.selectedEntities.length===0&&y({selectedEntities:(P==null?void 0:P.selectedEntities)||[]})},[x.selectedEntities.length,P==null?void 0:P.selectedEntities,y]);return l.jsxs(cst,{onFilesDropped:H,currentFileCount:_.length,disabled:s,className:"space-y-4",children:[l.jsx(Krt,{entities:x.selectedEntities,availableEntities:O||[],onRemoveEntity:V,onRemoveEntities:G}),_.length>0&&l.jsx(QZe,{files:_,onRemove:L,showRemove:!s,className:"mb-2"}),l.jsxs("div",{className:"rounded-lg border border-border bg-background shadow-sm focus-within:ring-1 focus-within:ring-foreground/40",children:[l.jsx("textarea",{ref:b,value:e,onChange:n,onKeyDown:Y,onPaste:W,onFocus:()=>{R(),i==null||i()},placeholder:"Ask a question...",className:"max-h-[200px] min-h-[40px] w-full resize-none overflow-y-auto border-0 bg-transparent px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),l.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[c==="dashboard"&&l.jsxs(Is,{open:d,onOpenChange:z=>{z&&B(),f(z)},children:[l.jsx(Ds,{asChild:!0,children:l.jsx(re,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:l.jsx(nue,{className:"h-4 w-4 text-muted-foreground"})})}),l.jsx(As,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:z=>z.preventDefault(),children:l.jsx(Yrt,{isOpen:!0,onSelect:F,onDeselect:I,onClose:()=>{var z;f(!1),(z=b.current)==null||z.focus()},availableEntities:O||[],selectedEntities:x.selectedEntities,onTabComplete:U,onSelectAll:()=>{O&&y({selectedEntities:O})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),m(!0)}})})]}),l.jsx(lst,{onFilesSelected:A,disabled:s,currentFileCount:_.length})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[s&&l.jsx(re,{className:"rounded-full",size:"sm",onClick:o,children:l.jsx(pue,{className:"size-3.5 bg-background"})}),!s&&l.jsx(re,{disabled:!e.trim()&&_.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:$,title:a!=="ready"?"Message will be queued":void 0,children:l.jsx(WI,{className:"size-4"})})]})]})]}),l.jsx(WO,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:m,dataSource:T||gj,dialogMode:"aiContext"})]})});qO.displayName="ChatInputWithContext";function coe({assistantType:e,className:t}){const n=qK(e),{removeFromQueue:r}=ng();return n.length===0?null:l.jsxs("div",{className:X("space-y-2",t),children:[l.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[l.jsx(Sc,{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(re,{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(Vt,{className:"h-3 w-3"})})]})},s.id))})]})}function uoe({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=qK(e),{dequeueMessage:o}=ng();w.useEffect(()=>{if(t!=="ready"||n||!(s&&s.length>0))return;const a=o(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,s,o,r,e])}function doe(e,t={}){const{threshold:n=50,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=w.useRef(null),[a,c]=w.useState(!0),[u,d]=w.useState(!0),[f,h]=w.useState(!1),[m,p]=w.useState(0),g=w.useRef(0),b=w.useRef(!1),x=w.useRef(0),y=w.useRef(a),v=w.useRef(void 0),S=w.useRef({key:null,count:0,length:0}),N=w.useCallback(()=>{const M=i.current;return M?M.scrollHeight-M.scrollTop-M.clientHeight:0},[]),C=w.useCallback((M={})=>{if(!i.current)return;const{force:_=!1,instant:T=!1}=M;if(!_&&!y.current||!a&&!_)return;const P=T||r==="auto"||r==="instant"?"auto":r;v.current&&cancelAnimationFrame(v.current),b.current=!0,v.current=requestAnimationFrame(()=>{if(!_&&!y.current){b.current=!1,v.current=void 0;return}const O=i.current;if(!O){b.current=!1,v.current=void 0;return}const R=O.scrollHeight;P==="smooth"&&"scrollTo"in O?O.scrollTo({top:R,behavior:P}):O.scrollTop=R,g.current=O.scrollTop,d(!0),c(!0),y.current=!0,h(!1),p(0),b.current=!1,v.current=void 0})},[r,a]),j=w.useCallback(()=>{const M=i.current;if(!M)return;const k=g.current,_=M.scrollTop,T=_-k;if(g.current=_,T<-1){v.current&&(cancelAnimationFrame(v.current),v.current=void 0),b.current=!1,y.current=!1,c(!1),d(!1);return}if(b.current)return;const P=N()<=n;d(P),c(P),y.current=P,P&&(h(!1),p(0))},[N,n]),E=w.useCallback(()=>{p(0),h(!1)},[]);return w.useEffect(()=>{y.current=a},[a]),w.useEffect(()=>{const M=i.current;if(!M||!e||e.length===0){h(!1),p(0),S.current={key:null,count:0,length:0},g.current=M?M.scrollTop:0,x.current=M?M.scrollHeight:0;return}g.current=M.scrollTop,x.current=M.scrollHeight;const k=S.current,_=e[e.length-1],T=(_==null?void 0:_.id)??(_==null?void 0:_.messageId)??(_==null?void 0:_.createdAt)??(_==null?void 0:_.timestamp)??e.length,P=Array.isArray(_==null?void 0:_.parts)?_.parts.reduce((H,A)=>A?typeof A=="string"?H+A.length:typeof A.text=="string"?H+A.text.length:typeof A.content=="string"?H+A.content.length:typeof A.value=="string"?H+A.value.length:H:H,0):typeof(_==null?void 0:_.content)=="string"?_.content.length:typeof(_==null?void 0:_.text)=="string"?_.text.length:0,O=e.length>k.count,R=T!==k.key,$=P>k.length,Y=s&&(_==null?void 0:_.role)==="assistant"&&!O&&(R||$),W=o||Y;if(S.current={key:T,count:e.length,length:P},a&&(O||R||$||W)){C({force:!1,instant:W});return}if(!a&&O){const H=e.length-k.count;H>0&&(h(!0),p(A=>A+H))}else!a&&$&&(h(!0),p(H=>H>0?H:1))},[e,C,a,s,o]),w.useEffect(()=>{C({instant:!0})},[C]),w.useEffect(()=>{if(typeof ResizeObserver>"u")return;const M=i.current;if(!M)return;x.current=M.scrollHeight;const k=new ResizeObserver(()=>{const _=i.current;if(!_)return;const T=x.current,P=_.scrollHeight;x.current=P,!b.current&&y.current&&P>T&&C({force:!1,instant:!0})});return k.observe(M),()=>{k.disconnect()}},[C]),w.useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:u,hasNewMessages:f,newMessageCount:m,scrollToBottom:C,handleScroll:j,resetNewMessageCount:E}}function foe(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=w.useState(r),a=w.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),c=e.length>o,u=o>=e.length,d=w.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=w.useCallback(()=>{i(r)},[r]);return w.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:c,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}function hoe(e){var n;if(!e||e.length===0)return{hasActiveTools:!1};const t=e[e.length-1];if(!(t!=null&&t.parts))return{hasActiveTools:!1};for(const r of t.parts){if(r.type==="reasoning"&&"state"in r&&r.state==="streaming")return{hasActiveTools:!0,activeToolText:r.text||"Reasoning...",toolType:"reasoning"};if(((n=r.type)!=null&&n.startsWith("tool-")||r.type==="dynamic-tool")&&"state"in r&&["input-streaming","input-available"].includes(r.state)){const s=r,o=s.state;return{hasActiveTools:!0,activeToolText:jre(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const ust=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function dst({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=w.useState(!1),[a,c]=w.useState(aI),[u,d]=w.useState(!1),[f,h]=w.useState(!1),[m,p]=w.useState(!1),g=n??m,{isLocalDev:b,isConsoleMode:x}=Rp(),y=w.useRef(null);Q(Re=>Re.dashboard.aiScopeTables),Q(Re=>Re.isDashboardEditing);const v=Q(Re=>Re.selectedSheetId),{setDataSource:S}=vr(),{addFrame:N,setSelectedFrameId:C,setIsDashboardEditing:j}=un(),E=tg(),{setCurrentAIContext:M,updateSelectedEntities:k,setReasoningEffort:_,setShowReasoning:T}=hN(),{clearQueue:P}=ng(),{clearFileAttachments:O,getFileAttachments:R}=GA(),$=YA("dashboard"),Y=Q(Re=>Re.dashboard.aiContext),W=Le(Re=>Re.card.dataSource),{assistantProfile:H}=soe(),A=Q(Re=>Re.handleOpenAssistantProfile),{sendMessage:L,isLoading:F,messages:I,setMessages:U,status:V,stop:G,errorMessage:B,clearError:z}=qrt(),q=w.useCallback(Re=>{r==null||r(Re),n===void 0&&p(Re)},[n,r]),Z=w.useCallback(()=>{q(!g)},[g,q]);w.useEffect(()=>{if(!g)return;function Re(it){it.key==="Escape"&&q(!1)}return window.addEventListener("keydown",Re),()=>{window.removeEventListener("keydown",Re)}},[g,q]);const[ee,K]=w.useState(""),te=Re=>{K(Re.target.value)};function ie({sql:Re,cardTitle:it,connectionId:ye,cardType:tt,python:Ue,cardConfig:Qe,dataSource:Et,customVisualPreferences:Oe}){if(!v)return;const Ne={id:br(),title:it||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:tt==="horizontalBar"?"y":"x"}},type:tt,sql:Re,python:Ue,dataSource:Et,config:Qe,connectionId:ye,customCardPreferences:Oe?{url:Oe.url,componentName:Oe.componentName,pluginChartType:Oe.pluginChartType,settings:Oe.settings,type:"component"}:void 0},ze={id:br(),cards:[Ne],activeCardId:Ne.id};j(!0),N(v,ze,"end"),C(ze.id)}const ue=Re=>{Re.preventDefault();const it=ee.trim();if(!it&&$.length===0)return;const ye=[];it&&ye.push({type:"text",text:it}),$.forEach(tt=>{tt.data&&ye.push({type:"file",mediaType:tt.type,filename:tt.name,url:`data:${tt.type};base64,${tt.data}`})}),L({role:"user",parts:ye}),K(""),O("dashboard"),J({force:!0})};w.useEffect(()=>{var Re;e&&((Re=y.current)==null||Re.focus())},[e]),uoe({assistantType:"dashboard",status:V,isLoading:F,sendMessage:L});const{hasActiveTools:le}=hoe(I),{visibleMessages:we,hasMoreMessages:se,totalMessageCount:ke,loadMoreMessages:be,resetMessageWindow:Me}=foe(I,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Pe,isAtBottom:ge,hasNewMessages:$e,newMessageCount:ce,scrollToBottom:J,handleScroll:ae,resetNewMessageCount:ve}=doe(we,{threshold:50,behavior:"smooth",isStreaming:F});function Ce(Re){He();const it={role:"user",parts:[{type:"text",text:Re.title+" "+Re.subtitle}]};L(it)}function Ee(Re){He(),L({role:"user",parts:[{type:"text",text:Re}]})}function me(Re){He(),L({role:"user",parts:[{type:"text",text:Re}]}),J({force:!0})}const De=w.useCallback(async()=>{const Re=JSON.stringify(I??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Re),We.success("Conversation copied")}catch(it){console.error("Failed to copy conversation",it),We.error("Unable to copy conversation")}},[I]);function He(){E.selectedEntities.length===0&&M({selectedEntities:(Y==null?void 0:Y.selectedEntities)||[]})}const et=(ee==null?void 0:ee.length)===0&&(I==null?void 0:I.filter(Re=>Re.role==="user").length)===0;function Te(){return l.jsx("div",{"data-role":"header",children:l.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function Ye(){return l.jsxs(ah,{children:[l.jsx(lh,{asChild:!0,children:l.jsx(yu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:l.jsx(Ep,{className:"size-3.5"})})}),l.jsxs(Yu,{align:"end",children:[l.jsx(hm,{children:"Options"}),l.jsx(Rf,{}),l.jsx(Eb,{checked:o,onCheckedChange:i,children:"Token Usage"}),l.jsx(Eb,{checked:a,onCheckedChange:c,children:"Tool Invocations"}),l.jsx(Eb,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const nt=l.jsxs("div",{"data-role":"dashboard-assistant",className:X("flex h-full grow flex-col justify-between break-words px-6 py-4",g&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[l.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Te(),A&&l.jsx(re,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:A,children:(H==null?void 0:H.name)||"Default Profile"}),l.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[x&&Ye(),a&&l.jsx(re,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:De,children:"Copy Conversation"}),l.jsx(yu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:Z,children:g?l.jsx(BI,{className:"size-4"}):l.jsx(lC,{className:"size-4"})}),l.jsx(yu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{U([]),P("dashboard"),z(),Me()},children:l.jsx(uC,{className:"size-4"})}),l.jsx(yu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:l.jsx(Vt,{className:"size-4"})})]})]}),l.jsxs(kl,{"data-role":"dashboard-assistant-scroll-area",ref:Pe,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:ae,children:[l.jsxs("div",{className:"space-y-3 pb-4",children:[se&&l.jsx("div",{className:"flex justify-center py-2",children:l.jsxs(re,{variant:"outline",size:"sm",onClick:be,className:"text-xs",children:["Load ",Math.min(5,ke-we.length)," ","more messages (",ke-we.length," ","hidden)"]})}),l.jsx(Ere,{showTools:a,showSystemMessage:u,messages:we,onAddToDashboard:ie,onQuickReply:me,disableQuickReplies:F}),!le&&l.jsx(kre,{status:V,errorMessage:B})]}),l.jsx(Li,{orientation:"horizontal"})]}),e&&!ge&&l.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:l.jsxs(re,{onClick:()=>{J({force:!0}),ve()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[l.jsx(ur,{className:"h-4 w-4"}),$e&&ce>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:ce>9?"9+":ce})]})}),l.jsxs("div",{className:"space-y-3",children:[!H&&et&&l.jsx(_re,{onClick:Ce,placeholders:ust}),l.jsx("div",{children:et&&H&&l.jsx(ooe,{seedQuestions:H.seedQuestions||[],handleSeedQuestionClick:Ee})}),l.jsx(coe,{assistantType:"dashboard",className:"mb-3"}),l.jsx(qO,{ref:y,setInput:K,stop:G,input:ee,handleInputChange:te,handleSubmit:Re=>{He(),ue(Re),J({force:!0})},isLoading:F,status:V,assistantType:"dashboard",onFocus:()=>{}})]}),l.jsx(WO,{incomingSelectedEntities:(Y==null?void 0:Y.selectedEntities)||[],open:f,onOpenChange:h,dataSource:W||gj,dialogMode:"aiContext"})]});return g&&s?cr.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:nt})}),s):nt}function fst(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=un(),o=Q(d=>d.dashboard.sheets),a=Q(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),c=Q(d=>d.isDashboardEditing),u=Q(d=>d.isVisualEditing);w.useEffect(()=>{if(!c||u)return;async function d(m){const p=m.ctrlKey||m.metaKey;p&&m.key==="c"?(await f(),We.success("Card copied to clipboard"),m.preventDefault()):p&&m.key==="v"&&(await h(),m.preventDefault())}async function f(){try{const m=n();m&&await navigator.clipboard.writeText(JSON.stringify(m))}catch(m){console.error("Failed to copy text:",m)}}async function h(){if(!a)return null;try{const m=await navigator.clipboard.readText();try{const p=JSON.parse(m);if(p!=null&&p.id){const g=XJ(p),b=g.cards.findIndex(x=>x.id===g.activeCardId);b!==-1&&(g.cards[b].title=`${g.cards[b].title} (Copy)`),r(a,g),s(g.id),We.success("Card pasted from clipboard")}}catch(p){console.error("Failed to parse clipboard contents: ",p)}return m}catch(m){return console.error("Failed to paste text:",m),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[r,n,s,a,c,u,t])}function hst(e,t){switch(e.interactionMode){case"drillToDetail":mst(e,t);break;case"drillThrough":pst(e,t);break;case"drillToURL":gst(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 mst(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 pst(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 gst(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 bst({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return l.jsx(qr,{open:e,onOpenChange:t,children:l.jsxs(Pr,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[l.jsxs(Or,{children:[l.jsx(Fr,{children:i||"Insight Detail"}),l.jsx(Jr,{children:a||"View detailed insight data with applied filters"})]}),l.jsx(Wee,{filters:r,filterDefinitions:s,contextMode:o}),l.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?l.jsx(Zee,{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 xst(){const e=Xt(S=>S.interactionStates),t=Xt(S=>S.setInteractionState),n=Xt(S=>S.clearLastInteractionEvent),r=Xt(S=>S.replaceCardWithInsight),s=Xt(S=>S.setPendingDrillThrough),o=Xt(S=>S.pendingDrillThrough),i=Xt(S=>S.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:c}=un(),{selectDashboard:u}=jp(),d=Q(S=>S.dashboard),f=Q(S=>S.filterValues),{data:h,isLoading:m}=_U((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[p,g]=w.useState({open:!1,insightId:""}),b=Xee(p.insightId,{enabled:p.open&&!!p.insightId}),x=w.useRef(new Set),y=w.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:S,filters:N,contextMode:C})=>{g({open:!0,insightId:S,filters:N,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:C})},replaceCardContent:({cardId:S,insightId:N,filters:C,contextMode:j})=>{r(S,N,C,j)},getCurrentFilters:()=>f||[],navigateWithDrill:c,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:S,contextMode:N,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:E})=>{const k={sourceCardId:el,interactionMode:"clickFilter",filterGroups:[{filters:S}]},_={...ki(),appliedClickFilters:[k],contextMode:N,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:E};t(el,_)}}),[a,r,f,c,d,s,t]);w.useEffect(()=>{Object.entries(e).forEach(([S,N])=>{if(N!=null&&N.lastInteractionEvent){const C=N.lastInteractionEvent,j=`${S}-${C.interactionMode}-${C.sourceCardId}-${Date.now()}`;if(x.current.has(j))return;x.current.add(j);try{hst(C,y)}catch(E){console.error("Error executing interaction event:",E)}finally{n(S),setTimeout(()=>{x.current.delete(j)},5e3)}}})},[e,n,y]),w.useEffect(()=>{if(!(!o||!h||m))try{u(h),c(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(S){console.error("[DrillThrough] Error during automatic navigation:",S),i()}},[o,h,m,u,c,i]);const v=()=>{g({open:!1,insightId:""})};return l.jsxs(l.Fragment,{children:[l.jsx(bst,{open:p.open,onOpenChange:v,insightId:p.insightId,filters:p.filters,filterDefinitions:p.filterDefinitions,contextMode:p.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&m&&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-3 rounded-lg border bg-background p-6 shadow-lg",children:[l.jsx(jn,{className:"h-8 w-8 animate-spin text-primary"}),l.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function yst(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=vst(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function vst(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function wst(e){return e?`Back to ${e}`:"Back"}function Sst(){var x,y,v,S,N;const e=Xt(C=>C.interactionStates[el]),t=Q(C=>C.actions.goBackFromDrill),n=Q(C=>C.actions.clearDrillContext),{selectDashboard:r}=jp(),[s,o]=w.useState({x:16,y:16}),[i,a]=w.useState(!1),c=w.useRef({x:0,y:0});w.useEffect(()=>{if(!i)return;const C=E=>{o({x:E.clientX-c.current.x,y:E.clientY-c.current.y})},j=()=>{a(!1)};return document.addEventListener("mousemove",C),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",C),document.removeEventListener("mouseup",j)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((S=(v=(y=(x=e==null?void 0:e.appliedClickFilters)==null?void 0:x[0])==null?void 0:y.filterGroups)==null?void 0:v[0])==null?void 0:S.filters)||[],h=u?{id:u,title:d||"Previous Dashboard",description:"",isPrivate:!1,isPublic:!1,version:"",createdBy:null,createdByTenantUser:"",tenantId:"",projectId:"",createdAt:"",updatedAt:"",lastModified:"",lastModifiedBy:"",createdByUser:null,createdByTenantUserRel:{name:"",email:""},permissions:{canEdit:!0,canShare:!0,canDelete:!0},ownership:{status:"private",isOwner:!0,sharedCount:0,createdBy:{type:"user",userId:"",name:"",email:""}}}:null;if(!e||!((N=e.appliedClickFilters)!=null&&N.length))return null;const m=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(C){console.error("[DrillBack] Error during back navigation:",C)}},p=()=>{n()},g=C=>{C.target.closest("button")||(a(!0),c.current={x:C.clientX-s.x,y:C.clientY-s.y})};yst(f);const b=wst(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((C,j)=>{const E=C.field.label||C.field.name,M=String(C.value);return l.jsxs(st,{variant:"secondary",className:"pointer-events-none text-xs",children:[E," = ",M]},j)})})]}),l.jsx(re,{variant:"ghost",size:"sm",onClick:p,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:l.jsx(Vt,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:l.jsxs(re,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[l.jsx(H7,{className:"mr-2 h-4 w-4"}),b]})})]})})}function moe(){var ke;const{showAssistant:e,tokenProps:t}=Je(),{preferences:n,isConsoleMode:r}=Rp(),s=((ke=n==null?void 0:n.cardDisplay)==null?void 0:ke.mode)==="print",o=w.useRef(null),i=w.useRef(null),[a,c]=w.useState(!1),{handleDragStart:u,isDraggingRef:d,getStyle:f,getPositionClasses:h}=WVe({initialPosition:"bottom-right"}),m=wf(be=>be.setFullscreen),p=wf(be=>be.setPanelOpen),g=wf(be=>be.setContainer),b=VK("dashboard"),x=UK(),y=HK("dashboard"),v=b.isOpen,S=x==="dashboard",N=Q(be=>be.isVisualEditing),C=Q(be=>be.themeStyle),j=Q(be=>{var Me;return(Me=be.dashboard)==null?void 0:Me.sheets}),E=Q(be=>be.showFilters),M=Q(be=>be.isDashboardEditing),k=Q(be=>be.selectedSheetId),_=Q(be=>{var Me,Pe;return((Pe=(Me=be.dashboard)==null?void 0:Me.summary)==null?void 0:Pe.position)||"top"}),T=Q(be=>{var Me;return(Me=be.dashboard)==null?void 0:Me.id}),P=Q(be=>be.isDashboardPanelOpen),O=Q(be=>be.actions.setIsDashboardPanelOpen),{getDefaultSheetId:R,setDefaultSheetId:$,clearDefaultSheetId:Y}=L7(T),[W,H]=w.useState(null);NC(cn.DASHBOARD);const{setSelectedSheetId:A,setSheetTitle:L,addSheet:F,setSheets:I}=un();fst(i);const{setActiveAssistantType:U}=hN();w.useEffect(()=>{if(T){const be=R();H(be)}},[T,R]),w.useEffect(()=>{v?U("dashboard"):x==="dashboard"&&m(null)},[v,U,x,m]),w.useEffect(()=>{var be;v||(be=o.current)==null||be.resize(0)},[v]);function V(be){var Me,Pe;be?((Me=o.current)==null||Me.resize(40),p("dashboard",!0),U("dashboard")):(p("dashboard",!1),m(null),(Pe=o.current)==null||Pe.resize(0),U(null))}function G(){const be={id:br(),title:"New Sheet"};F(be),A(be.id)}function B(be,Me){if(!T)return;W===be?(Y(),H(null),We.success("Default sheet cleared")):($(be),H(be),We.success(`"${Me}" set as default sheet`))}function z(be){var Me;be<1?(p("dashboard",!1),m(null),U(null),(Me=o.current)==null||Me.resize(0)):(v||p("dashboard",!0),U("dashboard"))}function q(){return(C==null?void 0:C.canvasTheme)==="muted"||!(C!=null&&C.canvasTheme)?"hsl(var(--semaphor-muted))":(C==null?void 0:C.canvasTheme)==="clear"?"":C==null?void 0:C.canvasTheme}const Z=(be,Me)=>{be.dataTransfer.setData("tabIndex",Me.toString())},ee=be=>{be.preventDefault()},K=(be,Me)=>{const Pe=be.dataTransfer.getData("tabIndex");if(Pe===Me.toString())return;const ge=Array.from(j||[]),[$e]=ge.splice(parseInt(Pe),1);ge.splice(Me,0,$e),I(ge)},te=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail,ie=e===!0&&!s&&!v&&!N&&!E;function ue(){var be,Me;if(j&&j.length>1||M)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 border-b border-b-muted bg-transparent px-3",children:[r&&te&&!P&&l.jsx(re,{style:{borderRadius:C==null?void 0:C.controlInputRadius},variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{O(!P)},className:"h-8 shrink-0 p-2",children:P?l.jsx(X7,{className:"h-4 w-4"}):l.jsx(Q7,{className:"h-4 w-4"})}),j==null?void 0:j.map((Pe,ge)=>{const $e=k===Pe.id,ce=W===Pe.id;return l.jsxs(pn,{draggable:!0,onDragStart:J=>Z(J,ge),onDragOver:ee,onDrop:J=>K(J,ge),style:{borderRadius:C==null?void 0:C.controlInputRadius},onClick:()=>A(Pe.id),className:"flex shrink-0 items-center gap-1 border px-2 py-1",value:Pe.id,children:[l.jsx(fS,{enabled:M&&$e,text:Pe.title,onSave:J=>L(Pe.id,J),children:Pe.title},Pe.id),!M&&$e&&l.jsx("div",{title:ce?"Clear default sheet":"Set as default sheet",children:l.jsx(qI,{className:X("ml-1 size-3 cursor-pointer transition-all",ce?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:J=>{J.stopPropagation(),B(Pe.id,Pe.title||"Sheet")}})}),M&&$e&&j.length>1&&l.jsx(Vt,{className:"ml-1 size-3",onClick:()=>c(!0)})]},Pe.id)}),M&&l.jsx("div",{style:{borderRadius:(Me=(be=C==null?void 0:C.chart)==null?void 0:be.options)==null?void 0:Me.borderRadius},className:"flex h-7 shrink-0 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:G,children:l.jsx(Rr,{className:"size-3"})})]})}function le(){return l.jsx("div",{ref:i,style:{},className:"grow",children:j==null?void 0:j.map(be=>l.jsx(xr,{style:{backgroundColor:q()},className:X("mt-0",{}),value:be.id,children:l.jsx(pVe,{sheet:be})},be.id))})}function we(){var be;return l.jsxs(Os,{"data-role":"dashboard-tabs-container",className:X("relative flex h-full flex-col",C==null?void 0:C.dashboardTabsContainer),onValueChange:Me=>{A(Me)},value:k||((be=j==null?void 0:j[0])==null?void 0:be.id),children:[ue(),_==="top"&&l.jsx(hM,{}),l.jsx(kl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:le()}),_==="bottom"&&l.jsx(hM,{}),l.jsx(qVe,{open:a,setOpen:c})]})}const se=w.useCallback(be=>{g("dashboard",be)},[g]);return j?l.jsxs(l.Fragment,{children:[l.jsx(xst,{}),l.jsx(Sst,{}),l.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[l.jsxs(lne,{className:X("flex-1 basis-0 overflow-y-auto transition-opacity",S&&"pointer-events-none opacity-0"),direction:"horizontal",children:[l.jsx(SM,{children:we()}),e===!0&&l.jsxs(l.Fragment,{children:[l.jsx(HVe,{open:v,onTabClick:V,withHandle:!0,disabled:!v}),l.jsx(SM,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:z,defaultSize:v?40:0,ref:o,children:l.jsx("div",{className:"grow overflow-y-auto",children:l.jsx(dst,{open:v,setOpen:V,isFullscreen:S,onFullscreenChange:be=>m(be?"dashboard":null),fullscreenContainer:y})})})]})]}),l.jsx("div",{ref:se,className:X("absolute inset-0",!S&&"pointer-events-none")}),ie&&l.jsx("div",{className:X("absolute z-50 transition-all duration-300 ease-in-out",h().horizontal,h().vertical),style:f(),children:l.jsx(re,{size:"sm",variant:"outline",className:"h-12 w-12 cursor-grab rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted active:cursor-grabbing",onClick:()=>{d.current||V(!0)},onMouseDown:u,onTouchStart:u,title:"Open Assistant (drag to move)",children:l.jsx(jy,{className:"h-5 w-5"})})})]})]}):null}function YO({children:e}){return l.jsx(_a,{style:{height:"100%",width:"100%"},children:l.jsx(mce,{defaultTheme:"system",storageKey:"vite-ui-theme",children:l.jsx(nr,{delayDuration:0,children:e})})})}function poe({children:e,preferences:t}){const{currentUser:n}=ro(),r=w.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return l.jsx(oU.Provider,{value:r,children:l.jsx(qP,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function Cst(e=2e3,t=500){const n=Wce(),[r,s]=w.useState(!1),[o,i]=w.useState(!1),a=w.useRef(null);return w.useEffect(()=>{const c=setTimeout(()=>s(!0),e);return()=>clearTimeout(c)},[e]),w.useEffect(()=>{if(r){if(n>0){i(!1),a.current&&(clearTimeout(a.current),a.current=null);return}return a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i(!0)},t),()=>{a.current&&clearTimeout(a.current)}}},[r,n,t]),o}function GO({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=Cst(e,t);return w.useEffect(()=>(s&&(window.__SEMAPHOR_READY__={ready:!0,type:n,componentId:r||null,timestamp:Date.now()}),()=>{window.__SEMAPHOR_READY__={ready:!1,type:n,componentId:r||null,timestamp:Date.now()}}),[s,n,r]),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 goe(e){if(typeof window>"u")return null;const{preferences:t}=e;return l.jsx(Na,{FallbackComponent:BN,children:l.jsxs(_I,{dashboardProps:e,children:[l.jsx(GO,{componentType:"dashboard",componentId:e.id}),l.jsx(YO,{children:l.jsx(poe,{preferences:t,children:l.jsx("main",{className:"flex h-full flex-col",children:l.jsx(KA,{...e,type:"dashboard",children:l.jsx(moe,{})})})})})]})})}function u9(e,t){return e.map(n=>({...n,fieldScope:t}))}function Nst(e){const t=new Map;return e.forEach(n=>{const r=`${n.name}-${n.role||"unknown"}`;t.has(r)||t.set(r,n)}),Array.from(t.values())}function d9(e){if(Dc(e)||Wy(e))return e.expression}function KO(){const{columns:e,columnGroups:t,isLoading:n,hasError:r,error:s,refetch:o}=yA(),i=Le(g=>g.frame.calculatedFields),a=Le(g=>g.card.config),c=w.useMemo(()=>e.filter(g=>g.fieldScope==="domain"),[e]),u=w.useMemo(()=>e.filter(g=>g.fieldScope!=="domain"),[e]),d=w.useMemo(()=>i!=null&&i.length?u9(i,"dashboard"):[],[i]),f=w.useMemo(()=>{const g=new Map;return d.forEach(b=>{const x=`${b.name}-${b.role||"unknown"}`;g.set(x,b)}),g},[d]),h=w.useMemo(()=>{const g=((a==null?void 0:a.metricColumns)||[]).filter(Dc),b=((a==null?void 0:a.groupByColumns)||[]).filter(Wy),y=Nst([...g,...b]).filter(v=>{const S=`${v.name}-${v.role||"unknown"}`,N=f.get(S);if(!N)return!0;const C=d9(v),j=d9(N);return C&&j?C!==j:!0});return u9(y,"card").map(v=>({...v,id:`card-source-${v.id}`}))},[a==null?void 0:a.groupByColumns,a==null?void 0:a.metricColumns,f]),m=w.useMemo(()=>[...c,...d,...h,...u],[h,u,d,c]),p=w.useMemo(()=>t.filter(g=>g.entityId!==l7),[t]);return{columns:e,columnGroups:p,rawColumnGroups:t,columnFields:u,domainCalculatedFields:c,dashboardCalculatedFields:d,cardCalculatedFields:h,scopedFields:m,isLoading:n,hasError:r,error:s,refetch:o}}function ZO(e){const{tokenProps:t,authToken:n}=Je(),r=t==null?void 0:t.apiServiceUrl;return Jt({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return yr(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 boe(e,t,n){if(t==="source")return{isValid:!0};const r=Ar(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 xoe(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 jst(e,t){return(e||[]).map(n=>({...n,id:t(n),label:n.label!==void 0?n.label:n.name}))}const yoe=e=>{var O;const t=(O=e==null?void 0:e.dataSource)==null?void 0:O.semanticDomainId,{data:n}=ZO(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:c,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=vr(),h=Le(R=>R.card.type),m=e==null?void 0:e.id,p=(R,$)=>{if(R.id)return R.id;const Y=R.qualifiedEntityName||R.entityName||$;return`${$}-${Y}-${R.name}`},g=w.useCallback(R=>{if(!(e!=null&&e.config))return[];switch(R){case"groupBy":return(e.config.groupByColumns||[]).map($=>({...$,id:p($,"groupBy"),label:$.label!==void 0?$.label:$.name}));case"metrics":return(e.config.metricColumns||[]).map($=>({...$,id:p($,"metrics"),label:$.label!==void 0?$.label:$.name}));case"pivotBy":return(e.config.pivotByColumns||[]).map($=>({id:p($,"pivotBy"),name:$.name,dataType:$.dataType,label:$.label!==void 0?$.label:$.name,qualifiedEntityName:$.qualifiedEntityName,entityId:$.entityId,entityName:$.entityName,entityType:$.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map($=>({id:p($,"sortBy"),name:$.name,dataType:$.dataType,label:$.label!==void 0?$.label:$.name,qualifiedEntityName:$.qualifiedEntityName,entityId:$.entityId,entityName:$.entityName,entityType:$.entityType,direction:$.direction}));case"detailColumns":return jst(e.config.detailColumns,$=>p($,"detailColumns"));case"source":return[];default:return[]}},[e]),b=w.useCallback((R,$)=>{if(m)switch(R){case"groupBy":{r(m,{groupByColumns:$});break}case"metrics":{r(m,{metricColumns:$});break}case"pivotBy":{r(m,{pivotByColumns:$});break}case"sortBy":{r(m,{sortByColumns:$});break}case"detailColumns":{r(m,{detailColumns:$});break}}},[m,r]),x=w.useCallback((R,$,Y)=>{if(!m)return;const W=g(R),H=W[$];if(H)switch(R){case"groupBy":s(m,H.id,{label:Y});break;case"metrics":o(m,H.id,{label:Y});break;case"pivotBy":i(m,H.id,{label:Y});break;case"sortBy":a(m,H.id,{label:Y});break;case"detailColumns":{const A=W.map((L,F)=>F===$?{...L,label:Y}:L);r(m,{detailColumns:A});break}}},[m,g,s,o,i,a,r]),y=w.useCallback((R,$)=>{if(!m)return;const W=g("metrics")[R];W&&o(m,W.id,{aggregate:$,label:CY(W.name,$)})},[m,g,o]),v=w.useCallback((R,$,Y,W="groupBy")=>{if(!m)return;const H=g(W),A=H[R];if(!A)return;const L={dateFormat:$,customFormat:$==="custom"&&Y?Y:void 0};if(W==="detailColumns"){const F=H.map((I,U)=>U===R?{...I,...L}:I);r(m,{detailColumns:F});return}s(m,A.id,L)},[m,g,r,s]),S=w.useCallback((R,$)=>{if(!m)return;const W=g("groupBy")[R];W&&s(m,W.id,{granularity:$})},[m,g,s]),N=w.useCallback((R,$)=>{if(!m)return;const W=g("metrics")[R];W&&o(m,W.id,{aliasTemplate:$})},[m,g,o]),C=w.useCallback((R,$)=>{if(console.log("handleValueAliasesChange",R,$),!m)return;console.log("handleValueAliasesChange",R,$);const W=g("metrics")[R];W&&(console.log("handleValueAliasesChange",$),o(m,W.id,{valueAliases:$}))},[m,g,o]),j=w.useCallback((R,$)=>{if(!m)return;const W=g("metrics")[R];W&&o(m,W.id,{comparisonType:$,...$!=="target"?{targetValue:void 0}:{}})},[m,g,o]),E=w.useCallback(R=>{m&&r(m,{showTrendline:R})},[m,r]),M=w.useCallback(R=>{m&&r(m,{trendlineWindow:R})},[m,r]),k=w.useCallback(R=>{m&&r(m,{trendlineGranularity:R})},[m,r]),_=w.useCallback((R,$)=>{if(!m)return;const W=g("metrics")[R];W&&o(m,W.id,{targetValue:$})},[m,g,o]),T=w.useCallback(async R=>{var I;if(!m)return;const $=[...g("groupBy"),...g("pivotBy"),...g("metrics"),...g("sortBy"),...g("detailColumns")],Y=R,W=Oje(Y,$,{joinPlan:(I=e==null?void 0:e.config)==null?void 0:I.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!W.isValid){W.showError&&vY();return}const H=Lje(Y,$,h);if(!H){We.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const A=boe(Y,H,h);if(!A.isValid){We.error("Invalid Field Type",{description:A.reason,position:"top-center",duration:3e3});return}const L=g(H);if(wY(Y,L))return;const F=NY(Y,H,L);if(F){const U=[...L,F];b(H,U),H==="metrics"&&xoe(h,e==null?void 0:e.config,r,m,U)}},[m,e==null?void 0:e.config,g,b,t,n,h,r]),P=w.useCallback((R,$)=>{if(!m)return;const W=g(R)[$];if(W){if(R!=="sortBy"){const H=g("sortBy"),A=H.filter(L=>!(L.name===W.name&&L.qualifiedEntityName===W.qualifiedEntityName));A.length!==H.length&&r(m,{sortByColumns:A})}switch(R){case"groupBy":c(m,W.id);break;case"metrics":u(m,W.id);break;case"pivotBy":d(m,W.id);break;case"sortBy":f(m,W.id);break;case"detailColumns":{r(m,{detailColumns:(g("detailColumns")||[]).filter((H,A)=>A!==$)});break}}}},[m,g,c,u,d,f,r]);return{getFieldsForContainer:g,setFieldsForContainer:b,updateLabel:x,handleAggregationChange:y,handleDateFormatChange:v,handleGranularityChange:S,handleAliasTemplateChange:N,handleValueAliasesChange:C,removeField:P,handleFieldClick:T,handleMetricComparisonChange:j,handleKpiShowTrendlineChange:E,handleKpiTrendlineWindowChange:M,handleKpiTrendlineGranularityChange:k,handleMetricTargetValueChange:_,cardType:h}};function wj(e,t){var De,He,et,Te,Ye,nt,Re,it;const{tokenProps:n}=Je(),r=us(),s=Je().authToken||e,o=Le(ye=>ye.selectedConnectionId),i=Le(ye=>ye.card),{queryKey:a}=rbe(i),c=Le(ye=>ye.selectedDatamodelId),u=Le(ye=>ye.isDevMode),d=Le(ye=>ye.selectedDatabaseName),f=Le(ye=>ye.selectedSchemaName),h=Le(ye=>ye.selectedTableName),m=Le(ye=>ye.actions.setSelectedConnectionId),p=Le(ye=>ye.actions.setSelectedDatamodelId),g=Le(ye=>ye.actions.setSelectedDatabaseName),b=Le(ye=>ye.actions.setSelectedSchemaName),x=Le(ye=>ye.actions.setSelectedTableName);Le(ye=>ye.actions.setCardSql);const{setQueryConfig:y}=vr();function v(ye){var Oe;if(!o||!ye)return!1;const tt=((Oe=M==null?void 0:M.capabilities)==null?void 0:Oe.path)||[],Ue=tt.includes("database"),Qe=tt.includes("schema");return!(!tt.includes("table")||Ue&&(!d||d==="NA")||Qe&&!f)}function S(ye){var tt;return!o||!ye?!1:!!((tt=M==null?void 0:M.capabilities)!=null&&tt.path.includes("database"))}const{refetchConnections:N,connectionsData:C,isConnectionsLoading:j,isConnectionsError:E,selectedConnection:M}=mi(e),{refetch:k,data:_,isLoading:T,isError:P}=Jt({queryKey:["models",o],queryFn:()=>yr(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),O=M==null?void 0:M.type,R=((De=M==null?void 0:M.capabilities)==null?void 0:De.path.includes("schema"))??!1,$=((He=M==null?void 0:M.capabilities)==null?void 0:He.path.length)===1&&((et=M==null?void 0:M.capabilities)==null?void 0:et.path[0])==="table",Y=$,{data:W,isLoading:H,isFetching:A,isError:L,refetch:F}=Jt({queryKey:["databases",o],queryFn:()=>yr(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:S(O)}),{data:I,isLoading:U,isFetching:V,isError:G,refetch:B}=Jt({queryKey:["schemas",o,d],queryFn:()=>yr(`${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:q,isFetching:Z,isError:ee,refetch:K}=Jt({queryKey:["tables",o,d,f],queryFn:()=>yr(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(O)}),{columns:te,isColumnsLoading:ie,isColumnsFetching:ue,isColumnsError:le,refetchColumns:we}=jY(e);w.useEffect(()=>{$&&(g(""),b(""),p(""),O==="API"&&x("api"))},[O,x,g,b,p,$]);const se=(M==null?void 0:M.type)==="API"?(Te=M==null?void 0:M.type)==null?void 0:Te.toLowerCase():h||"",ke=R&&f||"";function be(ye){x(ye),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function Me(ye){b(ye),x("")}function Pe(ye){g(ye==="none"?"":ye),b(""),x(""),ye!=="none"&&ye!==""&&p("")}function ge(ye){m(ye)}function $e(ye){p(ye==="none"?"":ye),ye!=="none"&&ye!==""&&g("")}W&&((Ye=W==null?void 0:W.databases)==null?void 0:Ye.length)>0,I&&((nt=I==null?void 0:I.schemas)==null?void 0:nt.length)>0;const ce=C==null?void 0:C.connections.map(ye=>({id:ye.id,name:ye.name,type:ye.type})),J=(Re=_==null?void 0:_.datamodels)==null?void 0:Re.map(ye=>({id:ye.id,name:ye.name})),ae=W==null?void 0:W.databases.map(ye=>({id:ye.database_name,name:ye.database_name})),ve=I==null?void 0:I.schemas.map(ye=>({id:ye.schema_name,name:ye.schema_name})),Ce=z==null?void 0:z.tables.map(ye=>({id:ye.table_name,name:ye.table_name})),Ee=(it=_==null?void 0:_.datamodels.find(ye=>ye.id===c))==null?void 0:it.name,me=M!=null&&M.capabilities?Qw({schemaName:ke,tableName:se,modelName:Ee,databaseName:d||"",capabilities:M.capabilities}):se;return{connectionItems:ce,selectedConnectionId:o,selectedConnection:M,isConnectionsLoading:j,isConnectionsError:E,modelItems:J,selectedDatamodelId:c,selectedDatamodelName:Ee,isModelsLoading:T,isModelsError:P,selectedDatabaseName:d,databaseItems:ae,isDatabasesLoadingOrFetching:H||A,isDatabaseError:L,schemaItems:ve,selectedSchemaName:f,isSchemaLoadingOrFetching:U||V,isSchemaError:G,tableItems:Ce,selectedTableName:h,isTableLoadingOrFetching:q||Z,isTableError:ee,columns:te,isColumnsLoadingOrFetching:ie||ue,isColumnsError:le,isNonDbConnection:Y,connectionType:O,tableName:se,formattedTableName:me,schemaName:ke,refetchConnections:N,refetchModels:k,refetchDatabases:F,refetchSchemas:B,refetchTables:K,refetchColumns:we,handleConnectionChange:ge,handleDatamodelChange:$e,handleDatabaseChange:Pe,handleSchemaChange:Me,handleTableChange:be}}function mw(e){return`${e}-${br()}`}function f9(e,t){const n=li(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 kst(e,t){const n=li(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function XO(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 voe(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function woe(){const e=Le(j=>j.sqlGen),t=Le(j=>j.isDevMode),n=Le(j=>j.card.dataSource),r=Le(j=>{var E,M;return(M=(E=j.card)==null?void 0:E.queryConfig)==null?void 0:M.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=XO(n),a=voe(n),c=Le(j=>j.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:m,setIsShowingVisual:p}=vr(),{modelItems:g,selectedDatamodelName:b}=wj(),{selectedConnection:x}=mi(),y=x==null?void 0:x.capabilities,v=j=>({column_name:j.name,data_type:j.dataType,label:j.label,description:j.description});return{handleDevModeFieldClick:j=>{var M;if(!t)return;const E=v(j);if(t&&a&&s&&y){const k=hI(E,e);m(k);const _=(M=g==null?void 0:g.find(P=>P.id===c))==null?void 0:M.name,T=fI(k,o||"",s,_||"",i||"",y,j.qualifiedEntityName);T&&(f(T),h(!0))}else if(!t){if(vy(E.data_type))if(r&&r.length>0){const k={...E,role:"groupby",id:mw(E.column_name),name:E.column_name,type:E.data_type};d(k)}else{const k={...E,role:"metric",id:mw(E.column_name),name:E.column_name,label:f9(E.column_name,"COUNT"),type:E.data_type,aggregate:"COUNT"};u(k)}if(ya(E.data_type)){const k={...E,role:"groupby",id:mw(E.column_name),name:E.column_name,type:E.data_type,label:kst(E.column_name,"month"),granularity:"month"};d(k)}if(xa(E.data_type)){const k={...E,role:"metric",id:mw(E.column_name),name:E.column_name,label:f9(E.column_name,"SUM"),type:E.data_type,aggregate:"SUM"};u(k)}}},handleShowSample:()=>{if(!a||!s||!y){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const j=Qw({schemaName:o||"",tableName:s,modelName:b,databaseName:i||"",capabilities:y});p(!1);const M=(x==null?void 0:x.type)==="MSSQL"?`SELECT top 10 * FROM ${j}`:`SELECT * FROM ${j} LIMIT 10`;f(M),h(!0)},handleShowCount:()=>{if(!a||!s||!y){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const j=Qw({schemaName:o||"",tableName:s,modelName:b,databaseName:i||"",capabilities:y});f(`SELECT COUNT(*) as count FROM ${j}`),h(!0)},isNumberField:j=>xa(j.dataType)}}function Est(e){const t=e.qualifiedFieldName,r=(e.qualifiedEntityName||e.qualifiedFieldName.split(".").slice(0,-1).join(".")).split(".").map(o=>rx(o)).join("."),s=rx(e.name);return{qualifiedColumnName:t,qualifiedTableName:r,formattedColumnName:s}}function Soe(e){const t=e;return{name:e.name,qualifiedFieldName:e.qualifiedFieldName,qualifiedEntityName:e.qualifiedEntityName,entityName:e.entityName,entityId:e.entityId,entityType:e.entityType,dataType:e.dataType,role:e.role,expression:t.expression,calculatedFormula:t.calculatedFormula}}function Coe(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 Noe(e){var t,n;return e?!!(e.entityName===Ec||e.expression||(n=(t=e.calculatedFormula)==null?void 0:t.inputFields)!=null&&n.length):!1}function joe(){const e=Q(c=>c.dashboard.filters)||[],t=Q(c=>c.selectedSheetId),n=Q(c=>c.actions.addFilter),r=Q(c=>c.actions.removeFilter),{removeFilterValues:s}=un(),o=Le(c=>c.card.dataSource),{selectedConnection:i}=mi();function a(c,u="sheet"){const{qualifiedColumnName:d,qualifiedTableName:f,formattedColumnName:h}=Est(c);let m;if(u==="sheet"&&t?m=sMe(e,d,f,t):m=e==null?void 0:e.find(p=>cp(p.column)===cp(d)),m)s(m.id),r(m.id);else{const p=br(),g=Soe(c),b=Coe(o,{connectionId:i==null?void 0:i.id,connectionType:i==null?void 0:i.type}),x=Noe(g),y=u==="sheet"&&t?[t]:void 0;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:"in",applyToSheetIds:y,sql:x?"":qQ(c.dataType,f,h),fieldMeta:g,semanticContext:b}),p}}return{assignFilter:a}}function _st({column:e}){const[t,n]=w.useState(!1),r=Le(y=>y.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=XO(r),a=Le(y=>y.selectedDatamodelId),c=Le(y=>y.sqlGen),{modelItems:u,selectedConnection:d}=wj(),f=d==null?void 0:d.capabilities,h=Le(y=>y.actions.setSqlGen),m=Le(y=>y.actions.setCardSql),p=Le(y=>y.actions.setRunSql),g=voe(r);function b(y,v){var E,M;if(!g||!s){console.warn("Cannot generate SQL: missing table metadata");return}const S=hI(y,c,v),N=(E=u==null?void 0:u.find(k=>k.id===a))==null?void 0:E.name;if(h(S),!f){console.warn("Cannot generate SQL: missing connection capabilities");return}const C=(M=y.qualifiedFieldName)==null?void 0:M.split(".").slice(0,-1).join("."),j=fI(S,o||"",s,N||"",i||"",f,C);j&&(m(j),p(!0)),n(!1)}function x(){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 g?l.jsxs(Pp,{openDelay:0,open:t,onOpenChange:n,children:[l.jsx(Op,{asChild:!0,children:l.jsx(Ep,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),l.jsx(Fp,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:x()})]}):null}function Tst({field:e,fieldState:t}){return l.jsxs("div",{className:"w-64 bg-background p-0",children:[l.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[l.jsx("h3",{className:"text-sm font-medium text-foreground",children:e.label||e.name}),l.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:e.dataType})]}),e.description&&l.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:e.description}),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 pb-2 pt-2",children:l.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:e.name})})]})}function h9({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s,actions:o}){const i=Le(K=>K.isDevMode),a=t==="filter"||t==="inline-filter",c=i||a||(n==null?void 0:n.state)==="unreachable"&&!a,u=Q(K=>K.dashboard.filters),d=Q(K=>K.selectedSheetId),f=Q(K=>K.actions.removeFilter),{removeFilterValues:h}=un(),{assignFilter:m}=joe(),p=t==="filter"?Ac(u,d):u,g=t==="filter"?p==null?void 0:p.find(K=>{if(K.title===e.name)return!0;const te=cp(K.column||""),ie=cp(e.name);return te.endsWith(`.${ie}`)||te===ie}):void 0,b=!!g,x=t==="inline-filter"&&(s==null?void 0:s.some(K=>K.column===e.qualifiedFieldName||K.column===e.name)),y=b||x,v=g&&a?u==null?void 0:u.find(K=>K.id===g.id):void 0,S=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:S,selectedSheetId:d});const[N,C]=w.useState(!1),[j,E]=w.useState(null),{attributes:M,listeners:k,setNodeRef:_,transform:T,transition:P,isDragging:O}=_0({id:e.id,disabled:c}),[R,$]=w.useState(!1),Y=Le(K=>K.card),{handleFieldClick:W}=yoe(Y),{handleDevModeFieldClick:H,isNumberField:A}=woe(),L=()=>{v&&(console.log("[SourceField] Removing multi-sheet filter:",v.id),h(v.id),f(v.id)),E(null),C(!1)},F=()=>{if(t==="inline-filter"&&r){r(e);return}t==="filter"?y&&S?(E(e),C(!0)):m(e,"sheet"):i?H(e):W(e)},I={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},U={transform:Vi.Transform.toString(T),transition:P},V=()=>{if(!n||a)return{};const te={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[n.state]||{};return n.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",...te},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...te},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...te}}[n.state]||te};function G(K){return K==="domain"?{label:"Domain",Icon:Ny,className:"border-border bg-muted text-foreground"}:K==="dashboard"?{label:"Dashboard",Icon:$I,className:"border-border bg-muted/70 text-foreground"}:{label:"Card",Icon:uB,className:"border-border bg-muted/40 text-foreground"}}const B=V(),z=e.fieldScope,q=z?G(z):null,Z=L1(e),ee=Z&&Dc(e);return l.jsxs("div",{ref:_,style:U,...c?{}:M,...c?{}:k,className:X("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",O&&"scale-95 opacity-50",!O&&"border",B.borderColor||"border-transparent",B.bgColor||"",B.hoverBorderColor,B.hoverBgColor||"hover:bg-muted",B.opacity,B.cursor,b&&"border-accent-foreground/20 bg-accent",x&&"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:F,children:[l.jsxs("div",{className:"relative shrink-0",children:[bp(e.dataType),Z&&l.jsx("span",{className:X("absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 text-[7px] font-semibold uppercase italic leading-none shadow-sm",ee?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),l.jsx(nr,{children:l.jsxs(kn,{children:[l.jsx(En,{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(In,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:l.jsx(Tst,{field:e,fieldState:n})})]})}),t==="editor"&&q&&l.jsx("span",{title:q.label,className:X("shrink-0 rounded-full border p-1",q.className),children:l.jsx(q.Icon,{className:"h-3.5 w-3.5"})}),i&&!a&&A(e)&&l.jsx("div",{onClick:K=>K.stopPropagation(),children:l.jsx(_st,{column:I})}),o&&l.jsx("div",{className:"ml-auto flex items-center",onClick:K=>K.stopPropagation(),onPointerDown:K=>K.stopPropagation(),children:o})]}),R&&l.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:l.jsx(Lo,{className:"",children:l.jsxs(Oi,{className:"space-y-2 p-3",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(dB,{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(wue,{className:"h-4 w-4 text-muted-foreground"}),l.jsx("span",{className:"break-all",children:e.name})]}),l.jsx(st,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),l.jsx(ch,{open:N,onOpenChange:C,children:l.jsxs(Gu,{children:[l.jsxs(Ku,{children:[l.jsx(Xu,{children:"Remove Filter from Multiple Sheets?"}),l.jsx(Qu,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),l.jsxs(Zu,{children:[l.jsx(ed,{children:"Cancel"}),l.jsx(Ju,{onClick:L,children:"Remove Filter"})]})]})})]})}let koe=(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 iy=[{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}],zl=e=>e.trim().toLowerCase().replace(/\s+/g,"_"),Jl=e=>e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e;function m9(e,t,n,r,s,o,i,a,c,u){const d=iy.find(x=>x.id===t);if(!d)throw new Error(`Unknown operation: ${t}`);let f,h=[],m;if(t==="custom"){if(!(a!=null&&a.trim()))throw new Error("Custom expression is required");f=a.trim(),h=u||[]}else if(t==="scale"){if(!n)throw new Error("Metric A is required for scale operation");if(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]}const p={operation:t,inputFields:h,...m!==void 0&&{constant:m}},g=zl(e);return{id:i||`calc_${koe(10)}`,name:g,label:e,alias:g,qualifiedFieldName:g,dataType:"number",role:"metric",aggregate:"SUM",expression:f,calculatedFormula:p,entityId:o,entityName:Ec,entityType:"table",description:`Calculated field: ${e}`}}function Mst(e){var r,s;const t=iy.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 Ist(e,t,n,r,s,o){const i=zl(e);return{id:o||`calc_dim_${koe(10)}`,name:i,label:e.trim(),alias:i,qualifiedFieldName:i,dataType:r,role:"groupby",expression:t.trim(),calculatedFormula:{operation:"custom",inputFields:n.map(a=>a.role==="metric"?{...a,role:"metric"}:{...a,role:"groupby"})},entityId:s,entityName:Ec,entityType:"table",description:`Calculated field: ${e.trim()}`}}function Dst(){const{domainCalculatedFields:e}=KO(),t=w.useMemo(()=>e.filter(r=>r.role==="metric"),[e]),n=w.useMemo(()=>e.filter(r=>r.role==="groupby"),[e]);return{fields:e,metrics:t,dimensions:n}}function Ast({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(Os,{value:a,onValueChange:c=>t(c),className:"w-full",children:l.jsx(ws,{className:"grid h-9 w-full",style:{gridTemplateColumns:`repeat(${o.length}, minmax(0, 1fr))`},children:o.map(c=>l.jsx(pn,{value:c,disabled:i,className:"text-xs",children:c==="metric"?"Calculated Metric":"Calculated Dimension"},c))})})}function Rst({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 b of g){const x=u(p,b);if(x!==p)return x}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(zo,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),l.jsx(Ln,{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(Vt,{className:"size-3.5"})})]}),l.jsx(kl,{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(Hx,{type:"multiple",defaultValue:c,className:"space-y-2",children:e.map(f=>l.jsxs(ku,{value:f.id,className:"border-none",children:[l.jsx(Eu,{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(st,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:f.fields.length})]})}),l.jsx(_u,{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",b=d(h,f.label);return l.jsxs("button",{type:"button",onClick:()=>h.isCompatible&&!o&&r(h),className:X("group/container flex w-full items-center gap-3 rounded-lg border border-transparent px-2 py-2 text-left transition-all",p?"cursor-not-allowed opacity-50":"hover:bg-muted",m&&"border-border bg-muted"),disabled:p,children:[l.jsxs("div",{className:"relative shrink-0",children:[bp(h.dataType),h.isCalculated&&l.jsx("span",{className:X("absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 text-[7px] font-semibold uppercase italic leading-none shadow-sm",g?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),l.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:l.jsx("span",{className:X("block truncate text-sm text-foreground/80",!p&&"group-hover/container:text-foreground"),children:b})}),m&&l.jsx(st,{variant:"secondary",className:"shrink-0 text-[10px]",children:"Selected"})]},h.id)})})})]},f.id))})})]})}function Pst({value:e,onChange:t,allowCustom:n,disabled:r}){const s=iy.filter(c=>n?!0:c.id!=="custom"),i=!s.some(c=>c.id==="custom")&&e==="custom"?[...s,iy.find(c=>c.id==="custom")]:s,a=i.find(c=>c.id===e);return l.jsxs("div",{className:"space-y-2",children:[l.jsxs(yt,{value:e,onValueChange:c=>t(c),disabled:r,children:[l.jsx(gt,{children:l.jsx(St,{})}),l.jsx(bt,{children:l.jsxs(BA,{children:[l.jsx(cN,{children:"OPERATIONS"}),i.map(c=>l.jsx(je,{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 Ost={COUNT:"Count",DISTINCT:"Count Distinct",SUM:"Sum",AVG:"Average",MIN:"Minimum",MAX:"Maximum",MEDIAN:"Median"};function Fst({value:e,onChange:t,disabled:n,fieldDataType:r,allowMedian:s}){const i=(r?Ar(r):"number")==="number",a=["SUM","AVG","COUNT","DISTINCT","MIN","MAX"],c=i?s?[...a,"MEDIAN"]:a:["COUNT","DISTINCT"];return l.jsxs(yt,{value:e,onValueChange:u=>t(u),disabled:n,children:[l.jsx(gt,{className:"h-9",children:l.jsx(St,{})}),l.jsx(bt,{children:c.map(u=>l.jsx(je,{value:u,children:Ost[u]},u))})]})}const $st=e=>{const n=(e.name||e.baseLabel||e.label||e.tokenLabel||"").trim();return n.includes(".")&&n.split(".").pop()||n};function p9({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:X("flex items-center gap-2 rounded-md border border-border px-2 py-2",a&&!u&&"cursor-pointer",u&&"opacity-60"),onClick:u?void 0:a,children:[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(yt,{value:d,onValueChange:h=>{const m=f.find(p=>p.id===h);m&&s(m)},disabled:u,children:[l.jsx(gt,{className:"h-9 flex-1",children:l.jsx(St,{placeholder:"Select field"})}),l.jsx(bt,{children:f.map(h=>l.jsx(je,{value:h.id,children:$st(h)},h.id))})]}),l.jsx("div",{className:"w-36",children:l.jsx(Fst,{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(re,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:h=>{h.stopPropagation(),i()},disabled:u,children:l.jsx(Vt,{className:"h-3.5 w-3.5"})})]})}const g9=w.forwardRef(function({value:t,onChange:n,onGenerate:r,showGenerate:s,disabled:o},i){return l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("span",{className:"text-sm font-medium",children:"Expression"}),s&&l.jsxs(re,{type:"button",size:"sm",variant:"outline",onClick:r,disabled:o,className:"h-7 gap-2 text-xs",children:[l.jsx(jy,{className:"h-3.5 w-3.5"}),"Generate with AI"]})]}),l.jsx(pp,{ref:i,value:t,onChange:a=>n(a.target.value),disabled:o,placeholder:"CASE WHEN {Amount} > 100 THEN 'Large' ELSE 'Small' END",className:"min-h-[140px] font-mono text-xs"})]})});function Lst({result:e}){const t=e.errors.length>0;return l.jsxs("div",{className:X("rounded-md border px-3 py-2 text-xs",t?"border-destructive/40 bg-destructive/10 text-destructive":"border-emerald-500/30 bg-emerald-500/10 text-emerald-700"),children:[l.jsx("div",{className:"font-medium",children:t?"Validation Failed":"Validation Passed"}),e.tokens.length>0&&l.jsxs("div",{className:"mt-2 space-y-1",children:[l.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Tokens Found"}),e.tokens.map(n=>l.jsx("div",{children:n.field?`{${n.token}} -> ${n.field.qualifiedFieldName||n.field.name}`:`{${n.token}}`},n.token))]}),e.errors.length>0&&l.jsxs("div",{className:"mt-2 space-y-1",children:[l.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Errors"}),e.errors.map((n,r)=>l.jsxs("div",{children:[n.message,n.suggestion?` (${n.suggestion})`:""]},`${n.code}-${r}`))]}),e.warnings.length>0&&l.jsxs("div",{className:"mt-2 space-y-1",children:[l.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Warnings"}),e.warnings.map((n,r)=>l.jsxs("div",{children:[n.message," ",n.suggestion]},`${n.code}-${r}`))]}),e.inferredDataType&&l.jsxs("div",{className:"mt-2 text-[11px] text-muted-foreground",children:["Inferred Output Type: ",e.inferredDataType]})]})}function b9({onValidate:e,isValidating:t,validationResult:n,fallbackResult:r,error:s,showFallback:o,disabled:i}){return l.jsxs("div",{className:"space-y-2",children:[l.jsx(re,{type:"button",variant:"outline",onClick:e,disabled:t||i,className:"h-8",children:t?"Validating...":"Validate Expression"}),s&&l.jsx("div",{className:"text-xs text-destructive",children:s}),(n||o)&&l.jsx(Lst,{result:n||r})]})}function zst({scope:e,onChange:t,showDashboardScope:n,showDomainScope:r,error:s,disabled:o}){return l.jsxs("div",{className:"space-y-3 border-t border-border pt-4",children:[l.jsx(de,{children:"Availability"}),l.jsxs(Ts,{value:e,onValueChange:i=>t(i),className:"space-y-2",disabled:o,children:[l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx(Cn,{id:"scope-card",value:"card"}),l.jsx(de,{htmlFor:"scope-card",className:"text-sm font-normal",children:"This card only"})]}),n&&l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx(Cn,{id:"scope-dashboard",value:"dashboard"}),l.jsx(de,{htmlFor:"scope-dashboard",className:"text-sm font-normal",children:"All cards in this dashboard"})]}),r&&l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx(Cn,{id:"scope-domain",value:"domain"}),l.jsx(de,{htmlFor:"scope-domain",className:"text-sm font-normal",children:"Save to domain"})]})]}),s&&l.jsx("p",{className:"text-xs text-red-500",children:s})]})}function Bst({description:e,tags:t,onDescriptionChange:n,onTagsChange:r,descriptionError:s,disabled:o}){return l.jsxs("div",{className:"space-y-3 rounded-md border border-muted bg-muted/30 p-3",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{htmlFor:"domain-description",children:"Description"}),l.jsx(Ma,{id:"domain-description",value:e,onChange:i=>n(i.target.value),placeholder:"Explain what this metric represents",className:X("text-sm",s&&"border-red-500"),rows:3,disabled:o}),s&&l.jsx("p",{className:"text-xs text-red-500",children:s})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{htmlFor:"domain-tags",children:"Tags (optional)"}),l.jsx(sn,{id:"domain-tags",value:t,onChange:i=>r(i.target.value),placeholder:"profitability, kpi",disabled:o})]}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"This field will be visible to all dashboards using this domain."})]})}function Vst({endpoint:e,availableFields:t,fieldType:n,dialect:r}){const{authToken:s}=Je(),[o,i]=w.useState(!1),[a,c]=w.useState(null);return{generateExpression:w.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})),fieldType:n},options:{dialect:r}},m=await ls(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((h==null?void 0:h.error)||(h==null?void 0:h.message)||"AI generation failed"),null}finally{i(!1)}},[e,t,n,r,s==null?void 0:s.accessToken]),isGenerating:o,error:a}}function Ust({open:e,onOpenChange:t,availableFields:n,fieldType:r,onExpressionGenerated:s,endpoint:o,dialect:i}){const[a,c]=w.useState(""),[u,d]=w.useState(""),[f,h]=w.useState(""),{generateExpression:m,isGenerating:p,error:g}=Vst({endpoint:o,availableFields:n,fieldType:r,dialect:i}),b=w.useMemo(()=>{const C=f.trim().toLowerCase();return C?n.filter(j=>[j.label,j.baseLabel,j.name,j.tokenLabel,j.entityName,j.qualifiedEntityName].filter(Boolean).join(" ").toLowerCase().includes(C)):n},[n,f]),x=C=>{const E=(C.name||C.baseLabel||C.label||C.tokenLabel||"").trim();return E.includes(".")&&E.split(".").pop()||E},y=C=>{const j=C.entityName||C.qualifiedEntityName||"";return j?j==="SEMAPHOR_CALCULATED_FIELD"?"Calculated":j.includes(".")&&j.split(".").pop()||j:"—"},v=async()=>{const C=await m(a.trim());C&&d(C)},S=()=>{u.trim()&&(s(u.trim()),c(""),d(""),t(!1))},N=()=>{c(""),d(""),h(""),t(!1)};return l.jsx(qr,{open:e,onOpenChange:C=>{C?t(!0):N()},children:l.jsxs(Pr,{className:"max-w-3xl",children:[l.jsxs(Or,{children:[l.jsx(Fr,{children:"Generate Expression with AI"}),l.jsx(Jr,{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(de,{htmlFor:"ai-prompt",children:"Describe what you want to calculate"}),l.jsx(pp,{id:"ai-prompt",value:a,onChange:C=>c(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(re,{size:"sm",onClick:v,disabled:p||!a.trim(),children:p?"Generating...":u?"Regenerate":"Generate"})]}),g&&l.jsx("p",{className:"text-xs text-destructive",children:g})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{children:"Available fields"}),l.jsxs("div",{className:"relative",children:[l.jsx(zo,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),l.jsx(sn,{value:f,onChange:C=>h(C.target.value),placeholder:"Search fields...",className:"pl-9"})]}),l.jsx("div",{className:"overflow-hidden rounded-lg border border-border",children:l.jsx("div",{className:"max-h-48 overflow-y-auto",children:l.jsxs("table",{className:"w-full text-sm",children:[l.jsx("thead",{className:"sticky top-0 z-10 border-b bg-muted",children:l.jsxs("tr",{children:[l.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Field"}),l.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Type"}),l.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Category"})]})}),l.jsx("tbody",{className:"divide-y",children:b.length===0?l.jsx("tr",{children:l.jsx("td",{colSpan:3,className:"py-6 text-center text-xs text-muted-foreground",children:"No fields match your search."})}):b.map(C=>l.jsxs("tr",{className:"hover:bg-muted/30",children:[l.jsx("td",{className:"px-3 py-1.5 font-mono text-xs",children:x(C)}),l.jsx("td",{className:"px-3 py-1.5",children:l.jsx(st,{variant:"secondary",className:"px-1.5 py-0 text-[11px]",children:C.dataType})}),l.jsx("td",{className:"px-3 py-1.5 text-sm text-muted-foreground",children:y(C)})]},C.id))})]})})})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{children:"Generated expression"}),l.jsx(pp,{value:u,readOnly:!0,rows:2,className:"font-mono text-sm"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Review the generated expression before using it."})]})]}),l.jsxs(vs,{className:"gap-2",children:[l.jsx(re,{variant:"ghost",onClick:N,children:"Cancel"}),l.jsx(re,{onClick:S,disabled:!u.trim(),children:"Use Expression"})]})]})})}const Hst=/\{([^}]+)\}/g;function Sj(e){return e.trim().toLowerCase()}function HS(e){return Array.from(e.matchAll(Hst)).map(t=>t[1]).filter(Boolean)}function Wst(e){const t=new Set,n=[];return e.forEach(r=>{const s=Sj(r);t.has(s)||(t.add(s),n.push(r))}),n}function QO(e){const t=new Map,n=(r,s)=>{const o=Sj(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 Zg(e,t){const n=HS(e),r=Wst(n),s=QO(t),o=r.map(a=>{const c=s.get(Sj(a))||[];return c.length===1?c[0]:null}),i=r.filter((a,c)=>!o[c]);return{orderedTokens:r,orderedFields:o,unresolvedTokens:i}}function x9(e,t){return t.reduce((n,r,s)=>{const o=new RegExp(`\\{${qst(r)}\\}`,"gi");return n.replace(o,`{field_${s}}`)},e)}function qst(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Yst=e=>e.entityName===Bm||e.entityName===Ec?"Calculated Fields":e.qualifiedEntityName?ox(e.entityName||e.qualifiedEntityName):ox(e.entityName||"Other"),Gst=e=>Ar(e.dataType||"")==="number";function Kst(e,t,n){const r=new Set((n||[]).map(s=>Jl(s)));return e.filter(s=>{const o=Jl(s.id);return o&&r.has(o)?!1:t==="dimension"?s.role!=="metric":!0})}function Zst(e){const t=new Map,n=new Map;return e.forEach(r=>{let o=r.entityName&&r.entityName!==Ec?`${r.entityName}.${r.name}`:r.name;const i=o.toLowerCase(),a=n.get(i)||0;a>0&&(o=`${o} ${a+1}`),n.set(i,a+1),t.set(r.id,o)}),t}function Xst(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||Gst(o);return{...o,isCompatible:i}}).filter(o=>r)}function Qst(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 Jst(e){const t=new Map;return e.forEach(n=>{var s;const r=n.qualifiedEntityName||n.entityName||"Other";t.has(r)||t.set(r,{id:r,label:Yst(n),fields:[]}),(s=t.get(r))==null||s.fields.push(n)}),Array.from(t.values())}function eot({fields:e,mode:t,searchTerm:n,excludeFieldIds:r,selectedAggregate:s,showIncompatible:o}){const i=w.useMemo(()=>Kst(e,t,r),[e,t,r]),a=w.useMemo(()=>Zst(i),[i]),c=w.useMemo(()=>i.map(m=>{const p=m.label||m.name,g=m.role==="metric"&&Dc(m)||m.role==="groupby"&&Wy(m);return{...m,baseLabel:p,tokenLabel:a.get(m.id)||p,isCalculated:g,isCompatible:!0}}),[i,a]),u=w.useMemo(()=>QO(c),[c]),d=w.useMemo(()=>Xst(c,t,s,o),[c,t,s,o]),f=w.useMemo(()=>Qst(d,n),[d,n]),h=w.useMemo(()=>Jst(f),[f]);return{allFields:c,filteredFields:f,groups:h,tokenCandidates:u}}const tot=e=>{let t=0;for(const n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0},not=(e,t)=>{const n=e.toLowerCase(),r=t.toLowerCase();if(n===r)return 0;if(!n.length)return r.length;if(!r.length)return n.length;const s=[];for(let o=0;o<=r.length;o+=1)s[o]=[o];for(let o=0;o<=n.length;o+=1)s[0][o]=o;for(let o=1;o<=r.length;o+=1)for(let i=1;i<=n.length;i+=1)r.charAt(o-1)===n.charAt(i-1)?s[o][i]=s[o-1][i-1]:s[o][i]=Math.min(s[o-1][i-1]+1,s[o][i-1]+1,s[o-1][i]+1);return s[r.length][n.length]},rot=(e,t)=>t.map(r=>({candidate:r,distance:not(e,r)})).filter(r=>r.distance>0&&r.distance<=3).sort((r,s)=>r.distance-s.distance).slice(0,3).map(r=>r.candidate),sot=(e,t)=>{var r;const n=e.trim();if(n){if(/\bDATE_TRUNC\b/i.test(n))return"date";if(/\bTIMESTAMP\b/i.test(n))return"datetime";if(/\bDATE\b/i.test(n)&&!/\bUPDATE\b/i.test(n))return"date";if(/['"]/.test(n))return"string";if(/[+\-*/]/.test(n))return"number";if(t.length===1){const s=((r=t[0])==null?void 0:r.dataType)||"";if(/date|timestamp/i.test(s))return"date";if(/int|decimal|float|double|num|real/i.test(s))return"number";if(/boolean/i.test(s))return"boolean"}return"string"}},oot=e=>e.map(t=>({id:t.id,name:t.name,label:t.tokenLabel,dataType:t.dataType,entityName:t.entityName,role:t.role}));function iot({expression:e,availableFields:t,excludeFieldIds:n,validationEndpoint:r,connectionId:s,dialect:o}){const{authToken:i}=Je(),[a,c]=w.useState(null),[u,d]=w.useState(!1),[f,h]=w.useState(null),m=w.useMemo(()=>QO(t),[t]),p=w.useMemo(()=>{const x=[],y=[],v=e.trim();v||x.push({code:"SYNTAX_ERROR",message:"Expression is required"}),v&&!tot(v)&&x.push({code:"SYNTAX_ERROR",message:"Unbalanced parentheses in expression"});const N=HS(e).map(j=>{const E=m.get(Sj(j))||[];if(!E.length){const _=Array.from(m.keys()),T=rot(j,_),P=T.length?`Did you mean {${T[0]}}?`:void 0;return x.push({code:"UNKNOWN_TOKEN",message:`Unknown field token: {${j}}`,suggestion:P}),{token:j,field:null,error:"Unknown token"}}if(E.length>1)return x.push({code:"UNKNOWN_TOKEN",message:`Token {${j}} matches multiple fields. Use a disambiguated label.`}),{token:j,field:null,error:"Ambiguous token"};const M=E[0];return(n||[]).map(Jl).includes(Jl(M.id))?(x.push({code:"SELF_REFERENCE",message:"Cannot reference the field being edited"}),{token:j,field:null,error:"Self reference"}):{token:j,field:M}});/\bCASE\b/i.test(e)&&!/\bELSE\b/i.test(e)&&y.push({code:"MISSING_ELSE",message:"CASE expression missing ELSE clause",suggestion:"Add an ELSE branch to handle default values."}),/\//.test(e)&&!/NULLIF\s*\(/i.test(e)&&y.push({code:"DIVISION_BY_ZERO",message:"Division may result in divide-by-zero errors",suggestion:"Wrap the denominator in NULLIF(..., 0)."});const C=N.map(j=>j.field).filter(Boolean);return{isValid:x.length===0,tokens:N,errors:x,warnings:y,inferredDataType:sot(e,C)}},[e,n,m]),g=w.useCallback(async()=>{var v;if(h(null),!r||!p.isValid)return c(p),p;const x=r,y={type:"calculated-field-expression",value:e,context:{availableFields:oot(t),connectionId:s,excludeFieldIds:n,dialect:o}};d(!0);try{const S=await ls(x,(i==null?void 0:i.accessToken)||"",y),N=S.errors||[],C=S.warnings||[],j={...p,isValid:S.valid&&N.length===0,errors:N,warnings:C,inferredDataType:((v=S.metadata)==null?void 0:v.inferredType)||p.inferredDataType};return c(j),j}catch(S){return h((S==null?void 0:S.error)||"Validation failed"),c(p),p}finally{d(!1)}},[r,p,e,t,s,n,o,i==null?void 0:i.accessToken]),b=w.useCallback(()=>{c(null),h(null)},[]);return{clientResult:p,validationResult:a,isValidating:u,serverError:f,validateExpression:g,resetValidation:b}}const y9=[{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"}],EE=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})`},Eoe=e=>Ar(e.dataType||"")==="number",Gh=e=>Eoe(e)?"SUM":"COUNT",_E=(e,t)=>Eoe(e)||t==="COUNT"||t==="DISTINCT"?t:Gh(e);function TE(e,t){if(e.role==="metric"){const n=e;return Dc(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 zh(e,t){const n=e.role==="metric"&&Dc(e);return{field:e,aggregate:n&&e.aggregate||t,isCalculatedField:n}}function _oe({open:e,onOpenChange:t,availableFields:n,existingField:r,existingFieldScope:s,onSave:o,onSaveToDashboard:i,onPromoteMetricToDomain:a,onPromoteDimensionToDomain:c,cardId:u,domainId:d,initialFieldType:f="metric",allowedFieldTypes:h}){var Ve;const{tokenProps:m}=Je(),{selectedConnection:p}=xY(),g=(p==null?void 0:p.dialect)==="bigquery"||(p==null?void 0:p.dialect)==="snowflake",[b,x]=w.useState(f),[y,v]=w.useState(""),[S,N]=w.useState("ratio"),[C,j]=w.useState(null),[E,M]=w.useState(null),[k,_]=w.useState(1),[T,P]=w.useState(""),[O,R]=w.useState(null),[$,Y]=w.useState("card"),[W,H]=w.useState(""),[A,L]=w.useState(""),[F,I]=w.useState({}),[U,V]=w.useState("A"),[G,B]=w.useState(""),[z,q]=w.useState(!1),[Z,ee]=w.useState(null),[K,te]=w.useState(!1),[ie,ue]=w.useState(!1),[le,we]=w.useState(!1),se=w.useRef(null),ke=w.useRef(!1),be=w.useRef(null),{userContext:Me}=ro(),{metrics:Pe,dimensions:ge}=Dst(),$e=(Me==null?void 0:Me.type)==="organization",ce=!$e,J=!!d&&$e,ae=J&&!!a,ve=J&&!!c,Ce=!!(i||ae||ve),Ee=!!i,me=b==="metric"?ae:ve,De=(Ve=m==null?void 0:m.apiServiceUrl)==null?void 0:Ve.replace(/\/$/,""),He=De?`${De}/v1/validate`:"/v1/validate",et=De?`${De}/v1/ai/generate`:"/v1/ai/generate",Te=w.useMemo(()=>{var xt;const pe=[...n];return(((xt=r==null?void 0:r.calculatedFormula)==null?void 0:xt.inputFields)||[]).forEach(Se=>{pe.some(ct=>ct.id===Se.id||ct.qualifiedFieldName===Se.qualifiedFieldName||ct.name===Se.name)||pe.push(Se)}),pe},[n,r]),Ye=U==="A"?C:E,nt=b==="metric"&&S!=="custom"?Ye==null?void 0:Ye.aggregate:void 0,{allFields:Re,groups:it}=eot({fields:Te,mode:b,searchTerm:G,excludeFieldIds:r?[r.id]:void 0,selectedAggregate:nt,showIncompatible:!0}),ye=Re,{clientResult:tt,validationResult:Ue,validateExpression:Qe,isValidating:Et,serverError:Oe,resetValidation:Ne}=iot({expression:T,availableFields:ye,excludeFieldIds:r?[r.id]:void 0,validationEndpoint:He,connectionId:p==null?void 0:p.id,dialect:p==null?void 0:p.dialect}),ze=(Ue==null?void 0:Ue.inferredDataType)||tt.inferredDataType,ft=O||ze||"string",lt=iy.find(pe=>pe.id===S),fe=w.useMemo(()=>{if(!y.trim())return!1;const pe=zl(y),rt=s==="domain"&&(r!=null&&r.name)?zl(r.name):null;return(b==="metric"?Pe:ge).some(Se=>{const Ge=zl(Se.name);return rt&&Ge===rt?!1:Ge===pe})},[ge,Pe,r,s,b,y]),qe=w.useMemo(()=>{if(b==="metric"&&S==="custom"){const{orderedFields:rt}=Zg(T,ye);return rt.filter(xt=>!!xt).map(xt=>xt.id)}const pe=[];return C!=null&&C.field.id&&pe.push(C.field.id),E!=null&&E.field.id&&pe.push(E.field.id),pe},[ye,T,b,C,E,S]),at=pe=>{ce||(x(pe),pe==="dimension"&&$==="domain"&&!ve&&Y("card"),pe==="metric"&&$==="domain"&&!ae&&Y("card"))},Pt=pe=>{ce||(N(pe),pe==="scale"&&M(null),pe==="custom"&&(j(null),M(null)))},$t=()=>{v(""),N("ratio"),j(null),M(null),_(1),P(""),R(null),Y("card"),H(""),L(""),I({}),B(""),q(!1),ee(null),te(!1),we(!1),Ne(),t(!1)},Tn=w.useCallback(pe=>Te.find(rt=>rt.qualifiedFieldName===pe.qualifiedFieldName||rt.name===pe.name)||pe,[Te]),or=w.useCallback(pe=>{if(!pe.calculatedFormula)return;const rt=pe.calculatedFormula;if(N(rt.operation),P(""),rt.operation==="scale"){const Ge=rt.inputFields[0];Ge&&j(zh(Tn(Ge),Ge.aggregate||"SUM")),_(rt.constant===void 0?1:rt.constant);return}if(rt.operation==="custom"){P(ss(pe.expression||"",rt.inputFields||[])),j(null),M(null);return}const[xt,Se]=rt.inputFields;xt&&j(zh(Tn(xt),xt.aggregate||"SUM")),Se&&M(zh(Tn(Se),Se.aggregate||"SUM"))},[Tn]),ss=w.useCallback((pe,rt)=>pe.replace(/\{field_(\d+)\}/g,(xt,Se)=>{var mt;const Ge=rt[Number(Se)];return Ge?`{${((mt=ye.find(Ct=>Ct.id===Ge.id))==null?void 0:mt.tokenLabel)||Ge.label||Ge.name}}`:xt}),[ye]);w.useEffect(()=>{var xt;if(!e){ke.current=!1,be.current=null;return}const pe=r?`${r.role}-${r.id||r.name}`:"new";if(ke.current&&be.current===pe)return;if(ke.current=!0,be.current=pe,I({}),B(""),we(!1),Ne(),r){const Se=r.tags||[];if(r.role==="metric"){x("metric"),v(r.label||r.name),Y(s||"card"),H(r.description||""),L(Se.join(", ")),or(r);return}x("dimension");const Ge=r;v(Ge.label||Ge.name),Y(s||"card"),P(ss(Ge.expression||"",((xt=Ge.calculatedFormula)==null?void 0:xt.inputFields)||[]));const ct=y9.some(mt=>mt.value===Ge.dataType)?Ge.dataType:"string";R(ct),H(Ge.description||""),L(Se.join(", "));return}const rt=h&&h.length>0?h.includes(f)?f:h[0]:f;x(rt),v(""),N("ratio"),j(null),M(null),_(1),P(""),R(null),Y("card"),H(""),L("")},[e,r,s,f,h,or,ss,Ne]);const Fs=pe=>{const rt=`{${pe}}`,xt=se.current;if(!xt){P(mt=>mt+rt);return}const Se=xt.selectionStart||0,Ge=xt.selectionEnd||0,ct=`${T.slice(0,Se)}${rt}${T.slice(Ge)}`;P(ct),requestAnimationFrame(()=>{xt.focus();const mt=Se+rt.length;xt.setSelectionRange(mt,mt)})},Ki=pe=>{if(ce)return;if(b==="dimension"||S==="custom"){Fs(pe.tokenLabel||pe.label||pe.name);return}const rt=_E(pe,U==="A"?(C==null?void 0:C.aggregate)||Gh(pe):(E==null?void 0:E.aggregate)||Gh(pe)),xt=zh(pe,rt);if(U==="A"){j(xt),E||V("B");return}M(xt),C||V("A")},Ss=(pe,rt)=>{if(!ce){if(pe==="A"&&C){j({...C,aggregate:rt});return}pe==="B"&&E&&M({...E,aggregate:rt})}},jo=async()=>{const pe={};if(y.trim()||(pe.name="Name is required"),S==="custom")T.trim()||(pe.expression="Expression is required"),HS(T).length===0&&(pe.expression=pe.expression||"Expression must include field tokens"),Zg(T,ye).unresolvedTokens.length>0&&(pe.expression=pe.expression||"Expression contains unknown or ambiguous tokens"),pe.expression||(await Qe()).isValid||(pe.expression="Fix validation errors before saving");else if(S==="scale")C||(pe.inputA="Please select a metric for input A"),Number.isNaN(k)&&(pe.constant="Please enter a valid multiplication factor");else{if(C||(pe.inputA="Please select a metric for input A"),E||(pe.inputB="Please select a metric for input B"),C&&E){const rt=C.field.id===E.field.id,xt=C.aggregate===E.aggregate;rt&&xt&&(pe.inputs="Inputs A and B must be different metrics")}if(r&&r.role==="metric"){const rt=Jl(r.id);(Jl(C==null?void 0:C.field.id)===rt||Jl(E==null?void 0:E.field.id)===rt)&&(pe.inputs="Cannot reference the field being edited")}}return Ce&&($==="domain"&&!ae&&(pe.scope="You do not have permission to save to domain"),$==="domain"&&!W.trim()&&(pe.description="Description is required for domain fields"),$==="domain"&&fe&&(pe.name="A domain field with this name already exists")),I(pe),Object.keys(pe).length===0},Tl=async()=>{const pe={};return y.trim()||(pe.name="Name is required"),T.trim()||(pe.expression="Expression is required"),HS(T).length===0&&(pe.expression=pe.expression||"Expression must include field tokens"),Zg(T,ye).unresolvedTokens.length>0&&(pe.expression=pe.expression||"Expression contains unknown or ambiguous tokens"),pe.expression||(await Qe()).isValid||(pe.expression="Fix validation errors before saving"),Ce&&($==="domain"&&!ve&&(pe.scope="You do not have permission to save to domain"),$==="domain"&&!W.trim()&&(pe.description="Description is required for domain fields"),$==="domain"&&fe&&(pe.name="A domain field with this name already exists")),I(pe),Object.keys(pe).length===0},Ml=()=>{const{orderedTokens:pe,orderedFields:rt}=Zg(T,ye),xt=rt.filter(ct=>!!ct),Se=x9(T,pe),Ge=Ist(y,Se,xt,ft,u,r==null?void 0:r.id);return r&&r.role==="groupby"?{...r,...Ge}:Ge},Il=()=>{var Se;if(S==="custom"){const{orderedTokens:Ge,orderedFields:ct}=Zg(T,ye),mt=ct.filter(Ft=>!!Ft),Ct=(r==null?void 0:r.role)==="metric"?((Se=r.calculatedFormula)==null?void 0:Se.inputFields)||[]:[],Mt=new Map;Ct.forEach(Ft=>{const Pn=Jl(Ft.id);Pn&&Mt.set(Pn,Ft),Ft.qualifiedFieldName&&Mt.set(Ft.qualifiedFieldName,Ft),Ft.name&&Mt.set(Ft.name,Ft)});const zr=mt.map(Ft=>{const Pn=Jl(Ft.id),Uo=Pn&&Mt.get(Pn)||Ft.qualifiedFieldName&&Mt.get(Ft.qualifiedFieldName)||Mt.get(Ft.name),wh=((Uo==null?void 0:Uo.role)==="metric"?Uo.aggregate:void 0)||(Ft.role==="metric"?Ft.aggregate:void 0)||Gh(Ft);return TE(Ft,wh)}),Bt=x9(T,Ge),Ot=m9(y,S,null,null,{},u,r==null?void 0:r.id,Bt,void 0,zr);return r&&r.role==="metric"?{...r,...Ot}:Ot}const pe=C?TE(C.field,C.aggregate):null,rt=E?TE(E.field,E.aggregate):null,xt=m9(y,S,pe,rt,{},u,r==null?void 0:r.id,void 0,S==="scale"?k:void 0);return r&&r.role==="metric"?{...r,...xt}:xt},Dl=async pe=>{var xt,Se,Ge;if(b==="dimension"){const ct=Ml();if(pe==="dashboard"){if(!i){I(mt=>({...mt,scope:"Dashboard scope is not available"}));return}i(ct),$t();return}if(pe==="domain"){if(!c){I(Ot=>({...Ot,scope:"Domain scope is not available"}));return}const mt=((xt=ct.calculatedFormula)==null?void 0:xt.inputFields)||[],Ct=new Map,Mt=mt.map(Ot=>{const Ft=zl(Ot.label||Ot.name),Pn=Ct.get(Ft)||0;return Ct.set(Ft,Pn+1),Pn===0?Ft:`${Ft}_${Pn+1}`}),zr=((Se=ct.expression)==null?void 0:Se.replace(/\{field_(\d+)\}/g,(Ot,Ft)=>`{${Mt[Number(Ft)]||Ft}}`))||"",Bt=Mt.reduce((Ot,Ft,Pn)=>{const Uo=mt[Pn];return Wy(Uo)?Ot[Ft]={dimension:Uo.name}:Ot[Ft]={dataset:Uo.entityName,field:Uo.name},Ot},{});try{await c({name:zl(y),label:y.trim(),description:W.trim(),expression:zr,inputs:Bt,dataType:ft,tags:A.split(",").map(Ot=>Ot.trim()).filter(Boolean),overwrite:s==="domain",previousName:s==="domain"?r==null?void 0:r.name:void 0})}catch(Ot){I(Ft=>({...Ft,scope:(Ot==null?void 0:Ot.message)||"Failed to save to domain"}));return}$t();return}o(ct),$t();return}const rt=Il();if(pe==="dashboard"){if(!i){I(ct=>({...ct,scope:"Dashboard scope is not available"}));return}i(rt),$t();return}if(pe==="domain"){if(!a){I(Bt=>({...Bt,scope:"Domain scope is not available"}));return}if(!rt.calculatedFormula){I(Bt=>({...Bt,scope:"Calculated formula missing"}));return}const ct=rt.calculatedFormula.inputFields,mt=new Map,Ct=ct.map(Bt=>{const Ot=zl(Bt.label||Bt.name),Ft=mt.get(Ot)||0;return mt.set(Ot,Ft+1),Ft===0?Ot:`${Ot}_${Ft+1}`}),Mt=((Ge=rt.expression)==null?void 0:Ge.replace(/\{field_(\d+)\}/g,(Bt,Ot)=>`{${Ct[Number(Ot)]||Ot}}`))||"",zr=Ct.reduce((Bt,Ot,Ft)=>{const Pn=ct[Ft];return Pn.role==="metric"?Dc(Pn)?Bt[Ot]={metric:Pn.name}:Bt[Ot]={dataset:Pn.entityName,field:Pn.name,aggregate:Pn.aggregate}:Bt[Ot]={dataset:Pn.entityName,field:Pn.name},Bt},{});try{await a({name:zl(y),label:y.trim(),description:W.trim(),expression:Mt,inputs:zr,tags:A.split(",").map(Bt=>Bt.trim()).filter(Boolean),overwrite:s==="domain",previousName:s==="domain"?r==null?void 0:r.name:void 0})}catch(Bt){I(Ot=>({...Ot,scope:(Bt==null?void 0:Bt.message)||"Failed to save to domain"}));return}$t();return}o(rt),$t()},pt=async()=>{if(ce)return;if(I({}),b==="metric"){if(!await jo())return}else if(!await Tl())return;const pe=Ce?$:s||"card";if(b==="metric"&&pe!=="domain"&&fe&&!r){ee(pe),te(!0);return}ue(!0);try{await Dl(pe)}finally{ue(!1)}},he=w.useMemo(()=>{if(!lt||S==="custom")return"";if(S==="scale"){const pe=Number.isFinite(k)?k:1;return`${EE(C)} x ${pe}`}return`${EE(C)||"A"} ${lt.symbol} ${EE(E)||"B"}`},[lt,S,C,E,k]);return l.jsxs(l.Fragment,{children:[l.jsxs(qr,{modal:!1,open:e,onOpenChange:pe=>{pe?t(!0):$t()},children:[e&&l.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),l.jsxs(Pr,{className:"max-w-5xl max-h-[90vh] overflow-hidden",onInteractOutside:pe=>{pe.preventDefault()},children:[l.jsxs(Or,{children:[l.jsxs(Fr,{children:[r?"Edit":"Create"," Calculated Field"]}),l.jsx(Jr,{children:"Build calculated metrics and dimensions using expressions."})]}),l.jsxs("div",{className:"grid h-[70vh] min-h-0 grid-cols-[320px_1fr] gap-6",children:[l.jsx(Rst,{groups:it,searchTerm:G,onSearchTermChange:B,onFieldClick:Ki,selectedFieldIds:qe,disabled:ce}),l.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-4 overflow-y-auto pr-2",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{children:"Field Type"}),l.jsx(Ast,{value:b,onChange:at,disabled:ce||!!r,options:h||["metric","dimension"]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{htmlFor:"calculated-name",children:"Name"}),l.jsx(sn,{id:"calculated-name",value:y,onChange:pe=>v(pe.target.value),placeholder:"e.g., Profit Margin",className:F.name?"border-red-500":"",disabled:ce}),F.name&&l.jsx("p",{className:"text-xs text-red-500",children:F.name})]}),b==="metric"&&l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{children:"Operation"}),l.jsx(Pst,{value:S,onChange:Pt,allowCustom:!0,disabled:ce}),F.operation&&l.jsx("p",{className:"text-xs text-red-500",children:F.operation})]}),S==="custom"?l.jsxs("div",{className:"space-y-4",children:[l.jsx(g9,{ref:se,value:T,onChange:pe=>{P(pe),we(!1)},onGenerate:()=>q(!0),showGenerate:!!et&&!ce,disabled:ce}),l.jsx(b9,{onValidate:async()=>{we(!0),await Qe()},isValidating:Et,validationResult:Ue,fallbackResult:tt,error:Oe,showFallback:le,disabled:ce}),F.expression&&l.jsx("p",{className:"text-xs text-red-500",children:F.expression})]}):l.jsxs("div",{className:"space-y-3",children:[l.jsx(de,{children:"Inputs"}),l.jsx(p9,{label:"A",input:C,availableFields:ye,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:pe=>{const rt=_E(pe,(C==null?void 0:C.aggregate)||Gh(pe));j(zh(pe,rt))},onAggregateChange:pe=>Ss("A",pe),onRemove:()=>j(null),onActivate:()=>V("A"),allowMedian:g,disabled:ce}),F.inputA&&l.jsx("p",{className:"text-xs text-red-500",children:F.inputA}),S!=="scale"&&l.jsxs(l.Fragment,{children:[l.jsx(p9,{label:"B",input:E,availableFields:ye,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:pe=>{const rt=_E(pe,(E==null?void 0:E.aggregate)||Gh(pe));M(zh(pe,rt))},onAggregateChange:pe=>Ss("B",pe),onRemove:()=>M(null),onActivate:()=>V("B"),allowMedian:g,disabled:ce}),F.inputB&&l.jsx("p",{className:"text-xs text-red-500",children:F.inputB})]}),S==="scale"&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{htmlFor:"constantFactor",children:"Multiplication Factor"}),l.jsx(sn,{id:"constantFactor",type:"number",step:"any",value:Number.isNaN(k)?"":k,onChange:pe=>_(pe.target.value===""?Number.NaN:Number(pe.target.value)),className:F.constant?"border-red-500":"",placeholder:"e.g., 0.15",disabled:ce}),F.constant&&l.jsx("p",{className:"text-xs text-red-500",children:F.constant})]}),l.jsx("div",{className:"rounded-md border border-border bg-muted/40 p-3 text-sm font-mono",children:he||"Select inputs to preview formula"}),F.inputs&&l.jsxs(_N,{variant:"destructive",children:[l.jsx(wc,{className:"h-4 w-4"}),l.jsx(TN,{children:F.inputs})]})]})]}),b==="dimension"&&l.jsxs("div",{className:"space-y-4",children:[l.jsx(g9,{ref:se,value:T,onChange:pe=>{P(pe),we(!1)},onGenerate:()=>q(!0),showGenerate:!!et&&!ce,disabled:ce}),l.jsx(b9,{onValidate:async()=>{we(!0),await Qe()},isValidating:Et,validationResult:Ue,fallbackResult:tt,error:Oe,showFallback:le,disabled:ce}),F.expression&&l.jsx("p",{className:"text-xs text-red-500",children:F.expression}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(de,{children:"Output Type"}),l.jsxs(yt,{value:ft,onValueChange:pe=>R(pe),disabled:ce,children:[l.jsx(gt,{className:"h-9 w-full",children:l.jsx(St,{placeholder:"Select output type"})}),l.jsx(bt,{children:y9.map(pe=>l.jsx(je,{value:pe.value,children:pe.label},pe.value))})]}),ze&&!O&&l.jsxs("p",{className:"text-xs text-muted-foreground",children:["Suggested type: ",ze]})]})]}),Ce&&(Ee||me)&&l.jsxs("div",{className:"space-y-3",children:[l.jsx(zst,{scope:$,onChange:Y,showDashboardScope:Ee,showDomainScope:me,error:F.scope,disabled:ce}),$==="domain"&&l.jsx(Bst,{description:W,tags:A,onDescriptionChange:H,onTagsChange:L,descriptionError:F.description,disabled:ce})]})]})]}),l.jsxs(vs,{children:[l.jsx(re,{variant:"outline",onClick:$t,children:"Cancel"}),l.jsxs(re,{onClick:pt,disabled:ie||ce,children:[r?"Update":"Create"," ",b==="metric"?"Metric":"Dimension"]})]})]})]}),l.jsx(Ust,{open:z,onOpenChange:q,availableFields:ye,fieldType:b,onExpressionGenerated:async pe=>{P(pe),we(!1),Ne()},endpoint:et,dialect:p==null?void 0:p.dialect}),l.jsx(ch,{open:K,onOpenChange:te,children:l.jsxs(Gu,{children:[l.jsxs(Ku,{children:[l.jsx(Xu,{children:"Name Conflict"}),l.jsxs(Qu,{children:['A domain metric named "',y.trim(),'" already exists. Your local version will override it in this'," ",Z==="dashboard"?"dashboard":"card",". Continue?"]})]}),l.jsxs(Zu,{children:[l.jsx(ed,{onClick:()=>{ee(null)},children:"Choose Different Name"}),l.jsx(Ju,{onClick:async()=>{if(Z){te(!1),ue(!0);try{await Dl(Z)}finally{ue(!1),ee(null)}}},children:"Continue"})]})]})})]})}function Toe({domainId:e}){const{authToken:t,tokenProps:n}=Je(),[r,s]=w.useState(!1),[o,i]=w.useState(null),a=w.useMemo(()=>{var m;if(!e)return null;const f=(m=n==null?void 0:n.apiServiceUrl)==null?void 0:m.replace(/\/$/,""),h=`/v1/domains/${e}/calculated-metrics`;return f?`${f}${h}`:h},[e,n==null?void 0:n.apiServiceUrl]),c=w.useMemo(()=>{var m;if(!e)return null;const f=(m=n==null?void 0:n.apiServiceUrl)==null?void 0:m.replace(/\/$/,""),h=`/v1/domains/${e}/calculated-dimensions`;return f?`${f}${h}`:h},[e,n==null?void 0:n.apiServiceUrl]),u=w.useCallback(async f=>{if(!a){const h="Domain promotion is not available";throw i(h),new Error(h)}if(!(t!=null&&t.accessToken)){const h="Missing authentication token";throw i(h),new Error(h)}s(!0),i(null);try{return await ls(a,t.accessToken,f)}catch(h){const m=(h==null?void 0:h.error)||(h==null?void 0:h.message)||"Failed to save to domain";throw i(m),new Error(m)}finally{s(!1)}},[a,t==null?void 0:t.accessToken]),d=w.useCallback(async f=>{if(!c){const h="Domain promotion is not available";throw i(h),new Error(h)}if(!(t!=null&&t.accessToken)){const h="Missing authentication token";throw i(h),new Error(h)}s(!0),i(null);try{return await ls(c,t.accessToken,f)}catch(h){const m=(h==null?void 0:h.error)||(h==null?void 0:h.message)||"Failed to save to domain";throw i(m),new Error(m)}finally{s(!1)}},[c,t==null?void 0:t.accessToken]);return{promoteMetric:u,promoteDimension:d,isPromoting:r,error:o}}const Moe=w.memo(function({context:t="editor",onFieldSelect:n,inlineFilters:r}={}){var Ne,ze,ft,lt;const[s,o]=w.useState(""),[i,a]=w.useState("all"),[c,u]=w.useState(!1),[d,f]=w.useState(null),[h,m]=w.useState("card"),[p,g]=w.useState("metric");Le(fe=>fe.isDevMode);const b=Le(fe=>fe.card.dataSource),x=Le(fe=>fe.card.config),y=Le(fe=>fe.card),v=Le(fe=>fe.frame),S=Le(fe=>fe.actions.updateCardConfig),N=Le(fe=>fe.actions.updateFrame),{userContext:C}=ro(),{autoJoinMetadata:j}=pl(y),{columns:E,rawColumnGroups:M,scopedFields:k,dashboardCalculatedFields:_,cardCalculatedFields:T,isLoading:P,error:O,refetch:R}=KO(),$=(b==null?void 0:b.mode)==="semanticDomain"?b.semanticDomainId:void 0,{data:Y}=ZO($),{promoteMetric:W,promoteDimension:H}=Toe({domainId:$}),A=w.useMemo(()=>[...(x==null?void 0:x.groupByColumns)||[],...(x==null?void 0:x.metricColumns)||[],...(x==null?void 0:x.detailColumns)||[]],[x==null?void 0:x.groupByColumns,x==null?void 0:x.metricColumns,x==null?void 0:x.detailColumns]);(ze=(Ne=x==null?void 0:x.joinPlan)==null?void 0:Ne.baseEntity)==null||ze.name,(lt=(ft=j==null?void 0:j.resolvedJoinPlan)==null?void 0:ft.baseEntity)==null||lt.name,woe();const L=t==="editor",F=(C==null?void 0:C.type)==="organization",I=L?k:E,U=M,V=s.toLowerCase(),G=(x==null?void 0:x.metricColumns)||[],B=(x==null?void 0:x.groupByColumns)||[],z=w.useCallback(async fe=>{await W(fe),R()},[W,R]),q=w.useCallback(async fe=>{await H(fe),R()},[H,R]),Z=fe=>fe.name.toLowerCase().includes(V)||fe.dataType.toLowerCase().includes(V)||fe.label&&fe.label.toLowerCase().includes(V)||fe.qualifiedEntityName&&fe.qualifiedEntityName.toLowerCase().includes(V),ee=fe=>(fe.label||fe.name).toLowerCase().trim(),K=(fe,qe)=>ee(fe).localeCompare(ee(qe),void 0,{numeric:!0,sensitivity:"base"}),te=I.filter(Z).sort(K),ie=fe=>{if(fe.role==="metric"&&Dc(fe)||fe.role==="groupby"&&fe.expression)return"calculated";if(fe.dataType==="number"||fe.dataType==="integer"||fe.dataType==="float"||fe.dataType==="decimal"||fe.dataType==="currency")return"metrics";const qe=Ar(fe.dataType);return["date","string","boolean"].includes(qe)?"dimensions":qe==="number"?"metrics":"dimensions"},ue=fe=>{const qe=fe.filter(Z);return i==="all"?qe:qe.filter(at=>ie(at)===i)},le=i==="all"?te:te.filter(fe=>ie(fe)===i),we=L?[..._,...T]:[],se=L?ue(we).sort(K):[],be=ue(E).sort(K).reduce((fe,qe)=>{const at=qe.qualifiedEntityName||"Other Fields";return fe[at]||(fe[at]={label:ox(qe.entityName),fields:[]}),fe[at].fields.push(qe),fe},{}),Me=w.useMemo(()=>Object.entries(be).map(([fe,qe])=>{const at=U.find($t=>$t.entityName===fe)||{entityName:fe,label:qe.label},Pt=fe===Bm?"Domain Calculated Fields":at.label||at.entityName;return{groupName:fe,groupLabel:Pt,fields:[...qe.fields].sort(K)}}).sort((fe,qe)=>fe.groupLabel.localeCompare(qe.groupLabel,void 0,{numeric:!0,sensitivity:"base"})),[be,U]),Pe=fe=>fe.id||`${fe.entityName}-${fe.qualifiedEntityName}-${fe.name}-${fe.role||"field"}`,ge=w.useMemo(()=>{const fe=new Map;return(L?k:E).forEach(at=>{fe.set(Pe(at),vA(at,{joinabilityMap:(Y==null?void 0:Y.joinabilityMap)||null,selectedFields:A,cardConfig:x,autoJoinMetadata:j}))}),fe},[L,k,E,Y==null?void 0:Y.joinabilityMap,A,x,j]),$e=L?[{key:"scope-calculated",label:"Calculated Fields",fields:se}].filter(fe=>fe.fields.length>0):[],J=[...$e.map(fe=>fe.key),...Me.map(fe=>fe.groupName)],ae=te.filter(fe=>ie(fe)==="dimensions").length,ve=te.filter(fe=>ie(fe)==="metrics").length,Ce=te.filter(fe=>ie(fe)==="calculated").length,Ee=te.length>0&&t!=="inline-filter",me=t==="inline-filter"?"w-full":"w-[290px]";if(P)return l.jsx("div",{className:X("flex h-full flex-col items-center justify-center py-8",me),children:l.jsx(_c,{size:"md",color:"muted","aria-label":"Loading data"})});if(O)return l.jsxs("div",{className:X("flex h-full flex-col items-center justify-center py-8",me),children:[l.jsx(rl,{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:O.message||"Failed to load column data"})]});if(!b||!b.selectedEntities||b.selectedEntities.length===0)return l.jsxs("div",{className:X("flex flex-col items-center justify-center py-8 text-center",me),children:[l.jsx(rl,{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 De=t==="inline-filter"?"px-3 pb-3":"px-6 pb-6",He=t==="inline-filter"?"overflow-hidden":"",et=fe=>fe!=null&&fe.startsWith("card-source-")?fe.replace("card-source-",""):fe,Te=(fe,qe,at)=>{const Pt=et(fe.id),$t=et(qe.id);return Pt&&$t&&Pt===$t?!0:!Pt||!$t||at!=null&&at.allowNameFallback?fe.name===qe.name&&fe.role===qe.role:!1},Ye=(fe,qe,at)=>fe.findIndex(Pt=>Te(Pt,qe,at)),nt=fe=>{if(!v)return fe;const qe=v.calculatedFields||[],at=Ye(qe,fe),Pt=at>=0&&qe[at].id!==fe.id?{...fe,id:qe[at].id}:fe,$t=at>=0?qe.map((Tn,or)=>or===at?Pt:Tn):[...qe,Pt];return N({calculatedFields:$t}),Pt},Re=(fe,qe,at,Pt)=>{var Tn;const $t=Ye(fe,at||qe,Pt);if($t>=0){const or=(Tn=fe[$t])==null?void 0:Tn.id,ss=or&&or!==qe.id?{...qe,id:or}:qe;return fe.map((Fs,Ki)=>Ki===$t?ss:Fs)}return[...fe,qe]},it=fe=>{if(fe.role==="metric")return G.find(qe=>Te(qe,fe));if(fe.role==="groupby")return B.find(qe=>Te(qe,fe))},ye=fe=>{var qe;return(qe=v==null?void 0:v.calculatedFields)==null?void 0:qe.find(at=>Te(at,fe))},tt=fe=>{if(fe.role==="metric"){S(y.id,{metricColumns:G.filter(qe=>!Te(qe,fe,{allowNameFallback:fe.fieldScope==="dashboard"}))});return}fe.role==="groupby"&&S(y.id,{groupByColumns:B.filter(qe=>!Te(qe,fe,{allowNameFallback:fe.fieldScope==="dashboard"}))})},Ue=fe=>{if(!v)return;const qe=(v.calculatedFields||[]).filter(at=>!Te(at,fe));N({calculatedFields:qe})},Qe=fe=>{if(!F)return;if(fe.fieldScope==="domain"){f(fe),m("domain"),g(fe.role==="metric"?"metric":"dimension"),u(!0);return}if(fe.fieldScope==="dashboard"){const at=ye(fe);if(!at)return;f(at),m("dashboard"),g(at.role==="metric"?"metric":"dimension"),u(!0);return}const qe=it(fe);qe&&(f(qe),m("card"),g(qe.role==="metric"?"metric":"dimension"),u(!0))},Et=fe=>{if(F&&fe.fieldScope!=="domain"){if(fe.fieldScope==="dashboard"){Ue(fe),tt(fe);return}tt(fe)}},Oe=fe=>{if(!F)return null;const qe=fe.fieldScope==="domain";return l.jsxs(ah,{children:[l.jsx(lh,{asChild:!0,children:l.jsx(re,{variant:"ghost",size:"icon",className:"h-6 w-6","aria-label":"Calculated field actions",children:l.jsx(nB,{className:"h-4 w-4"})})}),l.jsxs(Yu,{align:"end",className:"w-40",children:[l.jsx(Ro,{onClick:()=>Qe(fe),children:"Edit"}),l.jsx(Ro,{disabled:qe,onClick:()=>Et(fe),children:"Delete"})]})]})};return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:X("mt-2 flex h-full w-full grow flex-col gap-2",De,He),children:[l.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[I.length>0&&l.jsxs("div",{className:"relative",children:[l.jsx(zo,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),l.jsx(Ln,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:s,onChange:fe=>o(fe.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(Vt,{className:"size-3.5"})})]}),Ee&&l.jsx(Os,{defaultValue:"all",value:i,onValueChange:fe=>a(fe),className:"mb-4",children:l.jsxs(ws,{className:"grid h-9 w-full grid-cols-4",children:[l.jsxs(pn,{value:"all",className:"text-xs",children:["All",l.jsx("span",{className:"ml-2 text-xs font-semibold",children:te.length})]}),l.jsxs(pn,{value:"dimensions",className:"text-xs",children:[l.jsx(aC,{className:"size-4 shrink-0"}),l.jsx("span",{className:"ml-2 text-xs font-semibold",children:ae})]}),l.jsxs(pn,{value:"metrics",className:"text-xs",children:[l.jsx(kp,{className:"size-4 shrink-0"}),l.jsx("span",{className:"ml-2 text-xs font-semibold",children:ve})]}),l.jsxs(pn,{value:"calculated",className:"text-xs",children:[l.jsx(TI,{className:"size-4 shrink-0"}),l.jsx("span",{className:"ml-2 text-xs font-semibold",children:Ce})]})]})}),t==="editor"&&i==="calculated"&&F&&l.jsx("div",{className:"flex items-center justify-end gap-2",children:l.jsxs(re,{size:"sm",variant:"outline",className:"w-full",onClick:()=>{f(null),m("card"),g("dimension"),u(!0)},children:[l.jsx(Rr,{className:"mr-2 h-3.5 w-3.5"}),"Add calculated field"]})})]}),l.jsxs(kl,{className:"min-h-0 flex-1",children:[l.jsxs(Hx,{type:"multiple",defaultValue:J,className:"space-y-2",children:[$e.map(fe=>l.jsxs(ku,{value:fe.key,className:"border-none",children:[l.jsx(Eu,{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:fe.label}),l.jsx(st,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:fe.fields.length})]})}),l.jsx(_u,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:fe.fields.map(qe=>{const at=ge.get(Pe(qe)),Pt=t==="editor"&&i==="calculated";return l.jsx(h9,{field:qe,context:t,fieldState:at,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0,actions:Pt?Oe(qe):void 0},qe.id)})})})]},fe.key)),Me.map(({groupName:fe,groupLabel:qe,fields:at})=>l.jsxs(ku,{value:fe,className:"border-none",children:[l.jsx(Eu,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{title:qe,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:qe}),l.jsx(st,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:at.length})]})}),l.jsx(_u,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:at.map(Pt=>{const $t=ge.get(Pe(Pt));return l.jsx(h9,{field:Pt,context:t,fieldState:$t,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0},Pt.id)})})})]},fe))]}),I.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"})]}),I.length>0&&le.length===0&&l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),l.jsx(Li,{orientation:"horizontal"}),l.jsx(Li,{orientation:"vertical"})]})]}),l.jsx(_oe,{open:c,onOpenChange:fe=>{u(fe),fe||(f(null),m("card"))},availableFields:k,existingField:d??void 0,existingFieldScope:h,initialFieldType:p,onSave:fe=>{if(fe.role==="metric"){if(d&&h==="card"){S(y.id,{metricColumns:Re(G,fe,d)});return}S(y.id,{metricColumns:Re(G,fe)});return}if(d&&h==="card"){S(y.id,{groupByColumns:Re(B,fe,d)});return}S(y.id,{groupByColumns:Re(B,fe)})},onSaveToDashboard:fe=>{const qe=!!(d&&h==="dashboard"),at=qe?d:void 0;if(fe.role==="metric"){const $t=nt(fe);S(y.id,{metricColumns:Re(G,$t,at,{allowNameFallback:qe})});return}const Pt=nt(fe);S(y.id,{groupByColumns:Re(B,Pt,at,{allowNameFallback:qe})})},cardId:y.id,onPromoteMetricToDomain:$?z:void 0,onPromoteDimensionToDomain:$?q:void 0,domainId:$})]})}),Ioe=w.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(Moe,{context:t})," "]})});function Doe(){const e=Le(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=vr();w.useEffect(()=>{var m;if(!e)return;const{tableName:i,schemaName:a,databaseName:c,connectionId:u}=XO(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 aot(){Doe();const e=Q(c=>c.selectedSheetId),t=Q(c=>c.selectedFrameId),n=Q(c=>c.dashboard),r=Q(c=>c.actions.getSelectedFrame),{setSelectedFrameId:s}=un(),{setCard:o}=vr(),i=Le(c=>c.card.dataSource);return w.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 lot(){const e=Q(o=>o.dashboard.filterLayout),{setFilterLayout:t}=un(),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(Is,{children:[l.jsx(Ds,{asChild:!0,children:l.jsx(re,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0","aria-label":"Filter display settings",children:l.jsx(hc,{className:"h-4 w-4"})})}),l.jsx(As,{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(Ts,{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(Cn,{value:"canvas",id:"canvas",className:"mt-0.5"}),l.jsxs("div",{className:"grid gap-0.5",children:[l.jsx(de,{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(Cn,{value:"toolbar",id:"toolbar",className:"mt-0.5"}),l.jsxs("div",{className:"grid gap-0.5",children:[l.jsx(de,{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(wn,{id:"wrap",checked:r,onCheckedChange:o=>t({toolbarWrap:o===!0})}),l.jsx(de,{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(wn,{id:"download",checked:s,onCheckedChange:o=>t({showDownloadButton:o===!0})}),l.jsx(de,{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 cot(){const e=Q(n=>n.actions.setShowFilters),{hasEntities:t}=aot();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(de,{className:"px-2 text-base",children:"Dashboard Filters"}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(lot,{}),l.jsx(re,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:l.jsx(Jee,{})})]})]}),!t&&l.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[l.jsx(rl,{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(k0,{collisionDetection:C0,children:l.jsx(E0,{items:[],strategy:rO,children:l.jsx(Ioe,{context:"filter"})})})})]})}function uot(){const e=Q(r=>r.dashboard.filters),t=Q(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?l.jsx("div",{className:X("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>l.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[l.jsx(ZP,{filter:r}),l.jsx(hg,{filter:r})]},r.id))}):null}function dot(){const e=Q(r=>r.showFilters),t=Q(r=>r.isVisualEditing),n=Q(r=>r.isDashboardEditing);return l.jsxs("div",{role:"dashboard-plus-main",className:X("",{"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(uot,{}),l.jsx(moe,{})]}),e&&l.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:l.jsx(cot,{})})]})}const fot=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-BcpwRqRu.js"))),hot=w.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-B-qAacmt.js"))),mot=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-F8qwUIWM.js"))),pot=w.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-cwMyqyn1.js")).then(e=>({default:e.ResourceManagementPanel})));function got({showControls:e=!1,showFooter:t=!0,...n}){const r=Q(c=>c.isDashboardPanelOpen),s=Q(c=>c.isVisualEditing),o=Q(c=>c.showDashboardJSON),i=Q(c=>c.actions.setIsDashboardPanelOpen),{preferences:a}=n;return l.jsx(Na,{FallbackComponent:BN,children:l.jsxs(_I,{dashboardProps:n,children:[l.jsx(spe,{}),l.jsx(GO,{componentType:"surfboard",componentId:n.id}),l.jsx(YO,{children:l.jsxs(poe,{preferences:a,children:[o&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(mot,{})}),l.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(fot,{})}),l.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(pot,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),l.jsx("div",{className:"flex min-w-0 flex-1",children:l.jsxs(KA,{...n,type:"dashboard",children:[s&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(hot,{})}),l.jsx(dot,{})]})})]})]})]})})]})})}const Aoe=D.forwardRef(({className:e,...t},n)=>l.jsx(T0,{className:X("peer inline-flex h-[22px] w-[36px] shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:n,children:l.jsx(oO,{className:X("pointer-events-none block size-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));Aoe.displayName=T0.displayName;var bot=Object.defineProperty,xot=(e,t,n)=>t in e?bot(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,pw=(e,t,n)=>xot(e,typeof t!="symbol"?t+"":t,n);const yot={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},vot={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}},wot={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function Sot(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function Roe(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const Cot={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=Roe(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},Not={stringify:e=>`${e}`,parse:e=>parseFloat(e)},jot={stringify:e=>e,parse:e=>e},ME={string:jot,number:Not,boolean:yot,function:vot,method:Cot,json:wot},Xg=Symbol.for("r2wc.render"),gw=Symbol.for("r2wc.connected"),Dd=Symbol.for("r2wc.context"),Yo=Symbol.for("r2wc.props");function kot(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=Sot(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(),pw(this,o,!0),pw(this,s),pw(this,r,{}),pw(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[Yo].container=this.container;for(const p of i){const g=d[p],b=this.getAttribute(g),x=c[p],y=x?ME[x]:null;if(x==="method"){const v=Roe(g);Object.defineProperty(this[Yo].container,v,{enumerable:!0,configurable:!0,get(){return this[Yo][v]},set(S){this[Yo][v]=S,this[Xg]()}}),this[Yo][p]=y.parse(b,g,this)}y!=null&&y.parse&&b&&(this[Yo][p]=y.parse(b,g,this))}for(const p of a)this[Yo][p]=g=>{const b=p.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[p]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[gw]=!0,this[Xg]()}disconnectedCallback(){this[gw]=!1,this[Dd]&&n.unmount(this[Dd]),delete this[Dd]}attributeChangedCallback(p,g,b){const x=f[p],y=c[x],v=y?ME[y]:null;x in c&&v!=null&&v.parse&&b&&(this[Yo][x]=v.parse(b,p,this),this[Xg]())}[(o=gw,s=Dd,r=Yo,Xg)](){this[gw]&&(this[Dd]?n.update(this[Dd],this[Yo]):this[Dd]=n.mount(this.container,e,this[Yo]))}}for(const m of i){const p=d[m],g=c[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[Yo][m]},set(b){this[Yo][m]=b;const x=g?ME[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,p,this);this.getAttribute(p)!==y&&this.setAttribute(p,y)}else this[Xg]()}})}return h}function Eot(e,t,n){const r=Iie.createRoot(e),s=w.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function _ot({root:e,ReactComponent:t},n){const r=w.createElement(t,n);e.render(r)}function Tot({root:e}){e.unmount()}function Mot(e,t={}){return kot(e,t,{mount:Eot,update:_ot,unmount:Tot})}const Iot={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",currentTheme:"string",customCards:"json",customStyle:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},Dot=Mot(goe,{props:Iot});function v9(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Aot(e){if(Array.isArray(e))return e}function Rot(e,t,n){return(t=Bot(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Pot(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,s,o,i,a=[],c=!0,u=!1;try{if(o=(n=n.call(e)).next,t!==0)for(;!(c=(r=o.call(n)).done)&&(a.push(r.value),a.length!==t);c=!0);}catch(d){u=!0,s=d}finally{try{if(!c&&n.return!=null&&(i=n.return(),Object(i)!==i))return}finally{if(u)throw s}}return a}}function Oot(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
1100
1100
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function w9(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function S9(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?w9(Object(n),!0).forEach(function(r){Rot(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):w9(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function Fot(e,t){if(e==null)return{};var n,r,s=$ot(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function $ot(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function Lot(e,t){return Aot(e)||Pot(e,t)||Vot(e,t)||Oot()}function zot(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Bot(e){var t=zot(e,"string");return typeof t=="symbol"?t:t+""}function Vot(e,t){if(e){if(typeof e=="string")return v9(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?v9(e,t):void 0}}function Uot(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function C9(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function N9(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?C9(Object(n),!0).forEach(function(r){Uot(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):C9(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function Hot(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(r){return t.reduceRight(function(s,o){return o(s)},r)}}function kb(e){return function t(){for(var n=this,r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return s.length>=e.length?e.apply(this,s):function(){for(var i=arguments.length,a=new Array(i),c=0;c<i;c++)a[c]=arguments[c];return t.apply(n,[].concat(s,a))}}}function WS(e){return{}.toString.call(e).includes("Object")}function Wot(e){return!Object.keys(e).length}function ay(e){return typeof e=="function"}function qot(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Yot(e,t){return WS(t)||Mu("changeType"),Object.keys(t).some(function(n){return!qot(e,n)})&&Mu("changeField"),t}function Got(e){ay(e)||Mu("selectorType")}function Kot(e){ay(e)||WS(e)||Mu("handlerType"),WS(e)&&Object.values(e).some(function(t){return!ay(t)})&&Mu("handlersType")}function Zot(e){e||Mu("initialIsRequired"),WS(e)||Mu("initialType"),Wot(e)&&Mu("initialContent")}function Xot(e,t){throw new Error(e[t]||e.default)}var Qot={initialIsRequired:"initial state is required",initialType:"initial state should be an object",initialContent:"initial state shouldn't be an empty object",handlerType:"handler should be an object or a function",handlersType:"all handlers should be a functions",selectorType:"selector should be a function",changeType:"provided value of changes should be an object",changeField:'it seams you want to change a field in the state which is not specified in the "initial" state',default:"an unknown error accured in `state-local` package"},Mu=kb(Xot)(Qot),bw={changes:Yot,selector:Got,handler:Kot,initial:Zot};function Jot(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};bw.initial(e),bw.handler(t);var n={current:e},r=kb(nit)(n,t),s=kb(tit)(n),o=kb(bw.changes)(e),i=kb(eit)(n);function a(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(d){return d};return bw.selector(u),u(n.current)}function c(u){Hot(r,s,o,i)(u)}return[a,c]}function eit(e,t){return ay(t)?t(e.current):t}function tit(e,t){return e.current=N9(N9({},e.current),t),t}function nit(e,t,n){return ay(t)?t(e.current):Object.keys(n).forEach(function(r){var s;return(s=t[r])===null||s===void 0?void 0:s.call(t,e.current[r])}),n}var rit={create:Jot},sit={paths:{vs:"https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs"}};function oit(e){return function t(){for(var n=this,r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return s.length>=e.length?e.apply(this,s):function(){for(var i=arguments.length,a=new Array(i),c=0;c<i;c++)a[c]=arguments[c];return t.apply(n,[].concat(s,a))}}}function iit(e){return{}.toString.call(e).includes("Object")}function ait(e){return e||j9("configIsRequired"),iit(e)||j9("configType"),e.urls?(lit(),{paths:{vs:e.urls.monacoBase}}):e}function lit(){console.warn(Poe.deprecation)}function cit(e,t){throw new Error(e[t]||e.default)}var Poe={configIsRequired:"the configuration object is required",configType:"the configuration object should be an object",default:"an unknown error accured in `@monaco-editor/loader` package",deprecation:`Deprecation warning!
|
|
1101
1101
|
You are using deprecated way of configuration.
|
|
1102
1102
|
|