react-semaphor 0.1.180 → 0.1.181

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/dist/chunks/{dashboard-controls-CS3pAVZi.js → dashboard-controls-aSc1zv9H.js} +4 -4
  2. package/dist/chunks/{dashboard-controls-Baw7eUyM.js → dashboard-controls-uTcIgnwr.js} +1 -1
  3. package/dist/chunks/{dashboard-json-ClalWYi4.js → dashboard-json-4ck1yXt7.js} +1 -1
  4. package/dist/chunks/{dashboard-json-Cz4bNnCC.js → dashboard-json-Yy1p-xw4.js} +1 -1
  5. package/dist/chunks/{edit-dashboard-visual-BMElXt-n.js → edit-dashboard-visual-DEedEtg4.js} +1 -1
  6. package/dist/chunks/{edit-dashboard-visual-DFJ5FJ7y.js → edit-dashboard-visual-K-yosg4h.js} +2 -2
  7. package/dist/chunks/{editor-action-buttons-MtNYw1Bb.js → editor-action-buttons-D5zidD5p.js} +2 -2
  8. package/dist/chunks/{editor-action-buttons-DVWnnC_r.js → editor-action-buttons-WLwpPoSo.js} +1 -1
  9. package/dist/chunks/{index-CAeKp6K8.js → index-TF2KfLGc.js} +4 -4
  10. package/dist/chunks/{index-CfPKTeUk.js → index-tt1rwTc8.js} +1 -1
  11. package/dist/chunks/{notification-bell-2dZI5OV0.js → notification-bell-CWYeyuXL.js} +2 -2
  12. package/dist/chunks/{notification-bell-YZ8VqdwA.js → notification-bell-DNxWG0YY.js} +119 -102
  13. package/dist/chunks/{resource-management-panel-Buhi-kvP.js → resource-management-panel-CihSUDmt.js} +1 -1
  14. package/dist/chunks/{resource-management-panel-pxL28GXq.js → resource-management-panel-Dda1VGgq.js} +3 -3
  15. package/dist/chunks/{use-role-aware-display-preferences-B_i2f9tn.js → use-role-aware-display-preferences-CpROR4Gx.js} +1 -1
  16. package/dist/chunks/{use-role-aware-display-preferences-JljRcjrP.js → use-role-aware-display-preferences-DgsVnRKz.js} +1 -1
  17. package/dist/chunks/{use-visual-utils-DPEHcmFT.js → use-visual-utils-BkmyEMSD.js} +1 -1
  18. package/dist/chunks/{use-visual-utils-D3HjbsKO.js → use-visual-utils-Dwmrgj6E.js} +1 -1
  19. package/dist/dashboard/index.cjs +1 -1
  20. package/dist/dashboard/index.js +1 -1
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.js +5 -5
  23. package/dist/surfboard/index.cjs +1 -1
  24. package/dist/surfboard/index.js +1 -1
  25. package/package.json +1 -1
@@ -1069,7 +1069,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
1069
1069
 
1070
1070
  `)},flush(e){e.enqueue(`data: [DONE]
1071
1071
 
1072
- `)}})}});var RKe=NGe(()=>xJ(si([Kn({type:Rt("text-start"),id:st(),providerMetadata:cr.optional()}),Kn({type:Rt("text-delta"),id:st(),delta:st(),providerMetadata:cr.optional()}),Kn({type:Rt("text-end"),id:st(),providerMetadata:cr.optional()}),Kn({type:Rt("error"),errorText:st()}),Kn({type:Rt("tool-input-start"),toolCallId:st(),toolName:st(),providerExecuted:qs().optional(),dynamic:qs().optional()}),Kn({type:Rt("tool-input-delta"),toolCallId:st(),inputTextDelta:st()}),Kn({type:Rt("tool-input-available"),toolCallId:st(),toolName:st(),input:na(),providerExecuted:qs().optional(),providerMetadata:cr.optional(),dynamic:qs().optional()}),Kn({type:Rt("tool-input-error"),toolCallId:st(),toolName:st(),input:na(),providerExecuted:qs().optional(),providerMetadata:cr.optional(),dynamic:qs().optional(),errorText:st()}),Kn({type:Rt("tool-output-available"),toolCallId:st(),output:na(),providerExecuted:qs().optional(),dynamic:qs().optional(),preliminary:qs().optional()}),Kn({type:Rt("tool-output-error"),toolCallId:st(),errorText:st(),providerExecuted:qs().optional(),dynamic:qs().optional()}),Kn({type:Rt("reasoning-start"),id:st(),providerMetadata:cr.optional()}),Kn({type:Rt("reasoning-delta"),id:st(),delta:st(),providerMetadata:cr.optional()}),Kn({type:Rt("reasoning-end"),id:st(),providerMetadata:cr.optional()}),Kn({type:Rt("source-url"),sourceId:st(),url:st(),title:st().optional(),providerMetadata:cr.optional()}),Kn({type:Rt("source-document"),sourceId:st(),mediaType:st(),title:st(),filename:st().optional(),providerMetadata:cr.optional()}),Kn({type:Rt("file"),url:st(),mediaType:st(),providerMetadata:cr.optional()}),Kn({type:hJ(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:st().optional(),data:na(),transient:qs().optional()}),Kn({type:Rt("start-step")}),Kn({type:Rt("finish-step")}),Kn({type:Rt("start"),messageId:st().optional(),messageMetadata:na().optional()}),Kn({type:Rt("finish"),finishReason:uJ(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:na().optional()}),Kn({type:Rt("abort")}),Kn({type:Rt("message-metadata"),messageMetadata:na()})])));function IKe(e){return e.type.startsWith("data-")}function kJ(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]=kJ(o,s):n[r]=s}return n}function AKe(e){const t=["ROOT"];let n=-1,r=null;function s(l,u,d){switch(l){case'"':{n=u,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,r=u,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function o(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":s(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=l,t.pop();break}default:{n=l,s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l)):n=l;break}}}let a=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?a+="true".slice(d.length):"false".startsWith(d)?a+="false".slice(d.length):"null".startsWith(d)&&(a+="null".slice(d.length))}}return a}async function EJ(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Ww({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Ww({text:AKe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function lv(e){return e.type.startsWith("tool-")}function PKe(e){return e.type==="dynamic-tool"}function u_(e){return lv(e)||PKe(e)}function CL(e){return e.type.split("-").slice(1).join("-")}function OKe({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 FKe({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await r(async({state:u,write:d})=>{var f,h,p,m;function g(w){const S=u.message.parts.filter(lv).find(N=>N.toolCallId===w);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function b(w){const S=u.message.parts.filter(N=>N.type==="dynamic-tool").find(N=>N.toolCallId===w);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function x(w){var j;const S=u.message.parts.find(_=>lv(_)&&_.toolCallId===w.toolCallId),N=w,E=S;S!=null?(S.state=w.state,E.input=N.input,E.output=N.output,E.errorText=N.errorText,E.rawInput=N.rawInput,E.preliminary=N.preliminary,E.providerExecuted=(j=N.providerExecuted)!=null?j:S.providerExecuted,N.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=N.providerMetadata)):u.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.state,input:N.input,output:N.output,rawInput:N.rawInput,errorText:N.errorText,providerExecuted:N.providerExecuted,preliminary:N.preliminary,...N.providerMetadata!=null?{callProviderMetadata:N.providerMetadata}:{}})}function y(w){var j,S;const N=u.message.parts.find(k=>k.type==="dynamic-tool"&&k.toolCallId===w.toolCallId),E=w,_=N;N!=null?(N.state=w.state,_.toolName=w.toolName,_.input=E.input,_.output=E.output,_.errorText=E.errorText,_.rawInput=(j=E.rawInput)!=null?j:_.rawInput,_.preliminary=E.preliminary,_.providerExecuted=(S=E.providerExecuted)!=null?S:N.providerExecuted,E.providerMetadata!=null&&N.state==="input-available"&&(N.callProviderMetadata=E.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:w.toolName,toolCallId:w.toolCallId,state:w.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(w){if(w!=null){const j=u.message.metadata!=null?kJ(u.message.metadata,w):w;t!=null&&await xL({value:j,schema:t}),u.message.metadata=j}}switch(a.type){case"text-start":{const w={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=w,u.message.parts.push(w),d();break}case"text-delta":{const w=u.activeTextParts[a.id];w.text+=a.delta,w.providerMetadata=(f=a.providerMetadata)!=null?f:w.providerMetadata,d();break}case"text-end":{const w=u.activeTextParts[a.id];w.state="done",w.providerMetadata=(h=a.providerMetadata)!=null?h:w.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const w={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=w,u.message.parts.push(w),d();break}case"reasoning-delta":{const w=u.activeReasoningParts[a.id];w.text+=a.delta,w.providerMetadata=(p=a.providerMetadata)!=null?p:w.providerMetadata,d();break}case"reasoning-end":{const w=u.activeReasoningParts[a.id];w.providerMetadata=(m=a.providerMetadata)!=null?m:w.providerMetadata,w.state="done",delete u.activeReasoningParts[a.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),d();break}case"tool-input-start":{const w=u.message.parts.filter(lv);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:w.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const w=u.partialToolCalls[a.toolCallId];w.text+=a.inputTextDelta;const{value:j}=await EJ(w.text);w.dynamic?y({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:j}):x({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:j}),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 w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-available",input:w.input,output:a.output,preliminary:a.preliminary})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:CL(w),state:"output-available",input:w.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-error",input:w.input,errorText:a.errorText,providerExecuted:a.providerExecuted})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:CL(w),state:"output-error",input:w.input,rawInput:w.rawInput,errorText:a.errorText,providerExecuted:a.providerExecuted})}d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{a.messageId!=null&&(u.message.id=a.messageId),await v(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&d();break}case"finish":{a.finishReason!=null&&(u.finishReason=a.finishReason),await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"message-metadata":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"error":{s==null||s(new Error(a.errorText));break}default:if(IKe(a)){(n==null?void 0:n[a.type])!=null&&await xL({value:a.data,schema:n[a.type]});const w=a;if(w.transient){i==null||i(w);break}const j=w.id!=null?u.message.parts.find(S=>w.type===S.type&&w.id===S.id):void 0;j!=null?j.data=w.data:u.message.parts.push(w),i==null||i(w),d()}}l.enqueue(a)})}}))}async function $Ke({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()}}sy({prefix:"aitxt",size:24});sy({prefix:"aiobj",size:24});var LKe=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()})}};sy({prefix:"aiobj",size:24});var zKe={};SKe(zKe,{object:()=>VKe,text:()=>BKe});var BKe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),VKe=({schema:e})=>{const t=vKe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await EJ(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 Ww({text:n});if(!s.success)throw new wL({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 FI({value:s.value,schema:t});if(!o.success)throw new wL({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 HKe(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async t=>{const{name:n,type:r}=t,s=await new Promise((o,i)=>{const a=new FileReader;a.onload=l=>{var u;o((u=l.target)==null?void 0:u.result)},a.onerror=l=>i(l),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var UKe=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 Ef(this.body),l=await Ef(this.headers),u=await Ef(this.credentials),d={...Ru(l),...Ru(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,p=(f==null?void 0:f.headers)!==void 0?Ru(f.headers):d,m=(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:gL({"Content-Type":"application/json",...p},`ai-sdk/${SL}`,mL()),body:JSON.stringify(m),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 Ef(this.body),a=await Ef(this.headers),l=await Ef(this.credentials),u={...Ru(a),...Ru(e.headers)},d=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:u,credentials:l,requestMetadata:e.metadata})),f=(n=d==null?void 0:d.api)!=null?n:`${this.api}/${e.chatId}/stream`,h=(d==null?void 0:d.headers)!==void 0?Ru(d.headers):u,p=(r=d==null?void 0:d.credentials)!=null?r:l,g=await((s=this.fetch)!=null?s:globalThis.fetch)(f,{method:"GET",headers:gL(h,`ai-sdk/${SL}`,mL()),credentials:p});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)}},LI=class extends UKe{constructor(e={}){super(e)}processResponseStream(e){return _Ge({stream:e,schema:RKe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},WKe=class{constructor({generateId:e=xGe,id:t=e(),transport:n=new LI,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new LKe,this.sendMessage=async(f,h)=>{var p,m,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(p=this.lastMessage)==null?void 0:p.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await HKe(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:(m=x.role)!=null?m:"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 p=f==null?this.state.messages.length-1:this.state.messages.findIndex(m=>m.id===f);if(p===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[p].role==="assistant"?p:p+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:p,output:m,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(w=>u_(w)&&w.toolCallId===p?{...w,state:f,output:m,errorText:g}:w)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(w=>u_(w)&&w.toolCallId===p?{...w,state:f,output:m,errorText:g}:w)),this.status!=="streaming"&&this.status!=="submitted"&&((b=this.sendAutomaticallyWhen)!=null&&b.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(x=this.lastMessage)==null?void 0:x.id})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=l,this.onData=u,this.sendAutomaticallyWhen=d}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:s}){var o,i,a,l;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;let d=!1,f=!1,h=!1;try{const p={state:OKe({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};p.abortController.signal.addEventListener("abort",()=>{d=!0}),this.activeResponse=p;let m;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}m=b}else m=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:p.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const g=b=>this.jobExecutor.run(()=>b({state:p.state,write:()=>{var x;this.setStatus({status:"streaming"}),p.state.message.id===((x=this.lastMessage)==null?void 0:x.id)?this.state.replaceMessage(this.state.messages.length-1,p.state.message):this.state.pushMessage(p.state.message)}}));await $Ke({stream:FKe({stream:m,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(p){if(d||p.name==="AbortError")return d=!0,this.setStatus({status:"ready"}),null;h=!0,p instanceof TypeError&&(p.message.toLowerCase().includes("fetch")||p.message.toLowerCase().includes("network"))&&(f=!0),this.onError&&p instanceof Error&&this.onError(p),this.setStatus({status:"error",error:p})}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(p){console.error(p)}this.activeResponse=void 0}(a=this.sendAutomaticallyWhen)!=null&&a.call(this,{messages:this.state.messages})&&!h&&await this.makeRequest({trigger:"submit-message",messageId:(l=this.lastMessage)==null?void 0:l.id,metadata:t,headers:n,body:r})}};function qKe({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(u_).filter(s=>!s.providerExecuted);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function YKe(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...o){clearTimeout(n);const i=Date.now(),a=i-r,l=t-a;l<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},l)}}var GKe=YKe;const KKe=Ud(GKe);var _J=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Fn=(e,t,n)=>(_J(e,t,"read from private field"),n?n.call(e):t.get(e)),Xi=(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)},Jl=(e,t,n,r)=>(_J(e,t,"write to private field"),t.set(e,n),n);function ZKe(e,t){return t!=null?KKe(e,t):e}var Po,cv,uv,Jm,eg,tg,Rf,d_,f_,XKe=class{constructor(e=[]){Xi(this,Po,void 0),Xi(this,cv,"ready"),Xi(this,uv,void 0),Xi(this,Jm,new Set),Xi(this,eg,new Set),Xi(this,tg,new Set),this.pushMessage=t=>{Jl(this,Po,Fn(this,Po).concat(t)),Fn(this,Rf).call(this)},this.popMessage=()=>{Jl(this,Po,Fn(this,Po).slice(0,-1)),Fn(this,Rf).call(this)},this.replaceMessage=(t,n)=>{Jl(this,Po,[...Fn(this,Po).slice(0,t),this.snapshot(n),...Fn(this,Po).slice(t+1)]),Fn(this,Rf).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?ZKe(t,n):t;return Fn(this,Jm).add(r),()=>{Fn(this,Jm).delete(r)}},this["~registerStatusCallback"]=t=>(Fn(this,eg).add(t),()=>{Fn(this,eg).delete(t)}),this["~registerErrorCallback"]=t=>(Fn(this,tg).add(t),()=>{Fn(this,tg).delete(t)}),Xi(this,Rf,()=>{Fn(this,Jm).forEach(t=>t())}),Xi(this,d_,()=>{Fn(this,eg).forEach(t=>t())}),Xi(this,f_,()=>{Fn(this,tg).forEach(t=>t())}),Jl(this,Po,e)}get status(){return Fn(this,cv)}set status(e){Jl(this,cv,e),Fn(this,d_).call(this)}get error(){return Fn(this,uv)}set error(e){Jl(this,uv,e),Fn(this,f_).call(this)}get messages(){return Fn(this,Po)}set messages(e){Jl(this,Po,[...e]),Fn(this,Rf).call(this)}};Po=new WeakMap;cv=new WeakMap;uv=new WeakMap;Jm=new WeakMap;eg=new WeakMap;tg=new WeakMap;Rf=new WeakMap;d_=new WeakMap;f_=new WeakMap;var If,jL=class extends WKe{constructor({messages:e,...t}){const n=new XKe(e);super({...t,state:n}),Xi(this,If,void 0),this["~registerMessagesCallback"]=(r,s)=>Fn(this,If)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>Fn(this,If)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>Fn(this,If)["~registerErrorCallback"](r),Jl(this,If,n)}};If=new WeakMap;function MJ({experimental_throttle:e,resume:t=!1,...n}={}){const r=C.useRef("chat"in n?n.chat:new jL(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new jL(n));const o="id"in n?n.id:null,i=C.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=C.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),l=C.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=C.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=C.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return C.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:a,setMessages:d,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:u,resumeStream:r.current.resumeStream,status:l,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput}}function QKe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function JKe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function eZe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function tZe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function TJ(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:tZe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function DJ(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 nZe(){var b;const{authToken:e,tokenProps:t}=Ge(),n=X(x=>x.dashboard.aiScopeTables),r=(b=i1().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=MJ({transport:new LI({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=Ui.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:_W(x)}})}),onToolCall:p,sendAutomaticallyWhen:qKe,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 p({toolCall:x}){if(x.toolName==="getCurrentTableScope"&&u({tool:x.toolName,toolCallId:x.toolCallId,output:{tables:TJ(n||[])}}),x.toolName==="getDashboardContext"){const y=X.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const m=!["ready","error"].includes(l),g=DJ(d);return{sendMessage:s,regenerate:a,isLoading:m,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function RJ(){var u;const{authToken:e,tokenProps:t}=Ge(),n=(u=i1().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=pn({queryKey:["assistant-profile",n],queryFn:()=>qn(`${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 IJ({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:c.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[c.jsxs("div",{className:"mb-3 flex items-center",children:[c.jsx(lz,{className:"mr-2 h-4 w-4 text-muted-foreground"}),c.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),c.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>c.jsx(se,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function qw(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(uM,{className:r});case"view":return c.jsx(Pc,{className:r});case"materialized view":return c.jsx(Bse,{className:r});case"model":return c.jsx(f1,{className:r});case"file":return c.jsx(Ai,{className:r});case"dataset":return c.jsx(vl,{className:r});case"upload":return c.jsx(pM,{className:r});case"url":return c.jsx(pz,{className:r});default:return c.jsx(u1,{className:r})}}const AJ=D.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(Vi,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(Cs.Input,{ref:n,className:K("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})]}));AJ.displayName=Cs.Input.displayName;const A0=e=>e.label||(e==null?void 0:e.name),NL=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function rZe({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:u}){const{tokenProps:d}=Ge(),f=(d==null?void 0:d.type)==="dashboard",[h,p]=C.useState(""),[m,g]=C.useState(""),b=s.filter(S=>{if(!h)return!0;const N=A0(S).toLowerCase(),E=NL(S).toLowerCase(),_=h.toLowerCase();return N.includes(_)||E.includes(_)});C.useEffect(()=>{e||(p(""),g(""))},[e]),C.useEffect(()=>{b.length>0&&!m&&g(A0(b[0]))},[b,m]);const x=()=>{if(!m)return;const S=b.find(N=>A0(N)===m);S&&(o.some(E=>"id"in S&&"id"in E?S.id===E.id:S.name===E.name&&S.connectionId===E.connectionId)||t(S),i(S),r())},y=S=>{(S.key==="Tab"||S.key==="Enter")&&(S.preventDefault(),x())};if(!e)return null;const v=S=>o.some(N=>"id"in S&&"id"in N?S.id===N.id:S.name===N.name&&S.connectionId===N.connectionId),w=o.length===s.length,j=o.length>0;return c.jsx(c.Fragment,{children:c.jsxs(Ip,{shouldFilter:!1,value:m,onValueChange:g,onKeyDown:y,children:[s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[c.jsx(AJ,{placeholder:"Search entities...",value:h,onValueChange:p,className:"flex-1 border-0",autoFocus:!0}),!f&&c.jsxs(se,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u==null||u()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[c.jsx(wr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[c.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(se,{onClick:S=>{S.preventDefault(),S.stopPropagation(),a==null||a()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},disabled:w,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),j&&c.jsxs(se,{onClick:S=>{S.preventDefault(),S.stopPropagation(),l==null||l()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[c.jsx(vt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),c.jsxs(Ap,{className:"min-h-60",children:[c.jsx(Pp,{children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[c.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&c.jsxs(se,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u==null||u()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[c.jsx(wr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx(Op,{children:b.map((S,N)=>{const E=v(S),_="id"in S?S.id:`${S.connectionId}-${S.name}`,k=A0(S);return c.jsxs(Fp,{value:k,onSelect:()=>{E?n==null||n(S):t(S)},onMouseDown:T=>{T.preventDefault(),T.stopPropagation()},className:K("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[c.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:qw(S.type)}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate font-medium",children:k}),c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:NL(S)})]}),E&&c.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:c.jsx(Mr,{className:"h-3 w-3 text-background"})})]},_)})})]})]})})}const h_=e=>e.name||e.name,sZe=e=>{const t=h_(e),n="description"in e?e.description:"",r=e.database||"",s=e.schema||"";return c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"font-medium",children:t}),n&&c.jsx("div",{className:"text-sm text-muted-foreground",children:n}),c.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,s&&` • Schema: ${s}`]})]})};function oZe({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r}){const[s,o]=C.useState(!1),i=e.length>0;e.length,t.length,e.length<t.length;const a=e.length>=3?e.slice(0,2):e,l=e.length>=3?e.slice(2):[],u=l.length>0;return c.jsx(Mn,{children:c.jsx("div",{className:"space-y-2",children:i&&c.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.map((d,f)=>{const h="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs(Xt,{children:[c.jsx(Qt,{asChild:!0,children:c.jsxs(Fe,{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:[qw(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:h_(d)}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(d),children:c.jsx(vt,{className:"h-3 w-3"})})]})}),c.jsx(tn,{side:"top",className:"max-w-xs",children:sZe(d)})]},h)}),u&&c.jsxs(Xt,{open:s,onOpenChange:o,children:[c.jsx(Qt,{asChild:!0,children:c.jsxs(Fe,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>o(!0),children:[c.jsx(Vse,{className:"h-3 w-3"}),c.jsxs("span",{className:"text-xs",children:[l.length," more"]}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(l),children:c.jsx(vt,{className:"h-3 w-3"})})]})}),c.jsx(tn,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),c.jsx("div",{className:"space-y-2",children:l.map(d=>{const f="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:qw(d.type,{size:"h-3 w-3"})}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate text-sm font-medium",children:h_(d)}),c.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),c.jsx(se,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(d),l.length===1&&o(!1)},children:c.jsx(vt,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function PJ(e){return e.type==="dataset"&&e.label||e.name}function iZe(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 aZe({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:c.jsxs("div",{className:"mb-4 space-y-2",children:[c.jsxs(ce,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),c.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:c.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>c.jsxs(Fe,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[c.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),PJ(n),c.jsx("button",{onClick:s=>{s.stopPropagation(),t(n)},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-0 transition-opacity hover:bg-red-100 group-hover:opacity-100",children:c.jsx(vt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function lZe(e){const{tokenProps:t}=Ge(),n=X(l=>l.authToken)||e;Me(l=>l.selectedConnectionId),Me(l=>{var u,d;return(d=(u=l==null?void 0:l.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=pn({queryKey:["semantic-domains"],queryFn:()=>qn(`${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 cZe(e,t){const{tokenProps:n}=Ge(),r=X(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:l}=pn({queryKey:["datasets",e],queryFn:()=>qn(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:o,error:l,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:l,refetchDatasets:s}}function uZe(e){var g,b;const{tokenProps:t}=Ge(),n=X(x=>x.authToken)||e,{connections:r}=Pa(e),s=Me(x=>{var y,v;return(v=(y=x==null?void 0:x.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(x=>x.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(x){return s&&x?!(x==="API"||x==="S3"):!1}const{data:d,isPending:f,error:h,refetch:p}=pn({queryKey:["databases",s],queryFn:()=>qn(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),m=(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:m||[],refetch:p,label:l}}function dZe(e){var g;const{tokenProps:t}=Ge(),n=X(b=>b.authToken)||e,{connections:r}=Pa(e),s=Me(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=Me(b=>{var x,y,v;return(v=(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(b=>b.id===s),a=i==null?void 0:i.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){return!(!s||(i==null?void 0:i.type)==="API"||(i==null?void 0:i.type)==="S3"||!o||!(a!=null&&a.path.includes("schema")))}const{data:d,isPending:f,error:h,refetch:p}=pn({queryKey:["schemas",s,o],queryFn:()=>qn(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),m=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:m||[],refetch:p,label:l}}function OJ(e){const{tokenProps:t}=Ge(),n=X(h=>h.authToken)||e,{connections:r}=Pa(e),s=Me(h=>{var p,m;return(m=(p=h==null?void 0:h.card)==null?void 0:p.dataSource)==null?void 0:m.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:l,error:u,refetch:d}=pn({queryKey:["dataModels",s],queryFn:()=>qn(`${t.apiServiceUrl}/v1/datamodels`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:i()}),f=a==null?void 0:a.datamodels.map(h=>({id:h.id,name:h.name,label:h.label,description:h.description,connectionId:s,dialect:h.dialect,connectionType:o==null?void 0:o.type,type:"model",database:h.database,schema:h.schema}));return{isPending:l,error:u,dataModels:f||[],refetch:d}}function fZe(){var j,S,N;const e=Me(E=>E.card.dataSource);Me(E=>E.actions.updateDirectSource);const t=Me(E=>E.actions.updateDataSource),[n,r]=C.useState(""),{selectedConnection:s,error:o}=Pa(),{databases:i,isPending:a,error:l,label:u}=uZe(),{schemas:d,isPending:f,error:h,label:p}=dZe(),{error:m}=OJ(),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=p==null?void 0:p.toLowerCase(),v=E=>{e&&t({...e,dbSelection:{database:E,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},w=E=>{var k;if(!((k=e==null?void 0:e.dbSelection)!=null&&k.database))return;const _=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{..._,schema:E},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return c.jsxs(c.Fragment,{children:[(o||l||h||m)&&c.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[c.jsx("div",{className:"flex items-center",children:c.jsxs("div",{className:"text-sm text-red-800",children:[c.jsx("strong",{children:"Error loading data:"}),c.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&c.jsxs("li",{children:["Connections: ",o]}),l&&c.jsxs("li",{children:[u,": ",l.message]}),h&&c.jsxs("li",{children:[p,": ",h.message]}),m&&c.jsxs("li",{children:["Data Models: ",m.message]})]})]})}),c.jsx(se,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),c.jsxs("div",{className:"space-y-4",children:[b&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:u}),c.jsxs(nt,{value:((j=e==null?void 0:e.dbSelection)==null?void 0:j.database)||"",onValueChange:v,disabled:a,children:[c.jsx(et,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[a&&c.jsx(an,{className:"h-4 w-4 animate-spin"}),c.jsx(ot,{placeholder:l?`Error loading ${x}`:a?`Loading ${x}...`:`Select ${x}...`})]})}),c.jsx(tt,{children:i.map(E=>c.jsx(be,{className:"hover:bg-muted",value:E.id,children:E.name},E.id))})]})]}),((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)&&g&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:p}),c.jsxs(nt,{value:((N=e==null?void 0:e.dbSelection)==null?void 0:N.schema)||"",onValueChange:w,disabled:f,children:[c.jsx(et,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[f&&c.jsx(an,{className:"h-4 w-4 animate-spin"}),c.jsx(ot,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),c.jsx(tt,{children:d.map(E=>c.jsx(be,{className:"hover:bg-muted",value:E.id,children:E.name},E.id))})]})]})]})]})}function hZe(){const e=Me(l=>l.card.dataSource),t=Me(l=>l.actions.updateDataSource),[n,r]=C.useState(!1),s=l=>{if(!l||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(l).map(f=>({id:`file-${Date.now()}-${Math.random()}`,name:f.name,type:"upload",connectionId:"default",connectionType:"none",label:f.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:f.name,file:f})),d=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...d,...u]})},o=l=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==l);t({...e,selectedEntities:u})},i=l=>{if(l===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(l)/Math.log(u));return Number.parseFloat((l/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Upload Files"}),c.jsxs("div",{className:`rounded-lg border-2 border-dashed p-6 text-center transition-colors ${n?"border-blue-400 bg-blue-50":"border-gray-300 hover:border-gray-400"}`,onDragOver:l=>{l.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:l=>{l.preventDefault(),r(!1),s(l.dataTransfer.files)},children:[c.jsx(pM,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),c.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),c.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:l=>s(l.target.files),accept:".csv,.json,.xlsx,.xls"}),c.jsx(se,{variant:"outline",size:"sm",onClick:()=>{var l;return(l=document.getElementById("file-upload"))==null?void 0:l.click()},children:"Select Files"}),c.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ce,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(l=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(Ai,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:l.originalName}),c.jsx("p",{className:"text-xs text-gray-500",children:l.file?i(l.file.size):""})]})]}),c.jsx(se,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(l.id),children:c.jsx(vt,{className:"h-3 w-3"})})]},l.id))})]})]})}function pZe(){const e=Me(f=>f.card.dataSource),t=Me(f=>f.actions.updateDataSource),[n,r]=C.useState(""),[s,o]=C.useState(""),[i,a]=C.useState("api"),l=()=>{if(!n.trim()||!s.trim()||!e)return;const f={id:`url-${Date.now()}-${Math.random()}`,name:n.trim(),type:"url",connectionId:"default",connectionType:"none",label:n.trim(),description:`URL source of type ${i}`,url:s.trim(),sourceType:i,originalName:n.trim()},h=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...h,f]}),r(""),o(""),a("api")},u=f=>{if(!e)return;const h=(e.selectedEntities||[]).filter(p=>p.id!==f);t({...e,selectedEntities:h})},d=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),c.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"Source Name"}),c.jsx(Nn,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"URL"}),c.jsx(Nn,{placeholder:"https://api.example.com/data",value:s,onChange:f=>o(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"Type"}),c.jsxs("select",{value:i,onChange:f=>a(f.target.value),className:"h-8 w-full rounded-md border border-gray-300 px-2 text-sm",children:[c.jsx("option",{value:"api",children:"API Endpoint"}),c.jsx("option",{value:"csv",children:"CSV File"}),c.jsx("option",{value:"json",children:"JSON File"})]})]}),c.jsxs(se,{onClick:l,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[c.jsx(wr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ce,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(u1,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),c.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),c.jsx(se,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:c.jsx(vt,{className:"h-3 w-3"})})]},f.id))})]})]})}function mZe(e,t){var y,v;const{tokenProps:n}=Ge(),r=X(w=>w.authToken)||t,{connections:s}=Pa(t),o=Me(w=>{var j,S;return(S=(j=w==null?void 0:w.card)==null?void 0:j.dataSource)==null?void 0:S.connectionId}),i=Me(w=>{var j,S,N;return(N=(S=(j=w==null?void 0:w.card)==null?void 0:j.dataSource)==null?void 0:S.dbSelection)==null?void 0:N.database}),a=Me(w=>{var j,S,N;return(N=(S=(j=w==null?void 0:w.card)==null?void 0:j.dataSource)==null?void 0:S.dbSelection)==null?void 0:N.schema}),l=s==null?void 0:s.find(w=>w.id===o),u=l==null?void 0:l.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){return o?(l==null?void 0:l.type)==="API"||(l==null?void 0:l.type)==="S3"?!0:!(!i||u!=null&&u.path.includes("schema")&&!a):!1}const{data:h,isPending:p,isLoading:m,error:g,refetch:b}=pn({queryKey:[e,o,i,a],queryFn:()=>qn(`${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(w=>{var j;return{connectionId:l==null?void 0:l.id,connectionType:l==null?void 0:l.type,dialect:l==null?void 0:l.dialect,type:e,dbObjectType:(j=w==null?void 0:w.table_type)==null?void 0:j.toLowerCase(),id:w[`${e}_name`],database:i,schema:a,name:w[`${e}_name`]}});return{isPending:p,isLoading:m,error:g,entities:x||[],refetch:b,label:d}}function Yw({title:e,message:t}){return c.jsx("div",{className:"rounded-xl border border-destructive/40 bg-destructive/10 p-4 text-destructive shadow-sm",children:c.jsxs("div",{className:"flex items-start gap-4",children:[c.jsx(Ac,{className:"h-6 w-6 flex-shrink-0"}),c.jsxs("div",{className:"flex-1",children:[c.jsx("h4",{className:"text-base font-semibold",children:e}),t&&c.jsx("p",{className:"mt-1 text-sm text-destructive/90",children:t})]})]})})}function gZe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=Pa(),[i,a]=C.useState(""),[l,u]=C.useState(""),[d,f]=C.useState("tables"),{updateDataSource:h,setSelectedConnectionId:p}=Qn(),{entities:m,isLoading:g,error:b}=mZe("table"),{dataModels:x,isPending:y,error:v}=OJ(),w=k=>{const T=s.find(P=>P.id===k);if(!T)return;const M=T.type==="upload"?"upload":T.type==="url"?"url":"database";h({...e,connectionId:k,connectionType:T.type,mode:M,dbSelection:{database:"",schema:"",entityType:"table"}}),p(k)},j=k=>{var A,R;const T=n||[],M=T.some(L=>L.name===k.name&&L.type===k.type);let P;if(M)P=T.filter(L=>!(L.name===k.name&&L.type===k.type));else{const L={connectionId:e.connectionId,connectionType:e.connectionType,type:k.type,dbObjectType:k.dbObjectType,database:((A=e.dbSelection)==null?void 0:A.database)||"",schema:((R=e.dbSelection)==null?void 0:R.schema)||"",name:k.name,dialect:k.dialect};P=[...T,L]}t==null||t(P)},S=k=>{const T=n||[],M=T.some(A=>A.type==="model"&&A.name===k.name);let P;M?P=T.filter(A=>!(A.type==="model"&&A.name===k.name)):P=[...T,k],t==null||t(P)},N=m.filter(k=>k.name.toLowerCase().includes(i.toLowerCase())),E=x.filter(k=>k.name.toLowerCase().includes(l.toLowerCase())),_=C.useCallback(()=>{if(!t)return;const k=n||[];let T=[...k];if(d==="tables"){const P=N.filter(A=>!k.some(R=>R.name===A.name&&R.type==="table")).map(A=>{var R,L;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:A.dbObjectType,database:((R=e.dbSelection)==null?void 0:R.database)||"",schema:((L=e.dbSelection)==null?void 0:L.schema)||"",name:A.name,dialect:A.dialect}});T=[...k,...P]}else if(d==="datamodels"){const M=E.filter(P=>!k.some(A=>A.name===P.name&&A.type==="model"));T=[...k,...M]}t(T)},[d,N,E,n,e,t]);return C.useEffect(()=>{r&&r(_)},[r,_]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"font-medium= text-sm",children:"Connection"}),c.jsxs(nt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:w,disabled:o,children:[c.jsx(et,{className:"w-full",children:c.jsx(ot,{placeholder:o?"Loading connections...":"Select connection..."})}),c.jsx(tt,{children:s.map(k=>c.jsx(be,{className:"hover:bg-muted",value:k.id,children:c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(vl,{className:"h-4 w-4 flex-shrink-0"}),c.jsx("span",{className:"truncate",children:k.name}),c.jsx(Fe,{variant:"secondary",className:"flex-shrink-0 text-xs",children:k.type})]})},k.id))})]})]}),(e==null?void 0:e.connectionId)&&c.jsxs(c.Fragment,{children:[e.connectionType==="upload"&&c.jsx(hZe,{}),e.connectionType==="url"&&c.jsx(pZe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(fZe,{}),c.jsx("div",{className:"space-y-4",children:c.jsx("div",{className:"space-y-2",children:c.jsxs(Bs,{defaultValue:"tables",value:d,onValueChange:k=>f(k),className:"w-full",children:[c.jsxs(ws,{className:"grid w-full grid-cols-2",children:[c.jsxs(Kt,{value:"tables",children:["Tables & Views (",N.length,")"]}),c.jsxs(Kt,{value:"datamodels",children:["Data Models (",E.length,")"]})]}),c.jsxs(rr,{value:"tables",className:"space-y-2",children:[c.jsx(xn,{placeholder:"Search tables and views...",value:i,onChange:k=>a(k.target.value),className:"h-8 text-sm",disabled:g}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):b?c.jsx(Yw,{title:"Error loading tables",message:b.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):N.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):N.map(k=>{const T=n.some(M=>M.name===k.name&&M.type==="table");return c.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>j(k),children:[c.jsx(Jt,{id:`table-${k.name}`,checked:T,onCheckedChange:()=>j(k),onClick:M=>M.stopPropagation(),disabled:g}),c.jsxs(ce,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[k.name,k.dbObjectType==="view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),k.dbObjectType==="materialized view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},k.name)})})]}),c.jsxs(rr,{value:"datamodels",className:"space-y-2",children:[c.jsx(xn,{placeholder:"Search data models...",value:l,onChange:k=>u(k.target.value),className:"h-8 text-sm",disabled:y}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?c.jsx(Yw,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):E.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):E.map(k=>{const T=n.some(M=>M.name===k.name&&M.type==="model");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(k),children:[c.jsx(Jt,{id:`dataModel-${k.name}`,checked:T,onCheckedChange:()=>S(k),onClick:M=>M.stopPropagation(),disabled:y}),c.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[c.jsx(ce,{className:"cursor-pointer",children:k.name}),c.jsx("span",{className:"text-xs text-muted-foreground",children:k.description})]})]},k.name)})})]})]})})})]})]})]})}function bZe({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:s=[],isRestricted:o=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var j;const[l,u]=C.useState(""),d=C.useCallback(S=>{const N={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:S};t({...N})},[e,t]);C.useEffect(()=>{i&&!(e!=null&&e.semanticDomainId)&&d(i)},[i,e==null?void 0:e.semanticDomainId,d]);const{semanticDomains:f,isPending:h,error:p}=lZe(),m=o?f.filter(S=>s.includes(S.id)):f,{datasets:g,isPending:b,error:x}=cZe(e==null?void 0:e.semanticDomainId),y=S=>{const N=r||[],E=N.some(k=>k.id===S.id&&k.type==="dataset");let _;if(E)_=N.filter(k=>!(k.id===S.id&&k.type==="dataset"));else{const k={id:S.id,datasetType:S.type,name:S.name||S.table,label:S.label,domainId:S.domainId,description:S.description,database:S.database,schema:S.schema,type:"dataset",connectionId:S.connectionId,connectionType:S.connectionType,dialect:S.dialect,datamodelId:S.datamodelId,sql:S.sql};_=[...N,k]}n==null||n(_)},v=g.filter(S=>S.name.toLowerCase().includes(l.toLowerCase())),w=C.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const S=r||[],E=v.filter(k=>!S.some(T=>T.id===k.id&&T.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})),_=[...S,...E];n(_)},[v,r,e==null?void 0:e.semanticDomainId,n]);return C.useEffect(()=>{a&&a(w)},[a,w]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Semantic Domain"}),c.jsxs(nt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:d,disabled:h||o&&!!i,children:[c.jsx(et,{className:"w-full",children:c.jsx(ot,{placeholder:h?"Loading semantic domains...":o&&i?"Loading domain...":"Select semantic domain...",children:((j=m.find(S=>S.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:j.label)||"Select semantic domain"})}),c.jsx(tt,{children:m.map(S=>c.jsx(be,{className:"hover:bg-muted",value:S.id,children:c.jsxs("div",{className:"flex flex-col items-start",children:[c.jsx("span",{className:"font-medium",children:S.label}),c.jsx("span",{className:"text-xs",children:S.description})]})},S.id))})]}),p&&c.jsx(Yw,{title:"Error loading semantic models",message:p.message})]}),(e==null?void 0:e.semanticDomainId)&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(xn,{placeholder:"Search datasets...",value:l,onChange:S=>u(S.target.value),className:"h-8 text-sm",disabled:b}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:b?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):x?c.jsx(Yw,{title:"Error loading datasets",message:x.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):v.length===0?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:l?"No datasets match your search":"No datasets available"}):v.map(S=>{const N=r.some(E=>E.id===S.id&&E.type==="dataset");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>y(S),children:[c.jsx(Jt,{id:`dataset-${S.id}`,checked:N,onCheckedChange:()=>y(S),onClick:E=>E.stopPropagation(),disabled:b}),c.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[c.jsx(ce,{className:"cursor-pointer font-medium",children:S.label||S.name}),c.jsx("span",{className:"text-xs text-gray-500",children:S.description})]})]},S.label||S.name)})})]})]})]})}function zI({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s}){const{tokenProps:o}=Ge(),{allowedSemanticDomains:i}=o,[a,l]=C.useState([]),{updateDataSource:u}=Qn(),d=X(T=>T.isVisualEditing),f=X(T=>T.dashboard.aiContext),{setAiContext:h}=Ft(),p=C.useRef(null),[m,g]=C.useState(!1),b=i&&i.length>0,x=!b,y=b&&i.length===1?i[0]:void 0,v=C.useCallback(T=>{const M=T;u({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:M,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...M!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,u]),w=C.useCallback(T=>{u({...n,...T})},[n,u]);C.useEffect(()=>{b&&n.mode!=="semanticDomain"&&v("semanticDomain")},[b,n.mode,v]),C.useEffect(()=>{y&&!n.semanticDomainId&&w({semanticDomainId:y})},[y,n.semanticDomainId,w]),C.useEffect(()=>{e?l(s||[]):(p.current=null,g(!1))},[e,n==null?void 0:n.selectedEntities,r,u,s,n]);const j=T=>{const M=a.filter(P=>!(P.name===T.name&&P.type===T.type));l(M)},S=()=>{l([])},N=C.useCallback(T=>{l(T)},[]),E=C.useCallback(()=>{p.current&&p.current()},[]),_=C.useCallback(T=>{p.current=T,g(!0)},[]);function k(){var T,M;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const P=(T=a==null?void 0:a[0])==null?void 0:T.connectionId,A=(M=a==null?void 0:a[0])==null?void 0:M.connectionType;u({...n,connectionId:P,connectionType:A,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return c.jsx(rs,{open:e,onOpenChange:t,children:c.jsx(Vr,{className:"flex max-w-2xl flex-col",children:c.jsxs("div",{children:[c.jsxs(Hr,{className:"flex-shrink-0",children:[c.jsx(Ur,{children:r==="aiContext"?"Data Context":"Select Data Source"}),c.jsx(vs,{children:r==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),c.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:c.jsxs("div",{className:"space-y-4",children:[x&&c.jsx("div",{className:"space-y-2",children:c.jsx(Bs,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:v,className:"w-full",children:c.jsxs(ws,{className:"grid w-full grid-cols-2",children:[c.jsx(Kt,{value:"database",children:"Direct Source"}),c.jsx(Kt,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&c.jsx(bZe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:N,allowedDomainIds:i||[],isRestricted:b,autoSelectedDomainId:y,onRegisterSelectAll:_}),(n==null?void 0:n.mode)==="database"&&x&&c.jsx(gZe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:N,onRegisterSelectAll:_})]})}),c.jsx(aZe,{selectedEntities:a,onDeselectEntity:j}),c.jsx(ys,{className:"flex-shrink-0",children:c.jsx("div",{className:"flex w-full justify-between",children:c.jsxs("div",{className:"flex grow justify-end gap-2",children:[c.jsx(se,{variant:"outline",onClick:E,disabled:!m,children:"Select All"}),c.jsx(se,{variant:"outline",onClick:S,disabled:a.length===0,children:"Clear All"}),c.jsxs(se,{variant:"outline",onClick:()=>t(!1),children:[c.jsx(vt,{className:"mr-2 h-4 w-4"}),"Close"]}),c.jsxs(se,{onClick:k,children:[c.jsx(Mr,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function xZe({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=C.useRef(null),o=async a=>{const l=Array.from(a.target.files||[]);if(l.length===0)return;const u=Ja-n;if(l.length>u){Pe.error(`You can only attach ${Ja} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=vQ(l);if(f.forEach(({file:h,error:p})=>{Pe.error(`${h.name}: ${p}`)}),d.length>0)try{const h=await Promise.all(d.map(p=>MI(p)));e(h)}catch(h){console.error("Failed to process files:",h),Pe.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:s,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:o,className:"hidden",disabled:t||n>=Ja}),c.jsx(se,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=Ja,title:n>=Ja?`Maximum ${Ja} files allowed`:"Attach files",children:c.jsx(oM,{className:"h-4 w-4 text-muted-foreground"})})]})}function yZe({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=C.useState(!1),a=C.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),l=C.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),p=f.clientX,m=f.clientY;(p<h.left||p>=h.right||m<h.top||m>=h.bottom)&&i(!1)},[]),u=C.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=C.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const p=Ja-r;if(h.length>p){Pe.error(`You can only attach ${Ja} files per message. You have ${p} slot(s) remaining.`);return}const{valid:m,errors:g}=vQ(h);if(g.forEach(({file:b,error:x})=>{Pe.error(`${b.name}: ${x}`)}),m.length>0)try{const b=await Promise.all(m.map(x=>MI(x)));t(b),Pe.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),Pe.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:K("relative",s),onDragEnter:a,onDragLeave:l,onDragOver:u,onDrop:d,children:[e,o&&!n&&c.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-lg border-2 border-dashed border-primary bg-primary/5 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-2",children:[c.jsx(pM,{className:"h-8 w-8 text-primary"}),c.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ja-r," slot(s) available"]})]})})]})}const BI=C.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:l},u)=>{const[d,f]=C.useState(!1),[h,p]=C.useState(!1),[m,g]=C.useState(!1),b=C.useRef(null),x=Lp();pCe(),hCe();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:w,setShowReasoning:j}=dS(),{queueMessage:S}=zp(),{addFileAttachment:N,removeFileAttachment:E,clearFileAttachments:_,getFileAttachments:k}=lD(),T=aD(l),M=Me(H=>H.card.dataSource),P=X(H=>H.dashboard.aiContext),A=X(H=>{var G;return(G=H.dashboard.aiContext)==null?void 0:G.selectedEntities});C.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const R=C.useCallback(()=>{const H=b.current;if(H){if(!e||e.length===0){H.style.height="10px";return}H.style.height="auto";const G=Math.min(Math.max(H.scrollHeight,10),200);H.style.height=`${G}px`}},[e]);C.useEffect(()=>{R()},[R]),C.useEffect(()=>{const H=setTimeout(()=>{R()},0);return()=>clearTimeout(H)},[R]);const L=()=>{const H=e.trim();!H&&T.length===0||(a!=="ready"?(S(l,H,T),t(""),_(l)):r({preventDefault:()=>{}}))},F=H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),L()),H.key==="@"&&(W(),f(!0))},U=C.useCallback(H=>{const G=HHe(H.nativeEvent);G.length>0&&(H.preventDefault(),G.forEach(async Z=>{const J=await MI(Z);N(l,J)}))},[N,l]),$=C.useCallback(H=>{H.forEach(G=>{N(l,G)})},[N,l]),I=C.useCallback(H=>{H.forEach(G=>{N(l,G)})},[N,l]),B=C.useCallback(H=>{E(l,H)},[E,l]),z=H=>{if(x.selectedEntities.some(Z=>Z.id&&Z.id===H.id||Z.name===H.name)){const Z=x.selectedEntities.filter(J=>!(J.id&&J.id===H.id||J.name===H.name));y({selectedEntities:Z})}else{const Z=[...x.selectedEntities,H];y({selectedEntities:Z})}},O=H=>{z(H)},q=H=>{var J;if(!x.selectedEntities.some(Q=>Q.id&&Q.id===H.id||Q.name===H.name)){const Q=[...x.selectedEntities,H];y({selectedEntities:Q})}const Z="label"in H?H.label:H.name;t(e+`@${Z} `),f(!1),(J=b.current)==null||J.focus()},V=H=>{const G=x.selectedEntities.filter(Q=>!(Q.id&&Q.id===H.id||Q.name===H.name));y({selectedEntities:G});const J=`@${"label"in H?H.label:H.name}`;e.includes(J)&&t(e.replace(J,"").trim())},Y=H=>{const G=new Set(H.map(Q=>Q.id||Q.name)),Z=x.selectedEntities.filter(Q=>!G.has(Q.id||Q.name));y({selectedEntities:Z});let J=e;H.forEach(Q=>{const ie=`@${"label"in Q?Q.label:Q.name}`;J=J.replace(ie,"").trim()}),t(J)},W=C.useCallback(()=>{x.selectedEntities.length===0&&y({selectedEntities:(P==null?void 0:P.selectedEntities)||[]})},[x.selectedEntities.length,P==null?void 0:P.selectedEntities,y]);return c.jsxs(yZe,{onFilesDropped:$,currentFileCount:T.length,disabled:s,className:"space-y-4",children:[c.jsx(oZe,{entities:x.selectedEntities,availableEntities:A||[],onRemoveEntity:V,onRemoveEntities:Y}),T.length>0&&c.jsx(UHe,{files:T,onRemove:B,showRemove:!s,className:"mb-2"}),c.jsxs("div",{className:"rounded-lg border border-border bg-background shadow-sm focus-within:ring-1 focus-within:ring-foreground/40",children:[c.jsx("textarea",{ref:b,value:e,onChange:n,onKeyDown:F,onPaste:U,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"}}),c.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[l==="dashboard"&&c.jsxs(Qr,{open:d,onOpenChange:H=>{H&&W(),f(H)},children:[c.jsx(Jr,{asChild:!0,children:c.jsx(se,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:c.jsx(Pse,{className:"h-4 w-4 text-muted-foreground"})})}),c.jsx(es,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:H=>H.preventDefault(),children:c.jsx(rZe,{isOpen:!0,onSelect:z,onDeselect:O,onClose:()=>{var H;f(!1),(H=b.current)==null||H.focus()},availableEntities:A||[],selectedEntities:x.selectedEntities,onTabComplete:q,onSelectAll:()=>{A&&y({selectedEntities:A})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),p(!0)}})})]}),c.jsx(xZe,{onFilesSelected:I,disabled:s,currentFileCount:T.length})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[s&&c.jsx(se,{className:"rounded-full",size:"sm",onClick:o,children:c.jsx(Qse,{className:"size-3.5 bg-background"})}),!s&&c.jsx(se,{disabled:!e.trim()&&T.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:L,title:a!=="ready"?"Message will be queued":void 0,children:c.jsx(wz,{className:"size-4"})})]})]})]}),c.jsx(zI,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:p,dataSource:M||uC,dialogMode:"aiContext"})]})});BI.displayName="ChatInputWithContext";function FJ({assistantType:e,className:t}){const n=MW(e),{removeFromQueue:r}=zp();return n.length===0?null:c.jsxs("div",{className:K("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(Ml,{className:"h-3 w-3"}),c.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),c.jsx("div",{className:"space-y-2",children:n.map(s=>c.jsx("div",{className:"group relative rounded-lg border border-dashed border-muted-foreground/30 bg-muted/30 px-3 py-2 text-sm animate-in fade-in-0 slide-in-from-bottom-1",children:c.jsxs("div",{className:"flex items-start justify-between gap-2",children:[c.jsx("div",{className:"flex-1 space-y-1",children:c.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),c.jsx(se,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:c.jsx(vt,{className:"h-3 w-3"})})]})},s.id))})]})}function $J({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=MW(e),{dequeueMessage:o}=zp();C.useEffect(()=>{if(t!=="ready"||n||!(s&&s.length>0))return;const a=o(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,s,o,r,e])}function LJ(e,t={}){const{threshold:n=50,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=C.useRef(null),[a,l]=C.useState(!0),[u,d]=C.useState(!0),[f,h]=C.useState(!1),[p,m]=C.useState(0),g=C.useRef(0),b=C.useRef(!1),x=C.useRef(0),y=C.useRef(a),v=C.useRef(void 0),w=C.useRef({key:null,count:0,length:0}),j=C.useCallback(()=>{const _=i.current;return _?_.scrollHeight-_.scrollTop-_.clientHeight:0},[]),S=C.useCallback((_={})=>{if(!i.current)return;const{force:T=!1,instant:M=!1}=_;if(!T&&!y.current||!a&&!T)return;const P=M||r==="auto"||r==="instant"?"auto":r;v.current&&cancelAnimationFrame(v.current),b.current=!0,v.current=requestAnimationFrame(()=>{if(!T&&!y.current){b.current=!1,v.current=void 0;return}const A=i.current;if(!A){b.current=!1,v.current=void 0;return}const R=A.scrollHeight;P==="smooth"&&"scrollTo"in A?A.scrollTo({top:R,behavior:P}):A.scrollTop=R,g.current=A.scrollTop,d(!0),l(!0),y.current=!0,h(!1),m(0),b.current=!1,v.current=void 0})},[r,a]),N=C.useCallback(()=>{const _=i.current;if(!_)return;const k=g.current,T=_.scrollTop,M=T-k;if(g.current=T,M<-1){v.current&&(cancelAnimationFrame(v.current),v.current=void 0),b.current=!1,y.current=!1,l(!1),d(!1);return}if(b.current)return;const P=j()<=n;d(P),l(P),y.current=P,P&&(h(!1),m(0))},[j,n]),E=C.useCallback(()=>{m(0),h(!1)},[]);return C.useEffect(()=>{y.current=a},[a]),C.useEffect(()=>{const _=i.current;if(!_||!e||e.length===0){h(!1),m(0),w.current={key:null,count:0,length:0},g.current=_?_.scrollTop:0,x.current=_?_.scrollHeight:0;return}g.current=_.scrollTop,x.current=_.scrollHeight;const k=w.current,T=e[e.length-1],M=(T==null?void 0:T.id)??(T==null?void 0:T.messageId)??(T==null?void 0:T.createdAt)??(T==null?void 0:T.timestamp)??e.length,P=Array.isArray(T==null?void 0:T.parts)?T.parts.reduce(($,I)=>I?typeof I=="string"?$+I.length:typeof I.text=="string"?$+I.text.length:typeof I.content=="string"?$+I.content.length:typeof I.value=="string"?$+I.value.length:$:$,0):typeof(T==null?void 0:T.content)=="string"?T.content.length:typeof(T==null?void 0:T.text)=="string"?T.text.length:0,A=e.length>k.count,R=M!==k.key,L=P>k.length,F=s&&(T==null?void 0:T.role)==="assistant"&&!A&&(R||L),U=o||F;if(w.current={key:M,count:e.length,length:P},a&&(A||R||L||U)){S({force:!1,instant:U});return}if(!a&&A){const $=e.length-k.count;$>0&&(h(!0),m(I=>I+$))}else!a&&L&&(h(!0),m($=>$>0?$:1))},[e,S,a,s,o]),C.useEffect(()=>{S({instant:!0})},[S]),C.useEffect(()=>{if(typeof ResizeObserver>"u")return;const _=i.current;if(!_)return;x.current=_.scrollHeight;const k=new ResizeObserver(()=>{const T=i.current;if(!T)return;const M=x.current,P=T.scrollHeight;x.current=P,!b.current&&y.current&&P>M&&S({force:!1,instant:!0})});return k.observe(_),()=>{k.disconnect()}},[S]),C.useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:u,hasNewMessages:f,newMessageCount:p,scrollToBottom:S,handleScroll:N,resetNewMessageCount:E}}function zJ(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=C.useState(r),a=C.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),l=e.length>o,u=o>=e.length,d=C.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=C.useCallback(()=>{i(r)},[r]);return C.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:l,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}function BJ(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:wQ(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const vZe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function wZe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=C.useState(!1),[a,l]=C.useState(E_),[u,d]=C.useState(!1),[f,h]=C.useState(!1),[p,m]=C.useState(!1),g=n??p,{isLocalDev:b,isConsoleMode:x}=dp(),y=C.useRef(null);X(He=>He.dashboard.aiScopeTables),X(He=>He.isDashboardEditing);const v=X(He=>He.selectedSheetId),{setDataSource:w}=Qn(),{addFrame:j,setSelectedFrameId:S,setIsDashboardEditing:N}=Ft(),E=Lp(),{setCurrentAIContext:_,updateSelectedEntities:k,setReasoningEffort:T,setShowReasoning:M}=dS(),{clearQueue:P}=zp(),{clearFileAttachments:A,getFileAttachments:R}=lD(),L=aD("dashboard"),F=X(He=>He.dashboard.aiContext),U=Me(He=>He.card.dataSource),{assistantProfile:$}=RJ(),I=X(He=>He.handleOpenAssistantProfile),{sendMessage:B,isLoading:z,messages:O,setMessages:q,status:V,stop:Y,errorMessage:W,clearError:H}=nZe(),G=C.useCallback(He=>{r==null||r(He),n===void 0&&m(He)},[n,r]),Z=C.useCallback(()=>{G(!g)},[g,G]);C.useEffect(()=>{if(!g)return;function He(en){en.key==="Escape"&&G(!1)}return window.addEventListener("keydown",He),()=>{window.removeEventListener("keydown",He)}},[g,G]);const[J,Q]=C.useState(""),re=He=>{Q(He.target.value)};function ie({sql:He,cardTitle:en,connectionId:Ke,cardType:Qe,python:Le,cardConfig:ve,dataSource:Be,customVisualPreferences:we}){if(!v)return;const We={id:yr(),title:en||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Qe==="horizontalBar"?"y":"x"}},type:Qe,sql:He,python:Le,dataSource:Be,config:ve,connectionId:Ke,customCardPreferences:we?{url:we.url,componentName:we.componentName,pluginChartType:we.pluginChartType,settings:we.settings,type:"component"}:void 0},at={id:yr(),cards:[We],activeCardId:We.id};N(!0),j(v,at,"end"),S(at.id)}const fe=He=>{He.preventDefault();const en=J.trim();if(!en&&L.length===0)return;const Ke=[];en&&Ke.push({type:"text",text:en}),L.forEach(Qe=>{Qe.data&&Ke.push({type:"file",mediaType:Qe.type,filename:Qe.name,url:`data:${Qe.type};base64,${Qe.data}`})}),B({role:"user",parts:Ke}),Q(""),A("dashboard"),ae({force:!0})};C.useEffect(()=>{var He;e&&((He=y.current)==null||He.focus())},[e]),$J({assistantType:"dashboard",status:V,isLoading:z,sendMessage:B});const{hasActiveTools:le}=BJ(O),{visibleMessages:Ce,hasMoreMessages:he,totalMessageCount:te,loadMoreMessages:oe,resetMessageWindow:me}=zJ(O,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:_e,isAtBottom:ue,hasNewMessages:De,newMessageCount:Ue,scrollToBottom:ae,handleScroll:ye,resetNewMessageCount:$e}=LJ(Ce,{threshold:50,behavior:"smooth",isStreaming:z});function pe(He){Ae();const en={role:"user",parts:[{type:"text",text:He.title+" "+He.subtitle}]};B(en)}function Ee(He){Ae(),B({role:"user",parts:[{type:"text",text:He}]})}function Ve(He){Ae(),B({role:"user",parts:[{type:"text",text:He}]}),ae({force:!0})}const qe=C.useCallback(async()=>{const He=JSON.stringify(O??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(He),Pe.success("Conversation copied")}catch(en){console.error("Failed to copy conversation",en),Pe.error("Unable to copy conversation")}},[O]);function Ae(){E.selectedEntities.length===0&&_({selectedEntities:(F==null?void 0:F.selectedEntities)||[]})}const yt=(J==null?void 0:J.length)===0&&(O==null?void 0:O.filter(He=>He.role==="user").length)===0;function je(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function mt(){return c.jsxs(cp,{children:[c.jsx(up,{asChild:!0,children:c.jsx(jc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(tp,{className:"size-3.5"})})}),c.jsxs(Qd,{align:"end",children:[c.jsx(Xf,{children:"Options"}),c.jsx(Ed,{}),c.jsx(rg,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(rg,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(rg,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const Mt=c.jsxs("div",{"data-role":"dashboard-assistant",className:K("flex h-full grow flex-col justify-between break-words px-6 py-4",g&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[c.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[je(),I&&c.jsx(se,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:I,children:($==null?void 0:$.name)||"Default Profile"}),c.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[x&&mt(),a&&c.jsx(se,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:qe,children:"Copy Conversation"}),c.jsx(jc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:Z,children:g?c.jsx(sM,{className:"size-4"}):c.jsx(h1,{className:"size-4"})}),c.jsx(jc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{q([]),P("dashboard"),H(),me()},children:c.jsx(p1,{className:"size-4"})}),c.jsx(jc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(vt,{className:"size-4"})})]})]}),c.jsxs(zl,{"data-role":"dashboard-assistant-scroll-area",ref:_e,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:ye,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[he&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(se,{variant:"outline",size:"sm",onClick:oe,className:"text-xs",children:["Load ",Math.min(5,te-Ce.length)," ","more messages (",te-Ce.length," ","hidden)"]})}),c.jsx(CQ,{showTools:a,showSystemMessage:u,messages:Ce,onAddToDashboard:ie,onQuickReply:Ve,disableQuickReplies:z}),!le&&c.jsx(SQ,{status:V,errorMessage:W})]}),c.jsx(ti,{orientation:"horizontal"})]}),e&&!ue&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(se,{onClick:()=>{ae({force:!0}),$e()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(fr,{className:"h-4 w-4"}),De&&Ue>0&&c.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:Ue>9?"9+":Ue})]})}),c.jsxs("div",{className:"space-y-3",children:[!$&&yt&&c.jsx(jQ,{onClick:pe,placeholders:vZe}),c.jsx("div",{children:yt&&$&&c.jsx(IJ,{seedQuestions:$.seedQuestions||[],handleSeedQuestionClick:Ee})}),c.jsx(FJ,{assistantType:"dashboard",className:"mb-3"}),c.jsx(BI,{ref:y,setInput:Q,stop:Y,input:J,handleInputChange:re,handleSubmit:He=>{Ae(),fe(He),ae({force:!0})},isLoading:z,status:V,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx(zI,{incomingSelectedEntities:(F==null?void 0:F.selectedEntities)||[],open:f,onOpenChange:h,dataSource:U||uC,dialogMode:"aiContext"})]});return g&&s?Ln.createPortal(c.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:c.jsx("div",{className:"flex h-full w-full",children:Mt})}),s):Mt}function SZe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Ft(),o=X(d=>d.dashboard.sheets),a=X(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),l=X(d=>d.isDashboardEditing),u=X(d=>d.isVisualEditing);C.useEffect(()=>{if(!l||u)return;async function d(p){const m=p.ctrlKey||p.metaKey;m&&p.key==="c"?(await f(),Pe.success("Card copied to clipboard"),p.preventDefault()):m&&p.key==="v"&&(await h(),p.preventDefault())}async function f(){try{const p=n();p&&await navigator.clipboard.writeText(JSON.stringify(p))}catch(p){console.error("Failed to copy text:",p)}}async function h(){if(!a)return null;try{const p=await navigator.clipboard.readText();try{const m=JSON.parse(p);if(m!=null&&m.id){const g=AR(m),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),Pe.success("Card pasted from clipboard")}}catch(m){console.error("Failed to parse clipboard contents: ",m)}return p}catch(p){return console.error("Failed to paste text:",p),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[r,n,s,a,l,u,t])}function CZe(e,t){switch(e.interactionMode){case"drillToDetail":jZe(e,t);break;case"drillThrough":NZe(e,t);break;case"drillToURL":kZe(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 jZe(e,t){var l;const{targetInsightId:n,contextMode:r,displayMode:s,filterGroups:o}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=o.flatMap(u=>u.filters);break;case"full":{const u=((l=t.getCurrentFilters)==null?void 0:l.call(t))||[],d=o.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}s==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function NZe(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:s,sourceCardId:o}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=s.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",l=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:l,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:l,filters:i,contextMode:r})}function kZe(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 EZe({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(rs,{open:e,onOpenChange:t,children:c.jsxs(Vr,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(Hr,{children:[c.jsx(Ur,{children:i||"Insight Detail"}),c.jsx(vs,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(HK,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(YK,{insightId:n,filters:r,contextMode:o}):c.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function _Ze(){const e=At(w=>w.interactionStates),t=At(w=>w.setInteractionState),n=At(w=>w.clearLastInteractionEvent),r=At(w=>w.replaceCardWithInsight),s=At(w=>w.setPendingDrillThrough),o=At(w=>w.pendingDrillThrough),i=At(w=>w.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Ft(),{selectDashboard:u}=qb(),d=X(w=>w.dashboard),f=X(w=>w.filterValues),{data:h,isLoading:p}=O9((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[m,g]=C.useState({open:!1,insightId:""}),b=GK(m.insightId,{enabled:m.open&&!!m.insightId}),x=C.useRef(new Set),y=C.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:w,filters:j,contextMode:S})=>{g({open:!0,insightId:w,filters:j,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:S})},replaceCardContent:({cardId:w,insightId:j,filters:S,contextMode:N})=>{r(w,j,S,N)},getCurrentFilters:()=>f||[],navigateWithDrill:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:w,contextMode:j,sourceDashboardId:S,sourceDashboardTitle:N,targetDashboardId:E})=>{const k={sourceCardId:pa,interactionMode:"clickFilter",filterGroups:[{filters:w}]},T={...Ho(),appliedClickFilters:[k],contextMode:j,sourceDashboardId:S,sourceDashboardTitle:N,targetDashboardId:E};t(pa,T)}}),[a,r,f,l,d,s,t]);C.useEffect(()=>{Object.entries(e).forEach(([w,j])=>{if(j!=null&&j.lastInteractionEvent){const S=j.lastInteractionEvent,N=`${w}-${S.interactionMode}-${S.sourceCardId}-${Date.now()}`;if(x.current.has(N))return;x.current.add(N);try{CZe(S,y)}catch(E){console.error("Error executing interaction event:",E)}finally{n(w),setTimeout(()=>{x.current.delete(N)},5e3)}}})},[e,n,y]),C.useEffect(()=>{if(!(!o||!h||p))try{u(h),l(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(w){console.error("[DrillThrough] Error during automatic navigation:",w),i()}},[o,h,p,u,l,i]);const v=()=>{g({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(EZe,{open:m.open,onOpenChange:v,insightId:m.insightId,filters:m.filters,filterDefinitions:m.filterDefinitions,contextMode:m.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&p&&c.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border bg-background p-6 shadow-lg",children:[c.jsx(an,{className:"h-8 w-8 animate-spin text-primary"}),c.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function MZe(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=TZe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function TZe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function DZe(e){return e?`Back to ${e}`:"Back"}function RZe(){var x,y,v,w,j;const e=At(S=>S.interactionStates[pa]),t=X(S=>S.actions.goBackFromDrill),n=X(S=>S.actions.clearDrillContext),{selectDashboard:r}=qb(),[s,o]=C.useState({x:16,y:16}),[i,a]=C.useState(!1),l=C.useRef({x:0,y:0});C.useEffect(()=>{if(!i)return;const S=E=>{o({x:E.clientX-l.current.x,y:E.clientY-l.current.y})},N=()=>{a(!1)};return document.addEventListener("mousemove",S),document.addEventListener("mouseup",N),()=>{document.removeEventListener("mousemove",S),document.removeEventListener("mouseup",N)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((w=(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:w.filters)||[],h=u?{id:u,title:d||"Previous Dashboard",description:"",isPrivate:!1,isPublic:!1,version:"",createdBy:null,createdByTenantUser:"",tenantId:"",projectId:"",createdAt:"",updatedAt:"",lastModified:"",lastModifiedBy:"",createdByUser:null,createdByTenantUserRel:{name:"",email:""},permissions:{canEdit:!0,canShare:!0,canDelete:!0},ownership:{status:"private",isOwner:!0,sharedCount:0,createdBy:{type:"user",userId:"",name:"",email:""}}}:null;if(!e||!((j=e.appliedClickFilters)!=null&&j.length))return null;const p=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(S){console.error("[DrillBack] Error during back navigation:",S)}},m=()=>{n()},g=S=>{S.target.closest("button")||(a(!0),l.current={x:S.clientX-s.x,y:S.clientY-s.y})};MZe(f);const b=DZe(d);return c.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:c.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:g,style:{cursor:i?"grabbing":"grab"},children:[c.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((S,N)=>{const E=S.field.label||S.field.name,_=String(S.value);return c.jsxs(Fe,{variant:"secondary",className:"pointer-events-none text-xs",children:[E," = ",_]},N)})})]}),c.jsx(se,{variant:"ghost",size:"sm",onClick:m,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(vt,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(se,{variant:"secondary",size:"sm",onClick:p,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(tz,{className:"mr-2 h-4 w-4"}),b]})})]})})}function VJ(){var he;const{showAssistant:e,tokenProps:t}=Ge(),{preferences:n,isConsoleMode:r}=dp(),s=((he=n==null?void 0:n.cardDisplay)==null?void 0:he.mode)==="print",o=C.useRef(null),i=C.useRef(null),[a,l]=C.useState(!1),{handleDragStart:u,isDraggingRef:d,getStyle:f,getPositionClasses:h}=FLe({initialPosition:"bottom-right"}),p=pd(te=>te.setFullscreen),m=pd(te=>te.setPanelOpen),g=pd(te=>te.setContainer),b=NW("dashboard"),x=kW(),y=EW("dashboard"),v=b.isOpen,w=x==="dashboard",j=X(te=>te.isVisualEditing),S=X(te=>te.themeStyle),N=X(te=>{var oe;return(oe=te.dashboard)==null?void 0:oe.sheets}),E=X(te=>te.showFilters),_=X(te=>te.isDashboardEditing),k=X(te=>te.selectedSheetId),T=X(te=>{var oe;return(oe=te.dashboard)==null?void 0:oe.id}),M=X(te=>te.isDashboardPanelOpen),P=X(te=>te.actions.setIsDashboardPanelOpen),{getDefaultSheetId:A,setDefaultSheetId:R,clearDefaultSheetId:L}=Z6(T),[F,U]=C.useState(null);E1(Ot.DASHBOARD);const{setSelectedSheetId:$,setSheetTitle:I,addSheet:B,setSheets:z}=Ft();SZe(i);const{setActiveAssistantType:O}=dS();C.useEffect(()=>{if(T){const te=A();U(te)}},[T,A]),C.useEffect(()=>{v?O("dashboard"):x==="dashboard"&&p(null)},[v,O,x,p]),C.useEffect(()=>{var te;v||(te=o.current)==null||te.resize(0)},[v]);function q(te){var oe,me;te?((oe=o.current)==null||oe.resize(40),m("dashboard",!0),O("dashboard")):(m("dashboard",!1),p(null),(me=o.current)==null||me.resize(0),O(null))}function V(){const te={id:yr(),title:"New Sheet"};B(te),$(te.id)}function Y(te,oe){if(!T)return;F===te?(L(),U(null),Pe.success("Default sheet cleared")):(R(te),U(te),Pe.success(`"${oe}" set as default sheet`))}function W(te){var oe;te<1?(m("dashboard",!1),p(null),O(null),(oe=o.current)==null||oe.resize(0)):(v||m("dashboard",!0),O("dashboard"))}function H(){return(S==null?void 0:S.canvasTheme)==="muted"||!(S!=null&&S.canvasTheme)?"hsl(var(--semaphor-muted))":(S==null?void 0:S.canvasTheme)==="clear"?"":S==null?void 0:S.canvasTheme}const G=(te,oe)=>{te.dataTransfer.setData("tabIndex",oe.toString())},Z=te=>{te.preventDefault()},J=(te,oe)=>{const me=te.dataTransfer.getData("tabIndex");if(me===oe.toString())return;const _e=Array.from(N||[]),[ue]=_e.splice(parseInt(me),1);_e.splice(oe,0,ue),z(_e)},Q=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail,re=e===!0&&!s&&!v&&!j&&!E;function ie(){var te,oe;if(N&&N.length>1||_)return c.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&&Q&&c.jsx(se,{style:{borderRadius:S==null?void 0:S.controlInputRadius},variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{P(!M)},className:"h-8 shrink-0 p-2",children:M?c.jsx(iz,{className:"h-4 w-4"}):c.jsx(az,{className:"h-4 w-4"})}),N==null?void 0:N.map((me,_e)=>{const ue=k===me.id,De=F===me.id;return c.jsxs(Kt,{draggable:!0,onDragStart:Ue=>G(Ue,_e),onDragOver:Z,onDrop:Ue=>J(Ue,_e),style:{borderRadius:S==null?void 0:S.controlInputRadius},onClick:()=>$(me.id),className:"flex shrink-0 items-center gap-1 border px-2 py-1",value:me.id,children:[c.jsx(gb,{enabled:_&&ue,text:me.title,onSave:Ue=>I(me.id,Ue),children:me.title},me.id),!_&&ue&&c.jsx("div",{title:De?"Clear default sheet":"Set as default sheet",children:c.jsx(cM,{className:K("ml-1 size-3 cursor-pointer transition-all",De?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:Ue=>{Ue.stopPropagation(),Y(me.id,me.title||"Sheet")}})}),_&&ue&&N.length>1&&c.jsx(vt,{className:"ml-1 size-3",onClick:()=>l(!0)})]},me.id)}),_&&c.jsx("div",{style:{borderRadius:(oe=(te=S==null?void 0:S.chart)==null?void 0:te.options)==null?void 0:oe.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:V,children:c.jsx(wr,{className:"size-3"})})]})}function fe(){return c.jsx("div",{ref:i,style:{},className:"grow",children:N==null?void 0:N.map(te=>c.jsx(rr,{style:{backgroundColor:H()},className:K("mt-0",{}),value:te.id,children:c.jsx(aLe,{sheet:te})},te.id))})}function le(){var te;return c.jsxs(Bs,{"data-role":"dashboard-tabs-container",className:K("relative flex h-full flex-col",S==null?void 0:S.dashboardTabsContainer),onValueChange:oe=>{$(oe)},value:k||((te=N==null?void 0:N[0])==null?void 0:te.id),children:[ie(),c.jsx(zl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:fe()}),c.jsx($Le,{open:a,setOpen:l})]})}const Ce=C.useCallback(te=>{g("dashboard",te)},[g]);return N?c.jsxs(c.Fragment,{children:[c.jsx(_Ze,{}),c.jsx(RZe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(sX,{className:K("flex-1 basis-0 overflow-y-auto transition-opacity",w&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(HE,{children:le()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx(OLe,{open:v,onTabClick:q,withHandle:!0,disabled:!v}),c.jsx(HE,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:W,defaultSize:v?40:0,ref:o,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(wZe,{open:v,setOpen:q,isFullscreen:w,onFullscreenChange:te=>p(te?"dashboard":null),fullscreenContainer:y})})})]})]}),c.jsx("div",{ref:Ce,className:K("absolute inset-0",!w&&"pointer-events-none")}),re&&c.jsx("div",{className:K("absolute z-50 transition-all duration-300 ease-in-out",h().horizontal,h().vertical),style:f(),children:c.jsx(se,{size:"sm",variant:"outline",className:"h-12 w-12 cursor-grab rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted active:cursor-grabbing",onClick:()=>{d.current||q(!0)},onMouseDown:u,onTouchStart:u,title:"Open Assistant (drag to move)",children:c.jsx(lM,{className:"h-5 w-5"})})})]})]}):null}function VI({children:e}){return c.jsx(Aa,{style:{height:"100%",width:"100%"},children:c.jsx(Kre,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(Mn,{delayDuration:0,children:e})})})}function HJ({children:e,preferences:t}){const{currentUser:n}=oo(),r=C.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return c.jsx(h9.Provider,{value:r,children:c.jsx(HR,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function IZe(e=2e3,t=500){const n=jse(),[r,s]=C.useState(!1),[o,i]=C.useState(!1),a=C.useRef(null);return C.useEffect(()=>{const l=setTimeout(()=>s(!0),e);return()=>clearTimeout(l)},[e]),C.useEffect(()=>{if(r){if(n>0){i(!1),a.current&&(clearTimeout(a.current),a.current=null);return}return a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i(!0)},t),()=>{a.current&&clearTimeout(a.current)}}},[r,n,t]),o}function HI({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=IZe(e,t);return C.useEffect(()=>(s&&(window.__SEMAPHOR_READY__={ready:!0,type:n,componentId:r||null,timestamp:Date.now()}),()=>{window.__SEMAPHOR_READY__={ready:!1,type:n,componentId:r||null,timestamp:Date.now()}}),[s,n,r]),c.jsx("div",{id:"idle-check","aria-hidden":"true",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s?"ready":""})}function UJ(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(Ba,{FallbackComponent:FS,children:c.jsxs(q_,{dashboardProps:e,children:[c.jsx(HI,{componentType:"dashboard",componentId:e.id}),c.jsx(VI,{children:c.jsx(HJ,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(cD,{...e,type:"dashboard",children:c.jsx(VJ,{})})})})})]})})}function UI(e){const{tokenProps:t,authToken:n}=Ge(),r=t==null?void 0:t.apiServiceUrl;return pn({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return qn(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 WJ(e,t,n){if(t==="source")return{isValid:!0};const r=Tr(e.dataType);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 qJ(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=(t==null?void 0:t.comparisonType)==="none";!o&&i||n(r,{groupByColumns:[],comparisonType:"none"})}const YJ=e=>{var P;const t=(P=e==null?void 0:e.dataSource)==null?void 0:P.semanticDomainId,{data:n}=UI(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=Qn(),h=Me(A=>A.card.type),p=e==null?void 0:e.id,m=C.useCallback(A=>{if(!(e!=null&&e.config))return[];switch(A){case"groupBy":return(e.config.groupByColumns||[]).map(R=>({id:R.id,name:R.name,dataType:R.dataType,label:R.label!==void 0?R.label:R.name,qualifiedEntityName:R.qualifiedEntityName,entityId:R.entityId,entityName:R.entityName,entityType:R.entityType,dateFormat:R.dateFormat,customFormat:R.customFormat,granularity:R.granularity}));case"metrics":return e.config.metricColumns||[];case"pivotBy":return(e.config.pivotByColumns||[]).map(R=>({id:R.id,name:R.name,dataType:R.dataType,label:R.label!==void 0?R.label:R.name,qualifiedEntityName:R.qualifiedEntityName,entityId:R.entityId,entityName:R.entityName,entityType:R.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map(R=>({id:R.id,name:R.name,dataType:R.dataType,label:R.label!==void 0?R.label:R.name,qualifiedEntityName:R.qualifiedEntityName,entityId:R.entityId,entityName:R.entityName,entityType:R.entityType,direction:R.direction}));case"source":return[];default:return[]}},[e]),g=C.useCallback((A,R)=>{if(p)switch(A){case"groupBy":{r(p,{groupByColumns:R});break}case"metrics":{r(p,{metricColumns:R});break}case"pivotBy":{r(p,{pivotByColumns:R});break}case"sortBy":{r(p,{sortByColumns:R});break}}},[p,r]),b=C.useCallback((A,R,L)=>{if(!p)return;const U=m(A)[R];if(U)switch(A){case"groupBy":s(p,U.id,{label:L});break;case"metrics":o(p,U.id,{label:L});break;case"pivotBy":i(p,U.id,{label:L});break;case"sortBy":a(p,U.id,{label:L});break}},[p,m,s,o,i,a]),x=C.useCallback((A,R)=>{if(!p)return;const F=m("metrics")[A];F&&o(p,F.id,{aggregate:R,label:MH(F.name,R)})},[p,m,o]),y=C.useCallback((A,R,L)=>{if(!p)return;const U=m("groupBy")[A];if(!U)return;const $={dateFormat:R};R==="custom"&&L?$.customFormat=L:$.customFormat=void 0,s(p,U.id,$)},[p,m,s]),v=C.useCallback((A,R)=>{if(!p)return;const F=m("groupBy")[A];F&&s(p,F.id,{granularity:R})},[p,m,s]),w=C.useCallback((A,R)=>{if(!p)return;const F=m("metrics")[A];F&&o(p,F.id,{aliasTemplate:R})},[p,m,o]),j=C.useCallback((A,R)=>{if(console.log("handleValueAliasesChange",A,R),!p)return;console.log("handleValueAliasesChange",A,R);const F=m("metrics")[A];F&&(console.log("handleValueAliasesChange",R),o(p,F.id,{valueAliases:R}))},[p,m,o]),S=C.useCallback(A=>{if(!p)return;if(m("metrics").length===0){Pe.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(p,{comparisonType:A})},[p,r,m]),N=C.useCallback(A=>{p&&r(p,{showTrendline:A})},[p,r]),E=C.useCallback(A=>{p&&r(p,{trendlineWindow:A})},[p,r]),_=C.useCallback(A=>{p&&r(p,{trendlineGranularity:A})},[p,r]),k=C.useCallback(A=>{p&&r(p,{targetValue:A})},[p,r]),T=C.useCallback(A=>{var B;if(!p)return;const R=[...m("groupBy"),...m("pivotBy"),...m("metrics"),...m("sortBy")],L=Wwe(A,R,{joinPlan:(B=e==null?void 0:e.config)==null?void 0:B.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!L.isValid){L.showError&&kH();return}const F=Gwe(A,R,h);if(!F){Pe.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const U=WJ(A,F,h);if(!U.isValid){Pe.error("Invalid Field Type",{description:U.reason,position:"top-center",duration:3e3});return}const $=m(F);if(EH(A,$))return;const I=TH(A,F,$);if(I){const z=[...$,I];g(F,z),F==="metrics"&&qJ(h,e==null?void 0:e.config,r,p,z)}},[p,e==null?void 0:e.config,m,g,t,n,h,r]),M=C.useCallback((A,R)=>{if(!p)return;const F=m(A)[R];if(F){if(A!=="sortBy"){const U=m("sortBy"),$=U.filter(I=>!(I.name===F.name&&I.qualifiedEntityName===F.qualifiedEntityName));$.length!==U.length&&r(p,{sortByColumns:$})}switch(A){case"groupBy":l(p,F.id);break;case"metrics":u(p,F.id);break;case"pivotBy":d(p,F.id);break;case"sortBy":f(p,F.id);break}}},[p,m,l,u,d,f,r]);return{getFieldsForContainer:m,setFieldsForContainer:g,updateLabel:b,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:v,handleAliasTemplateChange:w,handleValueAliasesChange:j,removeField:M,handleFieldClick:T,handleKpiComparisonTypeChange:S,handleKpiShowTrendlineChange:N,handleKpiTrendlineWindowChange:E,handleKpiTrendlineGranularityChange:_,handleKpiTargetValueChange:k,cardType:h}};function oy(e,t){var Ee,Ve,qe,Ae,yt;const{tokenProps:n}=Ge(),r=zs(),s=Ge().authToken||e,o=Me(je=>je.selectedConnectionId),i=Me(je=>je.card),{queryKey:a}=ffe(i),l=Me(je=>je.selectedDatamodelId),u=Me(je=>je.isDevMode),d=Me(je=>je.selectedDatabaseName),f=Me(je=>je.selectedSchemaName),h=Me(je=>je.selectedTableName),p=Me(je=>je.actions.setSelectedConnectionId),m=Me(je=>je.actions.setSelectedDatamodelId),g=Me(je=>je.actions.setSelectedDatabaseName),b=Me(je=>je.actions.setSelectedSchemaName),x=Me(je=>je.actions.setSelectedTableName);Me(je=>je.actions.setCardSql);const{setQueryConfig:y}=Qn();function v(je){var Mt;return o&&je==="API"?!1:o&&je==="S3"?!0:!(!o||!d||d==="NA"||((Mt=_==null?void 0:_.capabilities)==null?void 0:Mt.path.includes("schema"))&&!f)}function w(je){return o&&je?!(je==="API"||je==="S3"):!1}const{refetchConnections:j,connectionsData:S,isConnectionsLoading:N,isConnectionsError:E,selectedConnection:_}=Pa(e),{refetch:k,data:T,isLoading:M,isError:P}=pn({queryKey:["models",o],queryFn:()=>qn(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),A=_==null?void 0:_.type,R=(_==null?void 0:_.type)==="API"||(_==null?void 0:_.type)==="S3",{data:L,isLoading:F,isFetching:U,isError:$,refetch:I}=pn({queryKey:["databases",o],queryFn:()=>qn(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:w(A)}),{data:B,isLoading:z,isFetching:O,isError:q,refetch:V}=pn({queryKey:["schemas",o,d],queryFn:()=>qn(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&!R&&d!=="NA"}),{data:Y,isLoading:W,isFetching:H,isError:G,refetch:Z}=pn({queryKey:["tables",o,d,f],queryFn:()=>qn(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(A)}),{columns:J,isColumnsLoading:Q,isColumnsFetching:re,isColumnsError:ie,refetchColumns:fe}=DH(e);C.useEffect(()=>{(A==="S3"||A==="API")&&(g(""),b(""),m(""),A==="API"&&x("api"))},[A,x,g,b,m]);const le=(_==null?void 0:_.type)==="API"?(Ee=_==null?void 0:_.type)==null?void 0:Ee.toLowerCase():h||"",Ce=R?"":f||"";function he(je){x(je),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function te(je){b(je),x("")}function oe(je){g(je==="none"?"":je),b(""),x(""),je!=="none"&&je!==""&&m("")}function me(je){p(je)}function _e(je){m(je==="none"?"":je),je!=="none"&&je!==""&&g("")}L&&((Ve=L==null?void 0:L.databases)==null?void 0:Ve.length)>0,B&&((qe=B==null?void 0:B.schemas)==null?void 0:qe.length)>0;const ue=S==null?void 0:S.connections.map(je=>({id:je.id,name:je.name,type:je.type})),De=(Ae=T==null?void 0:T.datamodels)==null?void 0:Ae.map(je=>({id:je.id,name:je.name})),Ue=L==null?void 0:L.databases.map(je=>({id:je.database_name,name:je.database_name})),ae=B==null?void 0:B.schemas.map(je=>({id:je.schema_name,name:je.schema_name})),ye=Y==null?void 0:Y.tables.map(je=>({id:je.table_name,name:je.table_name})),$e=(yt=T==null?void 0:T.datamodels.find(je=>je.id===l))==null?void 0:yt.name,pe=mv({schemaName:Ce,tableName:le,modelName:$e,connectionType:A,databaseName:d||""});return{connectionItems:ue,selectedConnectionId:o,selectedConnection:_,isConnectionsLoading:N,isConnectionsError:E,modelItems:De,selectedDatamodelId:l,selectedDatamodelName:$e,isModelsLoading:M,isModelsError:P,selectedDatabaseName:d,databaseItems:Ue,isDatabasesLoadingOrFetching:F||U,isDatabaseError:$,schemaItems:ae,selectedSchemaName:f,isSchemaLoadingOrFetching:z||O,isSchemaError:q,tableItems:ye,selectedTableName:h,isTableLoadingOrFetching:W||H,isTableError:G,columns:J,isColumnsLoadingOrFetching:Q||re,isColumnsError:ie,isNonDbConnection:R,connectionType:A,tableName:le,formattedTableName:pe,schemaName:Ce,refetchConnections:j,refetchModels:k,refetchDatabases:I,refetchSchemas:V,refetchTables:Z,refetchColumns:fe,handleConnectionChange:me,handleDatamodelChange:_e,handleDatabaseChange:oe,handleSchemaChange:te,handleTableChange:he}}function P0(e){return`${e}-${yr()}`}function kL(e,t){const n=Jo(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 AZe(e,t){const n=Jo(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 WI(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 GJ(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function KJ(){const e=Me(S=>S.sqlGen),t=Me(S=>S.isDevMode),n=Me(S=>S.card.dataSource),r=Me(S=>{var N,E;return(E=(N=S.card)==null?void 0:N.queryConfig)==null?void 0:E.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=WI(n),a=GJ(n),l=Me(S=>S.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:p,setIsShowingVisual:m}=Qn(),{connectionType:g,modelItems:b,selectedDatamodelName:x}=oy(),y=S=>({column_name:S.name,data_type:S.dataType,label:S.label,description:S.description});return{handleDevModeFieldClick:S=>{var E;if(!t)return;const N=y(S);if(t&&a&&s){const _=I_(N,e);p(_);const k=(E=b==null?void 0:b.find(M=>M.id===l))==null?void 0:E.name,T=R_(_,vi(o||""),vi(s),k||"",g,i||"");T&&(f(T),h(!0))}else if(!t){if(Hb(N.data_type))if(r&&r.length>0){const _={...N,role:"groupby",id:P0(N.column_name),name:N.column_name,type:N.data_type};d(_)}else{const _={...N,role:"metric",id:P0(N.column_name),name:N.column_name,label:kL(N.column_name,"COUNT"),type:N.data_type,aggregate:"COUNT"};u(_)}if(Ti(N.data_type)){const _={...N,role:"groupby",id:P0(N.column_name),name:N.column_name,type:N.data_type,label:AZe(N.column_name,"month"),granularity:"month"};d(_)}if(Mi(N.data_type)){const _={...N,role:"metric",id:P0(N.column_name),name:N.column_name,label:kL(N.column_name,"SUM"),type:N.data_type,aggregate:"SUM"};u(_)}}},handleShowSample:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const S=mv({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});m(!1);const N=g==="MSSQL"?`SELECT top 10 * FROM ${S}`:`SELECT * FROM ${S} LIMIT 10`;f(N),h(!0)},handleShowCount:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const S=mv({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});f(`SELECT COUNT(*) as count FROM ${S}`),h(!0)},isNumberField:S=>Mi(S.dataType)}}function PZe({columnName:e,database:t,schemaName:n,tableName:r,connectionType:s,datamodelId:o,modelName:i,field:a}){const l=vi(e),u=vi(t||""),d=vi(n||""),f=vi(r);let h=n1({schemaName:d,tableName:f,connectionType:s,databaseName:u}),p=`${h}.${l}`;return o&&o!=="none"&&i&&(p=`${Ag}.${i}.${l}`,h=`${Ag}.${i}`),a!=null&&a.qualifiedFieldName&&(p=a.qualifiedFieldName,h=a.qualifiedFieldName.split(".").slice(0,-1).join(".")),{qualifiedColumnName:p,qualifiedTableName:h,formattedColumnName:l,formattedTableName:f,formattedDatabase:u,formattedSchemaName:d}}function ZJ(){const e=Me(m=>m.selectedConnectionId),t=Me(m=>m.selectedDatamodelId),n=Me(m=>m.selectedDatabaseName),r=Me(m=>m.selectedSchemaName),s=Me(m=>m.selectedTableName),o=X(m=>m.dashboard.filters)||[],i=X(m=>m.selectedSheetId),a=X(m=>m.actions.addFilter),l=X(m=>m.actions.removeFilter),{removeFilterValues:u}=Ft(),{modelItems:d,tableName:f,connectionType:h}=oy();function p(m,g="sheet",b){var E;const x=(E=d==null?void 0:d.find(_=>_.id===t))==null?void 0:E.name,{qualifiedColumnName:y,qualifiedTableName:v,formattedColumnName:w,formattedTableName:j,formattedDatabase:S}=PZe({columnName:m.column_name,database:n,schemaName:r,tableName:f,connectionType:h,datamodelId:t,modelName:x,field:b});let N;if(g==="sheet"&&i?N=r2e(o,y,j,n||"",S,i):N=o==null?void 0:o.find(_=>_.column===y&&_.table===j&&(_.database===S||_.database===n)),N)u(N.id),l(N.id);else{const _=yr(),k=g==="sheet"&&i?[i]:void 0;return f==="api"&&e?(a({location:g,id:_,column:y,title:m.label||m.column_name,dataType:m.data_type,table:"api",database:"",connectionId:e,operation:"in",applyToSheetIds:k,sql:vE(m.data_type,v,w)}),_):(a({id:_,location:g,column:y,title:m.label||m.column_name,dataType:m.data_type,table:s||"",database:n||"",connectionId:e||"",operation:"in",applyToSheetIds:k,sql:vE(m.data_type,v,(b==null?void 0:b.qualifiedFieldName)||w)}),_)}}return{assignFilter:p}}function OZe({column:e}){const[t,n]=C.useState(!1),r=Me(x=>x.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=WI(r),a=Me(x=>x.selectedDatamodelId),l=Me(x=>x.sqlGen),{modelItems:u,connectionType:d}=oy(),f=Me(x=>x.actions.setSqlGen),h=Me(x=>x.actions.setCardSql),p=Me(x=>x.actions.setRunSql),m=GJ(r);function g(x,y){var S;if(!m||!s){console.warn("Cannot generate SQL: missing table metadata");return}const v=I_(x,l,y),w=(S=u==null?void 0:u.find(N=>N.id===a))==null?void 0:S.name;f(v);const j=R_(v,vi(o||""),vi(s),w||"",d,i||"");j&&(h(j),p(!0)),n(!1)}function b(){return c.jsxs("ul",{className:"text-xs",children:[c.jsx("li",{onClick:()=>g(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),c.jsx("li",{onClick:()=>g(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),c.jsx("li",{onClick:()=>g(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),c.jsx("li",{onClick:()=>g(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),c.jsx("li",{onClick:()=>g(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return m?c.jsxs(yp,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(vp,{asChild:!0,children:c.jsx(tp,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(ef,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]}):null}function FZe({field:e,fieldState:t}){return c.jsxs("div",{className:"w-64 bg-background p-0",children:[c.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[c.jsx("h3",{className:"text-sm font-medium text-foreground",children:e.label||e.name}),c.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:e.dataType})]}),e.description&&c.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:e.description}),t&&t.tooltip&&c.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:c.jsx("p",{className:"text-xs text-muted-foreground",children:t.tooltip})}),c.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:c.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:e.name})})]})}function $Ze({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s}){const o=Me(Y=>Y.isDevMode),i=t==="filter"||t==="inline-filter",a=o||i||(n==null?void 0:n.state)==="unreachable"&&!i,l=X(Y=>Y.dashboard.filters),u=X(Y=>Y.selectedSheetId),d=X(Y=>Y.actions.removeFilter),{removeFilterValues:f}=Ft(),{assignFilter:h}=ZJ(),p=t==="filter"?Ll(l,u):l,m=t==="filter"?p==null?void 0:p.find(Y=>{var W;return Y.title===e.name||((W=Y.column)==null?void 0:W.includes(e.name))}):void 0,g=!!m,b=t==="inline-filter"&&(s==null?void 0:s.some(Y=>Y.column===e.qualifiedFieldName||Y.column===e.name)),x=g||b,y=m&&i?l==null?void 0:l.find(Y=>Y.id===m.id):void 0,v=y&&(y.applyToSheetIds&&y.applyToSheetIds.length>1||y.excludeSheetIds&&y.excludeSheetIds.length>0||!y.applyToSheetIds&&!y.excludeSheetIds&&!y.sheetId);i&&x&&console.log("[SourceField Debug]",{fieldName:e.name,hasActiveFilter:x,activeFilterOnSheet:m?{id:m.id,title:m.title,column:m.column,applyToSheetIds:m.applyToSheetIds,excludeSheetIds:m.excludeSheetIds}:null,activeFilterForField:y?{id:y.id,title:y.title,column:y.column,applyToSheetIds:y.applyToSheetIds,excludeSheetIds:y.excludeSheetIds}:null,isMultiSheetFilter:v,selectedSheetId:u});const[w,j]=C.useState(!1),[S,N]=C.useState(null),{attributes:E,listeners:_,setNodeRef:k,transform:T,transition:M,isDragging:P}=Xx({id:e.id,disabled:a}),[A,R]=C.useState(!1),L=Me(Y=>Y.card),{handleFieldClick:F}=YJ(L),{handleDevModeFieldClick:U,isNumberField:$}=KJ(),I=()=>{y&&(console.log("[SourceField] Removing multi-sheet filter:",y.id),f(y.id),d(y.id)),N(null),j(!1)},B=()=>{if(t==="inline-filter"&&r){r(e);return}if(t==="filter"){const Y={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description,qualifiedFieldName:e.qualifiedFieldName};x&&v?(N({column:Y,field:e}),j(!0)):h(Y,"sheet",e)}else o?U(e):F(e)},z={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},O={transform:ri.Transform.toString(T),transition:M},V=(()=>{if(!n||i)return{};const W={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",...W},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...W},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...W}}[n.state]||W})();return c.jsxs("div",{ref:k,style:O,...a?{}:E,...a?{}:_,className:K("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",P&&"scale-95 opacity-50",!P&&"border",V.borderColor||"border-transparent",V.bgColor||"",V.hoverBorderColor,V.hoverBgColor||"hover:bg-muted",V.opacity,V.cursor,g&&"border-accent-foreground/20 bg-accent",b&&"border-primary/20 bg-primary/10",{"cursor-pointer":o||i,"cursor-grab active:cursor-grabbing":!a&&!o&&!i}),title:n==null?void 0:n.tooltip,children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:B,children:[xb(e.dataType),c.jsx(Mn,{children:c.jsxs(Xt,{children:[c.jsx(Qt,{asChild:!0,children:c.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:c.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${A?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),c.jsx(tn,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:c.jsx(FZe,{field:e,fieldState:n})})]})}),o&&!i&&$(e)&&c.jsx("div",{onClick:Y=>Y.stopPropagation(),children:c.jsx(OZe,{column:z})})]}),A&&c.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:c.jsx(Eo,{className:"",children:c.jsxs(Ii,{className:"space-y-2 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Cz,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.label||e.name})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(roe,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.name})]}),c.jsx(Fe,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),c.jsx(ax,{open:w,onOpenChange:j,children:c.jsxs(fp,{children:[c.jsxs(hp,{children:[c.jsx(mp,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(gp,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(pp,{children:[c.jsx(xp,{children:"Cancel"}),c.jsx(bp,{onClick:I,children:"Remove Filter"})]})]})})]})}const LZe="SEMAPHOR_CALCULATED_FIELD",zZe=["MM-DD-YYYY","YYYY-MM-DD","MM/DD/YYYY","DD/MM/YYYY","MMMM DD, YYYY","MMM DD, YYYY","DD MMM YYYY","Week of MMM DD, YYYY","Week of MMMM DD, YYYY","YYYY-WW","MMM YYYY","MMMM YYYY","YYYY-MM","MM/YYYY","YYYY MMM","Q1 YYYY","YYYY Q1","1st Quarter YYYY","YYYY-Q1","Quarter 1, YYYY","YYYY","YY","custom"];function XJ(e){return!!e.expression}function BZe(e){return!!e.expression}function VZe(e){return!!e.expression}var QJ=(e=>(e.SUBTOTAL="__SUBTOTAL__",e.TOTAL="__TOTAL__",e.ALL="__ALL__",e))(QJ||{}),Yi="Accordion",HZe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[qI,UZe,WZe]=Zb(Yi),[pC]=Nr(Yi,[WZe,fU]),YI=fU(),JJ=C.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(qI.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(KZe,{...o,ref:t}):c.jsx(GZe,{...s,ref:t})})});JJ.displayName=Yi;var[eee,qZe]=pC(Yi),[tee,YZe]=pC(Yi,{collapsible:!1}),GZe=C.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,l]=Br({prop:n,defaultProp:r??"",onChange:s,caller:Yi});return c.jsx(eee,{scope:e.__scopeAccordion,value:C.useMemo(()=>a?[a]:[],[a]),onItemOpen:l,onItemClose:C.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(tee,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(nee,{...i,ref:t})})})}),KZe=C.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i,a]=Br({prop:n,defaultProp:r??[],onChange:s,caller:Yi}),l=C.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=C.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return c.jsx(eee,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(tee,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(nee,{...o,ref:t})})})}),[ZZe,mC]=pC(Yi),nee=C.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=C.useRef(null),l=rt(a,t),u=UZe(n),f=Zc(s)==="ltr",h=ke(e.onKeyDown,p=>{var E;if(!HZe.includes(p.key))return;const m=p.target,g=u().filter(_=>{var k;return!((k=_.ref.current)!=null&&k.disabled)}),b=g.findIndex(_=>_.ref.current===m),x=g.length;if(b===-1)return;p.preventDefault();let y=b;const v=0,w=x-1,j=()=>{y=b+1,y>w&&(y=v)},S=()=>{y=b-1,y<v&&(y=w)};switch(p.key){case"Home":y=v;break;case"End":y=w;break;case"ArrowRight":o==="horizontal"&&(f?j():S());break;case"ArrowDown":o==="vertical"&&j();break;case"ArrowLeft":o==="horizontal"&&(f?S():j());break;case"ArrowUp":o==="vertical"&&S();break}const N=y%x;(E=g[N].ref.current)==null||E.focus()});return c.jsx(ZZe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(qI.Slot,{scope:n,children:c.jsx(ze.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),Gw="AccordionItem",[XZe,GI]=pC(Gw),ree=C.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=mC(Gw,n),i=qZe(Gw,n),a=YI(n),l=ir(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(XZe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(mU,{"data-orientation":o.orientation,"data-state":cee(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});ree.displayName=Gw;var see="AccordionHeader",oee=C.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=mC(Yi,n),o=GI(see,n);return c.jsx(ze.h3,{"data-orientation":s.orientation,"data-state":cee(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});oee.displayName=see;var p_="AccordionTrigger",iee=C.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=mC(Yi,n),o=GI(p_,n),i=YZe(p_,n),a=YI(n);return c.jsx(qI.ItemSlot,{scope:n,children:c.jsx(oSe,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});iee.displayName=p_;var aee="AccordionContent",lee=C.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=mC(Yi,n),o=GI(aee,n),i=YI(n);return c.jsx(iSe,{role:"region","aria-labelledby":o.triggerId,"data-orientation":s.orientation,...i,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...e.style}})});lee.displayName=aee;function cee(e){return e?"open":"closed"}var QZe=JJ,JZe=ree,eXe=oee,uee=iee,dee=lee;const fee=QZe,KI=D.forwardRef(({className:e,...t},n)=>c.jsx(JZe,{ref:n,className:K("border-b",e),...t}));KI.displayName="AccordionItem";const ZI=D.forwardRef(({className:e,children:t,...n},r)=>c.jsx(eXe,{className:"flex",children:c.jsxs(uee,{ref:r,className:K("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,c.jsx(fr,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));ZI.displayName=uee.displayName;const XI=D.forwardRef(({className:e,children:t,...n},r)=>c.jsx(dee,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:c.jsx("div",{className:K("pb-4 pt-0",e),children:t})}));XI.displayName=dee.displayName;function hee({context:e="editor",onFieldSelect:t,inlineFilters:n}={}){var R,L,F,U;const[r,s]=C.useState(""),[o,i]=C.useState("all");Me($=>$.isDevMode);const a=Me($=>$.card.dataSource),l=Me($=>$.card.config),u=Me($=>$.card),{autoJoinMetadata:d}=ka(u),{columns:f=[],columnGroups:h=[],isLoading:p,error:m}=OT(),g=(a==null?void 0:a.mode)==="semanticDomain"?a.semanticDomainId:void 0,{data:b}=UI(g),x=[...(l==null?void 0:l.groupByColumns)||[],...(l==null?void 0:l.metricColumns)||[]];(L=(R=l==null?void 0:l.joinPlan)==null?void 0:R.baseEntity)==null||L.name,(U=(F=d==null?void 0:d.resolvedJoinPlan)==null?void 0:F.baseEntity)==null||U.name,KJ();const y=f.filter($=>$.name.toLowerCase().includes(r.toLowerCase())||$.dataType.toLowerCase().includes(r.toLowerCase())||$.label&&$.label.toLowerCase().includes(r.toLowerCase())||$.qualifiedEntityName&&$.qualifiedEntityName.toLowerCase().includes(r.toLowerCase())),v=$=>{if($.role==="metric"&&XJ($)||$.role==="groupby"&&$.expression)return"calculated";if($.dataType==="number"||$.dataType==="integer"||$.dataType==="float"||$.dataType==="decimal"||$.dataType==="currency")return"metrics";const I=Tr($.dataType);return["date","string","boolean"].includes(I)?"dimensions":I==="number"?"metrics":"dimensions"},j=(o==="all"?y:y.filter($=>v($)===o)).reduce(($,I)=>{const B=I.qualifiedEntityName||"Other Fields";return $[B]||($[B]={label:L_(I.entityName),fields:[]}),$[B].fields.push(I),$},{}),N=Object.keys(j),E=y.filter($=>v($)==="dimensions").length,_=y.filter($=>v($)==="metrics").length,k=y.filter($=>v($)==="calculated").length,T=y.length>0&&e!=="inline-filter",M=e==="inline-filter"?"w-full":"w-[290px]";if(p)return c.jsx("div",{className:K("flex h-full flex-col items-center justify-center py-8",M),children:c.jsx(Wc,{size:"md",color:"muted","aria-label":"Loading data"})});if(m)return c.jsxs("div",{className:K("flex h-full flex-col items-center justify-center py-8",M),children:[c.jsx(vl,{className:"mb-4 h-12 w-12 text-red-300"}),c.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),c.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:m.message||"Failed to load column data"})]});if(!a||!a.selectedEntities||a.selectedEntities.length===0)return c.jsxs("div",{className:K("flex flex-col items-center justify-center py-8 text-center",M),children:[c.jsx(vl,{className:"mb-4 h-12 w-12 text-gray-300"}),c.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),c.jsx("p",{className:"px-4 text-xs text-gray-400",children:e==="filter"||e==="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 P=e==="inline-filter"?"px-3 pb-3":"px-6 pb-6",A=e==="inline-filter"?"overflow-hidden":"";return c.jsxs("div",{className:K("mt-2 flex h-full w-full grow flex-col gap-2",P,A),children:[c.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[f.length>0&&c.jsxs("div",{className:"relative",children:[c.jsx(Vi,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),c.jsx(xn,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:r,onChange:$=>s($.target.value)}),r&&c.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>s(""),type:"button",children:c.jsx(vt,{className:"size-3.5"})})]}),T&&c.jsx(Bs,{defaultValue:"all",value:o,onValueChange:$=>i($),className:"mb-4",children:c.jsxs(ws,{className:"grid h-9 w-full grid-cols-4",children:[c.jsxs(Kt,{value:"all",className:"text-xs",children:["All",c.jsx("span",{className:"ml-2 text-xs font-semibold",children:y.length})]}),c.jsxs(Kt,{value:"dimensions",className:"text-xs",children:[c.jsx(f1,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:E})]}),c.jsxs(Kt,{value:"metrics",className:"text-xs",children:[c.jsx(ep,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:_})]}),c.jsxs(Kt,{value:"calculated",className:"text-xs",children:[c.jsx(Y_,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:k})]})]})})]}),c.jsxs(zl,{className:"min-h-0 overflow-auto",children:[c.jsx(fee,{type:"multiple",defaultValue:N,className:"space-y-2",children:Object.entries(j).map(([$,I])=>{const B=h.find(z=>z.entityName===$)||{entityName:$,label:I.label};return c.jsxs(KI,{value:$,className:"border-none",children:[c.jsx(ZI,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{title:B.label||B.entityName,className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:B.label||B.entityName}),c.jsx(Fe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:I.fields.length})]})}),c.jsx(XI,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:I.fields.map(z=>{const O=FT(z,{joinabilityMap:(b==null?void 0:b.joinabilityMap)||null,selectedFields:x,cardConfig:l,autoJoinMetadata:d});return c.jsx($Ze,{field:z,context:e,fieldState:O,onFieldSelect:t,inlineFilters:e==="inline-filter"?n:void 0},z.id)})})})]},$)})}),Object.keys(j).length===0&&f.length===0&&c.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[c.jsx("p",{children:"No fields found for selected data source"}),c.jsx("p",{className:"mt-1 text-xs text-gray-400",children:e==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),Object.keys(j).length===0&&f.length>0&&c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),c.jsx(ti,{orientation:"horizontal"}),c.jsx(ti,{orientation:"vertical"})]})]})}function pee({context:e="editor"}={}){return c.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",c.jsx(hee,{context:e})," "]})}function mee(){const e=Me(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=Qn();C.useEffect(()=>{var p;if(!e)return;const{tableName:i,schemaName:a,databaseName:l,connectionId:u}=WI(e),d=(p=e.selectedEntities)==null?void 0:p[0],h=(d==null?void 0:d.type)==="model"&&"id"in d?d.id:"";t(u||""),n(l||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function tXe(){mee();const e=X(l=>l.selectedSheetId),t=X(l=>l.selectedFrameId),n=X(l=>l.dashboard),r=X(l=>l.actions.getSelectedFrame),{setSelectedFrameId:s}=Ft(),{setCard:o}=Qn(),i=Me(l=>l.card.dataSource);return C.useEffect(()=>{var u,d;let l=r();if(!l){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(p=>p.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),l=h)}if(l){const f=l.cards.find(h=>h.id===l.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function nXe(){const e=X(o=>o.dashboard.filterLayout),{setFilterLayout:t}=Ft(),n=(e==null?void 0:e.displayMode)||"canvas",r=(e==null?void 0:e.toolbarWrap)??!1,s=(e==null?void 0:e.showDownloadButton)??!1;return c.jsxs(Qr,{children:[c.jsx(Jr,{asChild:!0,children:c.jsx(se,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0","aria-label":"Filter display settings",children:c.jsx(wl,{className:"h-4 w-4"})})}),c.jsx(es,{className:"w-[280px]",align:"end",children:c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{children:[c.jsx("h4",{className:"mb-3 text-sm font-medium",children:"Filter Display"}),c.jsxs(ro,{value:n,onValueChange:o=>t({displayMode:o}),className:"space-y-2",children:[c.jsxs("div",{className:"flex items-start space-x-3",children:[c.jsx(Cn,{value:"canvas",id:"canvas",className:"mt-0.5"}),c.jsxs("div",{className:"grid gap-0.5",children:[c.jsx(ce,{htmlFor:"canvas",className:"cursor-pointer font-normal",children:"Canvas Cards"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Filters as draggable, resizable cards on the dashboard"})]})]}),c.jsxs("div",{className:"flex items-start space-x-3",children:[c.jsx(Cn,{value:"toolbar",id:"toolbar",className:"mt-0.5"}),c.jsxs("div",{className:"grid gap-0.5",children:[c.jsx(ce,{htmlFor:"toolbar",className:"cursor-pointer font-normal",children:"Toolbar"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Compact horizontal toolbar below dashboard controls"})]})]})]})]}),n==="toolbar"&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-center space-x-2 border-t pt-4",children:[c.jsx(Jt,{id:"wrap",checked:r,onCheckedChange:o=>t({toolbarWrap:o===!0})}),c.jsx(ce,{htmlFor:"wrap",className:"cursor-pointer text-sm font-normal",children:"Wrap filters to multiple lines"})]}),c.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[c.jsx(Jt,{id:"download",checked:s,onCheckedChange:o=>t({showDownloadButton:o===!0})}),c.jsx(ce,{htmlFor:"download",className:"cursor-pointer text-sm font-normal",children:"Show download button"})]})]}),c.jsx("p",{className:"border-t pt-3 text-xs text-muted-foreground",children:"Individual filters can override this setting in their configuration."})]})})]})}function rXe(){const e=X(n=>n.actions.setShowFilters),{hasEntities:t}=tXe();return c.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col overflow-hidden border-l",children:[c.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[c.jsx(ce,{className:"px-2 text-base",children:"Dashboard Filters"}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(nXe,{}),c.jsx(se,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:c.jsx(ZK,{})})]})]}),!t&&c.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[c.jsx(vl,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),c.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&c.jsx("div",{className:"flex grow overflow-y-auto",children:c.jsx(Kx,{collisionDetection:qx,children:c.jsx(Zx,{items:[],strategy:eI,children:c.jsx(pee,{context:"filter"})})})})]})}function sXe(){const e=X(r=>r.dashboard.filters),t=X(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?c.jsx("div",{className:K("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>c.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[c.jsx(YR,{filter:r}),c.jsx(Xp,{filter:r})]},r.id))}):null}function oXe(){const e=X(r=>r.showFilters),t=X(r=>r.isVisualEditing),n=X(r=>r.isDashboardEditing);return c.jsxs("div",{role:"dashboard-plus-main",className:K("",{"max-h-0 overflow-hidden":t,"flex grow overflow-hidden":!t}),children:[c.jsxs("section",{className:"flex grow flex-col overflow-y-auto",children:[n&&c.jsx(sXe,{}),c.jsx(VJ,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:c.jsx(rXe,{})})]})}const iXe=C.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-Baw7eUyM.js"))),aXe=C.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-BMElXt-n.js"))),lXe=C.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-Cz4bNnCC.js"))),cXe=C.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-Buhi-kvP.js")).then(e=>({default:e.ResourceManagementPanel})));function uXe({showControls:e=!1,showFooter:t=!0,...n}){const r=X(l=>l.isDashboardPanelOpen),s=X(l=>l.isVisualEditing),o=X(l=>l.showDashboardJSON),i=X(l=>l.actions.setIsDashboardPanelOpen),{preferences:a}=n;return c.jsx(Ba,{FallbackComponent:FS,children:c.jsxs(q_,{dashboardProps:n,children:[c.jsx(Qce,{}),c.jsx(HI,{componentType:"surfboard",componentId:n.id}),c.jsx(VI,{children:c.jsxs(HJ,{preferences:a,children:[o&&c.jsx(C.Suspense,{fallback:null,children:c.jsx(lXe,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&c.jsx(C.Suspense,{fallback:null,children:c.jsx(iXe,{})}),c.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&c.jsx(C.Suspense,{fallback:null,children:c.jsx(cXe,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),c.jsx("div",{className:"flex min-w-0 flex-1",children:c.jsxs(cD,{...n,type:"dashboard",children:[s&&c.jsx(C.Suspense,{fallback:null,children:c.jsx(aXe,{})}),c.jsx(oXe,{})]})})]})]})]})})]})})}var dXe=Object.defineProperty,fXe=(e,t,n)=>t in e?dXe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,O0=(e,t,n)=>fXe(e,typeof t!="symbol"?t+"":t,n);const hXe={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},pXe={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}},mXe={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function gXe(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function gee(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const bXe={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=gee(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},xXe={stringify:e=>`${e}`,parse:e=>parseFloat(e)},yXe={stringify:e=>e,parse:e=>e},a2={string:yXe,number:xXe,boolean:hXe,function:pXe,method:bXe,json:mXe},Mm=Symbol.for("r2wc.render"),F0=Symbol.for("r2wc.connected"),Eu=Symbol.for("r2wc.context"),fo=Symbol.for("r2wc.props");function vXe(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),l={},u={},d={},f={};for(const p of i){l[p]=Array.isArray(t.props)?"string":t.props[p];const m=gXe(p);d[p]=m,f[m]=p}for(const p of a)u[p]=Array.isArray(t.events)?{}:t.events[p];class h extends HTMLElement{constructor(){super(),O0(this,o,!0),O0(this,s),O0(this,r,{}),O0(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[fo].container=this.container;for(const m of i){const g=d[m],b=this.getAttribute(g),x=l[m],y=x?a2[x]:null;if(x==="method"){const v=gee(g);Object.defineProperty(this[fo].container,v,{enumerable:!0,configurable:!0,get(){return this[fo][v]},set(w){this[fo][v]=w,this[Mm]()}}),this[fo][m]=y.parse(b,g,this)}y!=null&&y.parse&&b&&(this[fo][m]=y.parse(b,g,this))}for(const m of a)this[fo][m]=g=>{const b=m.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[m]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[F0]=!0,this[Mm]()}disconnectedCallback(){this[F0]=!1,this[Eu]&&n.unmount(this[Eu]),delete this[Eu]}attributeChangedCallback(m,g,b){const x=f[m],y=l[x],v=y?a2[y]:null;x in l&&v!=null&&v.parse&&b&&(this[fo][x]=v.parse(b,m,this),this[Mm]())}[(o=F0,s=Eu,r=fo,Mm)](){this[F0]&&(this[Eu]?n.update(this[Eu],this[fo]):this[Eu]=n.mount(this.container,e,this[fo]))}}for(const p of i){const m=d[p],g=l[p];Object.defineProperty(h.prototype,p,{enumerable:!0,configurable:!0,get(){return this[fo][p]},set(b){this[fo][p]=b;const x=g?a2[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,m,this);this.getAttribute(m)!==y&&this.setAttribute(m,y)}else this[Mm]()}})}return h}function wXe(e,t,n){const r=Pte.createRoot(e),s=C.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function SXe({root:e,ReactComponent:t},n){const r=C.createElement(t,n);e.render(r)}function CXe({root:e}){e.unmount()}function jXe(e,t={}){return vXe(e,t,{mount:wXe,update:SXe,unmount:CXe})}const NXe={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"},kXe=jXe(UJ,{props:NXe});function EL(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 EXe(e){if(Array.isArray(e))return e}function _Xe(e,t,n){return(t=PXe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function MXe(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,s,o,i,a=[],l=!0,u=!1;try{if(o=(n=n.call(e)).next,t!==0)for(;!(l=(r=o.call(n)).done)&&(a.push(r.value),a.length!==t);l=!0);}catch(d){u=!0,s=d}finally{try{if(!l&&n.return!=null&&(i=n.return(),Object(i)!==i))return}finally{if(u)throw s}}return a}}function TXe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1072
+ `)}})}});var RKe=NGe(()=>xJ(si([Kn({type:Rt("text-start"),id:st(),providerMetadata:cr.optional()}),Kn({type:Rt("text-delta"),id:st(),delta:st(),providerMetadata:cr.optional()}),Kn({type:Rt("text-end"),id:st(),providerMetadata:cr.optional()}),Kn({type:Rt("error"),errorText:st()}),Kn({type:Rt("tool-input-start"),toolCallId:st(),toolName:st(),providerExecuted:qs().optional(),dynamic:qs().optional()}),Kn({type:Rt("tool-input-delta"),toolCallId:st(),inputTextDelta:st()}),Kn({type:Rt("tool-input-available"),toolCallId:st(),toolName:st(),input:na(),providerExecuted:qs().optional(),providerMetadata:cr.optional(),dynamic:qs().optional()}),Kn({type:Rt("tool-input-error"),toolCallId:st(),toolName:st(),input:na(),providerExecuted:qs().optional(),providerMetadata:cr.optional(),dynamic:qs().optional(),errorText:st()}),Kn({type:Rt("tool-output-available"),toolCallId:st(),output:na(),providerExecuted:qs().optional(),dynamic:qs().optional(),preliminary:qs().optional()}),Kn({type:Rt("tool-output-error"),toolCallId:st(),errorText:st(),providerExecuted:qs().optional(),dynamic:qs().optional()}),Kn({type:Rt("reasoning-start"),id:st(),providerMetadata:cr.optional()}),Kn({type:Rt("reasoning-delta"),id:st(),delta:st(),providerMetadata:cr.optional()}),Kn({type:Rt("reasoning-end"),id:st(),providerMetadata:cr.optional()}),Kn({type:Rt("source-url"),sourceId:st(),url:st(),title:st().optional(),providerMetadata:cr.optional()}),Kn({type:Rt("source-document"),sourceId:st(),mediaType:st(),title:st(),filename:st().optional(),providerMetadata:cr.optional()}),Kn({type:Rt("file"),url:st(),mediaType:st(),providerMetadata:cr.optional()}),Kn({type:hJ(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:st().optional(),data:na(),transient:qs().optional()}),Kn({type:Rt("start-step")}),Kn({type:Rt("finish-step")}),Kn({type:Rt("start"),messageId:st().optional(),messageMetadata:na().optional()}),Kn({type:Rt("finish"),finishReason:uJ(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:na().optional()}),Kn({type:Rt("abort")}),Kn({type:Rt("message-metadata"),messageMetadata:na()})])));function IKe(e){return e.type.startsWith("data-")}function kJ(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]=kJ(o,s):n[r]=s}return n}function AKe(e){const t=["ROOT"];let n=-1,r=null;function s(l,u,d){switch(l){case'"':{n=u,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,r=u,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function o(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":s(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=l,t.pop();break}default:{n=l,s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l)):n=l;break}}}let a=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?a+="true".slice(d.length):"false".startsWith(d)?a+="false".slice(d.length):"null".startsWith(d)&&(a+="null".slice(d.length))}}return a}async function EJ(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Ww({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Ww({text:AKe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function lv(e){return e.type.startsWith("tool-")}function PKe(e){return e.type==="dynamic-tool"}function u_(e){return lv(e)||PKe(e)}function CL(e){return e.type.split("-").slice(1).join("-")}function OKe({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 FKe({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await r(async({state:u,write:d})=>{var f,h,p,m;function g(w){const S=u.message.parts.filter(lv).find(N=>N.toolCallId===w);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function b(w){const S=u.message.parts.filter(N=>N.type==="dynamic-tool").find(N=>N.toolCallId===w);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function x(w){var j;const S=u.message.parts.find(_=>lv(_)&&_.toolCallId===w.toolCallId),N=w,E=S;S!=null?(S.state=w.state,E.input=N.input,E.output=N.output,E.errorText=N.errorText,E.rawInput=N.rawInput,E.preliminary=N.preliminary,E.providerExecuted=(j=N.providerExecuted)!=null?j:S.providerExecuted,N.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=N.providerMetadata)):u.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.state,input:N.input,output:N.output,rawInput:N.rawInput,errorText:N.errorText,providerExecuted:N.providerExecuted,preliminary:N.preliminary,...N.providerMetadata!=null?{callProviderMetadata:N.providerMetadata}:{}})}function y(w){var j,S;const N=u.message.parts.find(k=>k.type==="dynamic-tool"&&k.toolCallId===w.toolCallId),E=w,_=N;N!=null?(N.state=w.state,_.toolName=w.toolName,_.input=E.input,_.output=E.output,_.errorText=E.errorText,_.rawInput=(j=E.rawInput)!=null?j:_.rawInput,_.preliminary=E.preliminary,_.providerExecuted=(S=E.providerExecuted)!=null?S:N.providerExecuted,E.providerMetadata!=null&&N.state==="input-available"&&(N.callProviderMetadata=E.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:w.toolName,toolCallId:w.toolCallId,state:w.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(w){if(w!=null){const j=u.message.metadata!=null?kJ(u.message.metadata,w):w;t!=null&&await xL({value:j,schema:t}),u.message.metadata=j}}switch(a.type){case"text-start":{const w={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=w,u.message.parts.push(w),d();break}case"text-delta":{const w=u.activeTextParts[a.id];w.text+=a.delta,w.providerMetadata=(f=a.providerMetadata)!=null?f:w.providerMetadata,d();break}case"text-end":{const w=u.activeTextParts[a.id];w.state="done",w.providerMetadata=(h=a.providerMetadata)!=null?h:w.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const w={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=w,u.message.parts.push(w),d();break}case"reasoning-delta":{const w=u.activeReasoningParts[a.id];w.text+=a.delta,w.providerMetadata=(p=a.providerMetadata)!=null?p:w.providerMetadata,d();break}case"reasoning-end":{const w=u.activeReasoningParts[a.id];w.providerMetadata=(m=a.providerMetadata)!=null?m:w.providerMetadata,w.state="done",delete u.activeReasoningParts[a.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),d();break}case"tool-input-start":{const w=u.message.parts.filter(lv);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:w.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const w=u.partialToolCalls[a.toolCallId];w.text+=a.inputTextDelta;const{value:j}=await EJ(w.text);w.dynamic?y({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:j}):x({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:j}),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 w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-available",input:w.input,output:a.output,preliminary:a.preliminary})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:CL(w),state:"output-available",input:w.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-error",input:w.input,errorText:a.errorText,providerExecuted:a.providerExecuted})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:CL(w),state:"output-error",input:w.input,rawInput:w.rawInput,errorText:a.errorText,providerExecuted:a.providerExecuted})}d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{a.messageId!=null&&(u.message.id=a.messageId),await v(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&d();break}case"finish":{a.finishReason!=null&&(u.finishReason=a.finishReason),await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"message-metadata":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"error":{s==null||s(new Error(a.errorText));break}default:if(IKe(a)){(n==null?void 0:n[a.type])!=null&&await xL({value:a.data,schema:n[a.type]});const w=a;if(w.transient){i==null||i(w);break}const j=w.id!=null?u.message.parts.find(S=>w.type===S.type&&w.id===S.id):void 0;j!=null?j.data=w.data:u.message.parts.push(w),i==null||i(w),d()}}l.enqueue(a)})}}))}async function $Ke({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()}}sy({prefix:"aitxt",size:24});sy({prefix:"aiobj",size:24});var LKe=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()})}};sy({prefix:"aiobj",size:24});var zKe={};SKe(zKe,{object:()=>VKe,text:()=>BKe});var BKe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),VKe=({schema:e})=>{const t=vKe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await EJ(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 Ww({text:n});if(!s.success)throw new wL({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 FI({value:s.value,schema:t});if(!o.success)throw new wL({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 HKe(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async t=>{const{name:n,type:r}=t,s=await new Promise((o,i)=>{const a=new FileReader;a.onload=l=>{var u;o((u=l.target)==null?void 0:u.result)},a.onerror=l=>i(l),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var UKe=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 Ef(this.body),l=await Ef(this.headers),u=await Ef(this.credentials),d={...Ru(l),...Ru(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,p=(f==null?void 0:f.headers)!==void 0?Ru(f.headers):d,m=(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:gL({"Content-Type":"application/json",...p},`ai-sdk/${SL}`,mL()),body:JSON.stringify(m),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 Ef(this.body),a=await Ef(this.headers),l=await Ef(this.credentials),u={...Ru(a),...Ru(e.headers)},d=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:u,credentials:l,requestMetadata:e.metadata})),f=(n=d==null?void 0:d.api)!=null?n:`${this.api}/${e.chatId}/stream`,h=(d==null?void 0:d.headers)!==void 0?Ru(d.headers):u,p=(r=d==null?void 0:d.credentials)!=null?r:l,g=await((s=this.fetch)!=null?s:globalThis.fetch)(f,{method:"GET",headers:gL(h,`ai-sdk/${SL}`,mL()),credentials:p});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)}},LI=class extends UKe{constructor(e={}){super(e)}processResponseStream(e){return _Ge({stream:e,schema:RKe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},WKe=class{constructor({generateId:e=xGe,id:t=e(),transport:n=new LI,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new LKe,this.sendMessage=async(f,h)=>{var p,m,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(p=this.lastMessage)==null?void 0:p.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await HKe(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:(m=x.role)!=null?m:"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 p=f==null?this.state.messages.length-1:this.state.messages.findIndex(m=>m.id===f);if(p===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[p].role==="assistant"?p:p+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:p,output:m,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(w=>u_(w)&&w.toolCallId===p?{...w,state:f,output:m,errorText:g}:w)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(w=>u_(w)&&w.toolCallId===p?{...w,state:f,output:m,errorText:g}:w)),this.status!=="streaming"&&this.status!=="submitted"&&((b=this.sendAutomaticallyWhen)!=null&&b.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(x=this.lastMessage)==null?void 0:x.id})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=l,this.onData=u,this.sendAutomaticallyWhen=d}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:s}){var o,i,a,l;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;let d=!1,f=!1,h=!1;try{const p={state:OKe({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};p.abortController.signal.addEventListener("abort",()=>{d=!0}),this.activeResponse=p;let m;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}m=b}else m=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:p.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const g=b=>this.jobExecutor.run(()=>b({state:p.state,write:()=>{var x;this.setStatus({status:"streaming"}),p.state.message.id===((x=this.lastMessage)==null?void 0:x.id)?this.state.replaceMessage(this.state.messages.length-1,p.state.message):this.state.pushMessage(p.state.message)}}));await $Ke({stream:FKe({stream:m,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(p){if(d||p.name==="AbortError")return d=!0,this.setStatus({status:"ready"}),null;h=!0,p instanceof TypeError&&(p.message.toLowerCase().includes("fetch")||p.message.toLowerCase().includes("network"))&&(f=!0),this.onError&&p instanceof Error&&this.onError(p),this.setStatus({status:"error",error:p})}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(p){console.error(p)}this.activeResponse=void 0}(a=this.sendAutomaticallyWhen)!=null&&a.call(this,{messages:this.state.messages})&&!h&&await this.makeRequest({trigger:"submit-message",messageId:(l=this.lastMessage)==null?void 0:l.id,metadata:t,headers:n,body:r})}};function qKe({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(u_).filter(s=>!s.providerExecuted);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function YKe(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...o){clearTimeout(n);const i=Date.now(),a=i-r,l=t-a;l<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},l)}}var GKe=YKe;const KKe=Ud(GKe);var _J=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Fn=(e,t,n)=>(_J(e,t,"read from private field"),n?n.call(e):t.get(e)),Xi=(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)},Jl=(e,t,n,r)=>(_J(e,t,"write to private field"),t.set(e,n),n);function ZKe(e,t){return t!=null?KKe(e,t):e}var Po,cv,uv,Jm,eg,tg,Rf,d_,f_,XKe=class{constructor(e=[]){Xi(this,Po,void 0),Xi(this,cv,"ready"),Xi(this,uv,void 0),Xi(this,Jm,new Set),Xi(this,eg,new Set),Xi(this,tg,new Set),this.pushMessage=t=>{Jl(this,Po,Fn(this,Po).concat(t)),Fn(this,Rf).call(this)},this.popMessage=()=>{Jl(this,Po,Fn(this,Po).slice(0,-1)),Fn(this,Rf).call(this)},this.replaceMessage=(t,n)=>{Jl(this,Po,[...Fn(this,Po).slice(0,t),this.snapshot(n),...Fn(this,Po).slice(t+1)]),Fn(this,Rf).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?ZKe(t,n):t;return Fn(this,Jm).add(r),()=>{Fn(this,Jm).delete(r)}},this["~registerStatusCallback"]=t=>(Fn(this,eg).add(t),()=>{Fn(this,eg).delete(t)}),this["~registerErrorCallback"]=t=>(Fn(this,tg).add(t),()=>{Fn(this,tg).delete(t)}),Xi(this,Rf,()=>{Fn(this,Jm).forEach(t=>t())}),Xi(this,d_,()=>{Fn(this,eg).forEach(t=>t())}),Xi(this,f_,()=>{Fn(this,tg).forEach(t=>t())}),Jl(this,Po,e)}get status(){return Fn(this,cv)}set status(e){Jl(this,cv,e),Fn(this,d_).call(this)}get error(){return Fn(this,uv)}set error(e){Jl(this,uv,e),Fn(this,f_).call(this)}get messages(){return Fn(this,Po)}set messages(e){Jl(this,Po,[...e]),Fn(this,Rf).call(this)}};Po=new WeakMap;cv=new WeakMap;uv=new WeakMap;Jm=new WeakMap;eg=new WeakMap;tg=new WeakMap;Rf=new WeakMap;d_=new WeakMap;f_=new WeakMap;var If,jL=class extends WKe{constructor({messages:e,...t}){const n=new XKe(e);super({...t,state:n}),Xi(this,If,void 0),this["~registerMessagesCallback"]=(r,s)=>Fn(this,If)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>Fn(this,If)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>Fn(this,If)["~registerErrorCallback"](r),Jl(this,If,n)}};If=new WeakMap;function MJ({experimental_throttle:e,resume:t=!1,...n}={}){const r=C.useRef("chat"in n?n.chat:new jL(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new jL(n));const o="id"in n?n.id:null,i=C.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=C.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),l=C.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=C.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=C.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return C.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:a,setMessages:d,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:u,resumeStream:r.current.resumeStream,status:l,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput}}function QKe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function JKe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function eZe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function tZe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function TJ(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:tZe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function DJ(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 nZe(){var b;const{authToken:e,tokenProps:t}=Ge(),n=X(x=>x.dashboard.aiScopeTables),r=(b=i1().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=MJ({transport:new LI({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=Ui.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:_W(x)}})}),onToolCall:p,sendAutomaticallyWhen:qKe,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 p({toolCall:x}){if(x.toolName==="getCurrentTableScope"&&u({tool:x.toolName,toolCallId:x.toolCallId,output:{tables:TJ(n||[])}}),x.toolName==="getDashboardContext"){const y=X.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const m=!["ready","error"].includes(l),g=DJ(d);return{sendMessage:s,regenerate:a,isLoading:m,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function RJ(){var u;const{authToken:e,tokenProps:t}=Ge(),n=(u=i1().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=pn({queryKey:["assistant-profile",n],queryFn:()=>qn(`${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 IJ({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:c.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[c.jsxs("div",{className:"mb-3 flex items-center",children:[c.jsx(lz,{className:"mr-2 h-4 w-4 text-muted-foreground"}),c.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),c.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>c.jsx(se,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function qw(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(uM,{className:r});case"view":return c.jsx(Pc,{className:r});case"materialized view":return c.jsx(Bse,{className:r});case"model":return c.jsx(f1,{className:r});case"file":return c.jsx(Ai,{className:r});case"dataset":return c.jsx(vl,{className:r});case"upload":return c.jsx(pM,{className:r});case"url":return c.jsx(pz,{className:r});default:return c.jsx(u1,{className:r})}}const AJ=D.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(Vi,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(Cs.Input,{ref:n,className:K("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})]}));AJ.displayName=Cs.Input.displayName;const A0=e=>e.label||(e==null?void 0:e.name),NL=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function rZe({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:u}){const{tokenProps:d}=Ge(),f=(d==null?void 0:d.type)==="dashboard",[h,p]=C.useState(""),[m,g]=C.useState(""),b=s.filter(S=>{if(!h)return!0;const N=A0(S).toLowerCase(),E=NL(S).toLowerCase(),_=h.toLowerCase();return N.includes(_)||E.includes(_)});C.useEffect(()=>{e||(p(""),g(""))},[e]),C.useEffect(()=>{b.length>0&&!m&&g(A0(b[0]))},[b,m]);const x=()=>{if(!m)return;const S=b.find(N=>A0(N)===m);S&&(o.some(E=>"id"in S&&"id"in E?S.id===E.id:S.name===E.name&&S.connectionId===E.connectionId)||t(S),i(S),r())},y=S=>{(S.key==="Tab"||S.key==="Enter")&&(S.preventDefault(),x())};if(!e)return null;const v=S=>o.some(N=>"id"in S&&"id"in N?S.id===N.id:S.name===N.name&&S.connectionId===N.connectionId),w=o.length===s.length,j=o.length>0;return c.jsx(c.Fragment,{children:c.jsxs(Ip,{shouldFilter:!1,value:m,onValueChange:g,onKeyDown:y,children:[s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[c.jsx(AJ,{placeholder:"Search entities...",value:h,onValueChange:p,className:"flex-1 border-0",autoFocus:!0}),!f&&c.jsxs(se,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u==null||u()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[c.jsx(wr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[c.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(se,{onClick:S=>{S.preventDefault(),S.stopPropagation(),a==null||a()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},disabled:w,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),j&&c.jsxs(se,{onClick:S=>{S.preventDefault(),S.stopPropagation(),l==null||l()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[c.jsx(vt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),c.jsxs(Ap,{className:"min-h-60",children:[c.jsx(Pp,{children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[c.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&c.jsxs(se,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u==null||u()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[c.jsx(wr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx(Op,{children:b.map((S,N)=>{const E=v(S),_="id"in S?S.id:`${S.connectionId}-${S.name}`,k=A0(S);return c.jsxs(Fp,{value:k,onSelect:()=>{E?n==null||n(S):t(S)},onMouseDown:T=>{T.preventDefault(),T.stopPropagation()},className:K("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[c.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:qw(S.type)}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate font-medium",children:k}),c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:NL(S)})]}),E&&c.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:c.jsx(Mr,{className:"h-3 w-3 text-background"})})]},_)})})]})]})})}const h_=e=>e.name||e.name,sZe=e=>{const t=h_(e),n="description"in e?e.description:"",r=e.database||"",s=e.schema||"";return c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"font-medium",children:t}),n&&c.jsx("div",{className:"text-sm text-muted-foreground",children:n}),c.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,s&&` • Schema: ${s}`]})]})};function oZe({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r}){const[s,o]=C.useState(!1),i=e.length>0;e.length,t.length,e.length<t.length;const a=e.length>=3?e.slice(0,2):e,l=e.length>=3?e.slice(2):[],u=l.length>0;return c.jsx(Mn,{children:c.jsx("div",{className:"space-y-2",children:i&&c.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.map((d,f)=>{const h="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs(Xt,{children:[c.jsx(Qt,{asChild:!0,children:c.jsxs(Fe,{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:[qw(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:h_(d)}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(d),children:c.jsx(vt,{className:"h-3 w-3"})})]})}),c.jsx(tn,{side:"top",className:"max-w-xs",children:sZe(d)})]},h)}),u&&c.jsxs(Xt,{open:s,onOpenChange:o,children:[c.jsx(Qt,{asChild:!0,children:c.jsxs(Fe,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>o(!0),children:[c.jsx(Vse,{className:"h-3 w-3"}),c.jsxs("span",{className:"text-xs",children:[l.length," more"]}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(l),children:c.jsx(vt,{className:"h-3 w-3"})})]})}),c.jsx(tn,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),c.jsx("div",{className:"space-y-2",children:l.map(d=>{const f="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:qw(d.type,{size:"h-3 w-3"})}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate text-sm font-medium",children:h_(d)}),c.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),c.jsx(se,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(d),l.length===1&&o(!1)},children:c.jsx(vt,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function PJ(e){return e.type==="dataset"&&e.label||e.name}function iZe(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 aZe({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:c.jsxs("div",{className:"mb-4 space-y-2",children:[c.jsxs(ce,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),c.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:c.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>c.jsxs(Fe,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[c.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),PJ(n),c.jsx("button",{onClick:s=>{s.stopPropagation(),t(n)},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-0 transition-opacity hover:bg-red-100 group-hover:opacity-100",children:c.jsx(vt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function lZe(e){const{tokenProps:t}=Ge(),n=X(l=>l.authToken)||e;Me(l=>l.selectedConnectionId),Me(l=>{var u,d;return(d=(u=l==null?void 0:l.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=pn({queryKey:["semantic-domains"],queryFn:()=>qn(`${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 cZe(e,t){const{tokenProps:n}=Ge(),r=X(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:l}=pn({queryKey:["datasets",e],queryFn:()=>qn(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:o,error:l,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:l,refetchDatasets:s}}function uZe(e){var g,b;const{tokenProps:t}=Ge(),n=X(x=>x.authToken)||e,{connections:r}=Pa(e),s=Me(x=>{var y,v;return(v=(y=x==null?void 0:x.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(x=>x.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(x){return s&&x?!(x==="API"||x==="S3"):!1}const{data:d,isPending:f,error:h,refetch:p}=pn({queryKey:["databases",s],queryFn:()=>qn(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),m=(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:m||[],refetch:p,label:l}}function dZe(e){var g;const{tokenProps:t}=Ge(),n=X(b=>b.authToken)||e,{connections:r}=Pa(e),s=Me(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=Me(b=>{var x,y,v;return(v=(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(b=>b.id===s),a=i==null?void 0:i.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){return!(!s||(i==null?void 0:i.type)==="API"||(i==null?void 0:i.type)==="S3"||!o||!(a!=null&&a.path.includes("schema")))}const{data:d,isPending:f,error:h,refetch:p}=pn({queryKey:["schemas",s,o],queryFn:()=>qn(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),m=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:m||[],refetch:p,label:l}}function OJ(e){const{tokenProps:t}=Ge(),n=X(h=>h.authToken)||e,{connections:r}=Pa(e),s=Me(h=>{var p,m;return(m=(p=h==null?void 0:h.card)==null?void 0:p.dataSource)==null?void 0:m.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:l,error:u,refetch:d}=pn({queryKey:["dataModels",s],queryFn:()=>qn(`${t.apiServiceUrl}/v1/datamodels`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:i()}),f=a==null?void 0:a.datamodels.map(h=>({id:h.id,name:h.name,label:h.label,description:h.description,connectionId:s,dialect:h.dialect,connectionType:o==null?void 0:o.type,type:"model",database:h.database,schema:h.schema}));return{isPending:l,error:u,dataModels:f||[],refetch:d}}function fZe(){var j,S,N;const e=Me(E=>E.card.dataSource);Me(E=>E.actions.updateDirectSource);const t=Me(E=>E.actions.updateDataSource),[n,r]=C.useState(""),{selectedConnection:s,error:o}=Pa(),{databases:i,isPending:a,error:l,label:u}=uZe(),{schemas:d,isPending:f,error:h,label:p}=dZe(),{error:m}=OJ(),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=p==null?void 0:p.toLowerCase(),v=E=>{e&&t({...e,dbSelection:{database:E,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},w=E=>{var k;if(!((k=e==null?void 0:e.dbSelection)!=null&&k.database))return;const _=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{..._,schema:E},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return c.jsxs(c.Fragment,{children:[(o||l||h||m)&&c.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[c.jsx("div",{className:"flex items-center",children:c.jsxs("div",{className:"text-sm text-red-800",children:[c.jsx("strong",{children:"Error loading data:"}),c.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&c.jsxs("li",{children:["Connections: ",o]}),l&&c.jsxs("li",{children:[u,": ",l.message]}),h&&c.jsxs("li",{children:[p,": ",h.message]}),m&&c.jsxs("li",{children:["Data Models: ",m.message]})]})]})}),c.jsx(se,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),c.jsxs("div",{className:"space-y-4",children:[b&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:u}),c.jsxs(nt,{value:((j=e==null?void 0:e.dbSelection)==null?void 0:j.database)||"",onValueChange:v,disabled:a,children:[c.jsx(et,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[a&&c.jsx(an,{className:"h-4 w-4 animate-spin"}),c.jsx(ot,{placeholder:l?`Error loading ${x}`:a?`Loading ${x}...`:`Select ${x}...`})]})}),c.jsx(tt,{children:i.map(E=>c.jsx(be,{className:"hover:bg-muted",value:E.id,children:E.name},E.id))})]})]}),((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)&&g&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:p}),c.jsxs(nt,{value:((N=e==null?void 0:e.dbSelection)==null?void 0:N.schema)||"",onValueChange:w,disabled:f,children:[c.jsx(et,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[f&&c.jsx(an,{className:"h-4 w-4 animate-spin"}),c.jsx(ot,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),c.jsx(tt,{children:d.map(E=>c.jsx(be,{className:"hover:bg-muted",value:E.id,children:E.name},E.id))})]})]})]})]})}function hZe(){const e=Me(l=>l.card.dataSource),t=Me(l=>l.actions.updateDataSource),[n,r]=C.useState(!1),s=l=>{if(!l||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(l).map(f=>({id:`file-${Date.now()}-${Math.random()}`,name:f.name,type:"upload",connectionId:"default",connectionType:"none",label:f.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:f.name,file:f})),d=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...d,...u]})},o=l=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==l);t({...e,selectedEntities:u})},i=l=>{if(l===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(l)/Math.log(u));return Number.parseFloat((l/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Upload Files"}),c.jsxs("div",{className:`rounded-lg border-2 border-dashed p-6 text-center transition-colors ${n?"border-blue-400 bg-blue-50":"border-gray-300 hover:border-gray-400"}`,onDragOver:l=>{l.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:l=>{l.preventDefault(),r(!1),s(l.dataTransfer.files)},children:[c.jsx(pM,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),c.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),c.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:l=>s(l.target.files),accept:".csv,.json,.xlsx,.xls"}),c.jsx(se,{variant:"outline",size:"sm",onClick:()=>{var l;return(l=document.getElementById("file-upload"))==null?void 0:l.click()},children:"Select Files"}),c.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ce,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(l=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(Ai,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:l.originalName}),c.jsx("p",{className:"text-xs text-gray-500",children:l.file?i(l.file.size):""})]})]}),c.jsx(se,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(l.id),children:c.jsx(vt,{className:"h-3 w-3"})})]},l.id))})]})]})}function pZe(){const e=Me(f=>f.card.dataSource),t=Me(f=>f.actions.updateDataSource),[n,r]=C.useState(""),[s,o]=C.useState(""),[i,a]=C.useState("api"),l=()=>{if(!n.trim()||!s.trim()||!e)return;const f={id:`url-${Date.now()}-${Math.random()}`,name:n.trim(),type:"url",connectionId:"default",connectionType:"none",label:n.trim(),description:`URL source of type ${i}`,url:s.trim(),sourceType:i,originalName:n.trim()},h=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...h,f]}),r(""),o(""),a("api")},u=f=>{if(!e)return;const h=(e.selectedEntities||[]).filter(p=>p.id!==f);t({...e,selectedEntities:h})},d=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),c.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"Source Name"}),c.jsx(Nn,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"URL"}),c.jsx(Nn,{placeholder:"https://api.example.com/data",value:s,onChange:f=>o(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"Type"}),c.jsxs("select",{value:i,onChange:f=>a(f.target.value),className:"h-8 w-full rounded-md border border-gray-300 px-2 text-sm",children:[c.jsx("option",{value:"api",children:"API Endpoint"}),c.jsx("option",{value:"csv",children:"CSV File"}),c.jsx("option",{value:"json",children:"JSON File"})]})]}),c.jsxs(se,{onClick:l,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[c.jsx(wr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ce,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(u1,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),c.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),c.jsx(se,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:c.jsx(vt,{className:"h-3 w-3"})})]},f.id))})]})]})}function mZe(e,t){var y,v;const{tokenProps:n}=Ge(),r=X(w=>w.authToken)||t,{connections:s}=Pa(t),o=Me(w=>{var j,S;return(S=(j=w==null?void 0:w.card)==null?void 0:j.dataSource)==null?void 0:S.connectionId}),i=Me(w=>{var j,S,N;return(N=(S=(j=w==null?void 0:w.card)==null?void 0:j.dataSource)==null?void 0:S.dbSelection)==null?void 0:N.database}),a=Me(w=>{var j,S,N;return(N=(S=(j=w==null?void 0:w.card)==null?void 0:j.dataSource)==null?void 0:S.dbSelection)==null?void 0:N.schema}),l=s==null?void 0:s.find(w=>w.id===o),u=l==null?void 0:l.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){return o?(l==null?void 0:l.type)==="API"||(l==null?void 0:l.type)==="S3"?!0:!(!i||u!=null&&u.path.includes("schema")&&!a):!1}const{data:h,isPending:p,isLoading:m,error:g,refetch:b}=pn({queryKey:[e,o,i,a],queryFn:()=>qn(`${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(w=>{var j;return{connectionId:l==null?void 0:l.id,connectionType:l==null?void 0:l.type,dialect:l==null?void 0:l.dialect,type:e,dbObjectType:(j=w==null?void 0:w.table_type)==null?void 0:j.toLowerCase(),id:w[`${e}_name`],database:i,schema:a,name:w[`${e}_name`]}});return{isPending:p,isLoading:m,error:g,entities:x||[],refetch:b,label:d}}function Yw({title:e,message:t}){return c.jsx("div",{className:"rounded-xl border border-destructive/40 bg-destructive/10 p-4 text-destructive shadow-sm",children:c.jsxs("div",{className:"flex items-start gap-4",children:[c.jsx(Ac,{className:"h-6 w-6 flex-shrink-0"}),c.jsxs("div",{className:"flex-1",children:[c.jsx("h4",{className:"text-base font-semibold",children:e}),t&&c.jsx("p",{className:"mt-1 text-sm text-destructive/90",children:t})]})]})})}function gZe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=Pa(),[i,a]=C.useState(""),[l,u]=C.useState(""),[d,f]=C.useState("tables"),{updateDataSource:h,setSelectedConnectionId:p}=Qn(),{entities:m,isLoading:g,error:b}=mZe("table"),{dataModels:x,isPending:y,error:v}=OJ(),w=k=>{const T=s.find(P=>P.id===k);if(!T)return;const M=T.type==="upload"?"upload":T.type==="url"?"url":"database";h({...e,connectionId:k,connectionType:T.type,mode:M,dbSelection:{database:"",schema:"",entityType:"table"}}),p(k)},j=k=>{var A,R;const T=n||[],M=T.some(L=>L.name===k.name&&L.type===k.type);let P;if(M)P=T.filter(L=>!(L.name===k.name&&L.type===k.type));else{const L={connectionId:e.connectionId,connectionType:e.connectionType,type:k.type,dbObjectType:k.dbObjectType,database:((A=e.dbSelection)==null?void 0:A.database)||"",schema:((R=e.dbSelection)==null?void 0:R.schema)||"",name:k.name,dialect:k.dialect};P=[...T,L]}t==null||t(P)},S=k=>{const T=n||[],M=T.some(A=>A.type==="model"&&A.name===k.name);let P;M?P=T.filter(A=>!(A.type==="model"&&A.name===k.name)):P=[...T,k],t==null||t(P)},N=m.filter(k=>k.name.toLowerCase().includes(i.toLowerCase())),E=x.filter(k=>k.name.toLowerCase().includes(l.toLowerCase())),_=C.useCallback(()=>{if(!t)return;const k=n||[];let T=[...k];if(d==="tables"){const P=N.filter(A=>!k.some(R=>R.name===A.name&&R.type==="table")).map(A=>{var R,L;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:A.dbObjectType,database:((R=e.dbSelection)==null?void 0:R.database)||"",schema:((L=e.dbSelection)==null?void 0:L.schema)||"",name:A.name,dialect:A.dialect}});T=[...k,...P]}else if(d==="datamodels"){const M=E.filter(P=>!k.some(A=>A.name===P.name&&A.type==="model"));T=[...k,...M]}t(T)},[d,N,E,n,e,t]);return C.useEffect(()=>{r&&r(_)},[r,_]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"font-medium= text-sm",children:"Connection"}),c.jsxs(nt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:w,disabled:o,children:[c.jsx(et,{className:"w-full",children:c.jsx(ot,{placeholder:o?"Loading connections...":"Select connection..."})}),c.jsx(tt,{children:s.map(k=>c.jsx(be,{className:"hover:bg-muted",value:k.id,children:c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(vl,{className:"h-4 w-4 flex-shrink-0"}),c.jsx("span",{className:"truncate",children:k.name}),c.jsx(Fe,{variant:"secondary",className:"flex-shrink-0 text-xs",children:k.type})]})},k.id))})]})]}),(e==null?void 0:e.connectionId)&&c.jsxs(c.Fragment,{children:[e.connectionType==="upload"&&c.jsx(hZe,{}),e.connectionType==="url"&&c.jsx(pZe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(fZe,{}),c.jsx("div",{className:"space-y-4",children:c.jsx("div",{className:"space-y-2",children:c.jsxs(Bs,{defaultValue:"tables",value:d,onValueChange:k=>f(k),className:"w-full",children:[c.jsxs(ws,{className:"grid w-full grid-cols-2",children:[c.jsxs(Kt,{value:"tables",children:["Tables & Views (",N.length,")"]}),c.jsxs(Kt,{value:"datamodels",children:["Data Models (",E.length,")"]})]}),c.jsxs(rr,{value:"tables",className:"space-y-2",children:[c.jsx(xn,{placeholder:"Search tables and views...",value:i,onChange:k=>a(k.target.value),className:"h-8 text-sm",disabled:g}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):b?c.jsx(Yw,{title:"Error loading tables",message:b.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):N.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):N.map(k=>{const T=n.some(M=>M.name===k.name&&M.type==="table");return c.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>j(k),children:[c.jsx(Jt,{id:`table-${k.name}`,checked:T,onCheckedChange:()=>j(k),onClick:M=>M.stopPropagation(),disabled:g}),c.jsxs(ce,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[k.name,k.dbObjectType==="view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),k.dbObjectType==="materialized view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},k.name)})})]}),c.jsxs(rr,{value:"datamodels",className:"space-y-2",children:[c.jsx(xn,{placeholder:"Search data models...",value:l,onChange:k=>u(k.target.value),className:"h-8 text-sm",disabled:y}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?c.jsx(Yw,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):E.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):E.map(k=>{const T=n.some(M=>M.name===k.name&&M.type==="model");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(k),children:[c.jsx(Jt,{id:`dataModel-${k.name}`,checked:T,onCheckedChange:()=>S(k),onClick:M=>M.stopPropagation(),disabled:y}),c.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[c.jsx(ce,{className:"cursor-pointer",children:k.name}),c.jsx("span",{className:"text-xs text-muted-foreground",children:k.description})]})]},k.name)})})]})]})})})]})]})]})}function bZe({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:s=[],isRestricted:o=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var j;const[l,u]=C.useState(""),d=C.useCallback(S=>{const N={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:S};t({...N})},[e,t]);C.useEffect(()=>{i&&!(e!=null&&e.semanticDomainId)&&d(i)},[i,e==null?void 0:e.semanticDomainId,d]);const{semanticDomains:f,isPending:h,error:p}=lZe(),m=o?f.filter(S=>s.includes(S.id)):f,{datasets:g,isPending:b,error:x}=cZe(e==null?void 0:e.semanticDomainId),y=S=>{const N=r||[],E=N.some(k=>k.id===S.id&&k.type==="dataset");let _;if(E)_=N.filter(k=>!(k.id===S.id&&k.type==="dataset"));else{const k={id:S.id,datasetType:S.type,name:S.name||S.table,label:S.label,domainId:S.domainId,description:S.description,database:S.database,schema:S.schema,type:"dataset",connectionId:S.connectionId,connectionType:S.connectionType,dialect:S.dialect,datamodelId:S.datamodelId,sql:S.sql};_=[...N,k]}n==null||n(_)},v=g.filter(S=>S.name.toLowerCase().includes(l.toLowerCase())),w=C.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const S=r||[],E=v.filter(k=>!S.some(T=>T.id===k.id&&T.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})),_=[...S,...E];n(_)},[v,r,e==null?void 0:e.semanticDomainId,n]);return C.useEffect(()=>{a&&a(w)},[a,w]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Semantic Domain"}),c.jsxs(nt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:d,disabled:h||o&&!!i,children:[c.jsx(et,{className:"w-full",children:c.jsx(ot,{placeholder:h?"Loading semantic domains...":o&&i?"Loading domain...":"Select semantic domain...",children:((j=m.find(S=>S.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:j.label)||"Select semantic domain"})}),c.jsx(tt,{children:m.map(S=>c.jsx(be,{className:"hover:bg-muted",value:S.id,children:c.jsxs("div",{className:"flex flex-col items-start",children:[c.jsx("span",{className:"font-medium",children:S.label}),c.jsx("span",{className:"text-xs",children:S.description})]})},S.id))})]}),p&&c.jsx(Yw,{title:"Error loading semantic models",message:p.message})]}),(e==null?void 0:e.semanticDomainId)&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(xn,{placeholder:"Search datasets...",value:l,onChange:S=>u(S.target.value),className:"h-8 text-sm",disabled:b}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:b?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):x?c.jsx(Yw,{title:"Error loading datasets",message:x.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):v.length===0?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:l?"No datasets match your search":"No datasets available"}):v.map(S=>{const N=r.some(E=>E.id===S.id&&E.type==="dataset");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>y(S),children:[c.jsx(Jt,{id:`dataset-${S.id}`,checked:N,onCheckedChange:()=>y(S),onClick:E=>E.stopPropagation(),disabled:b}),c.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[c.jsx(ce,{className:"cursor-pointer font-medium",children:S.label||S.name}),c.jsx("span",{className:"text-xs text-gray-500",children:S.description})]})]},S.label||S.name)})})]})]})]})}function zI({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s}){const{tokenProps:o}=Ge(),{allowedSemanticDomains:i}=o,[a,l]=C.useState([]),{updateDataSource:u}=Qn(),d=X(T=>T.isVisualEditing),f=X(T=>T.dashboard.aiContext),{setAiContext:h}=Ft(),p=C.useRef(null),[m,g]=C.useState(!1),b=i&&i.length>0,x=!b,y=b&&i.length===1?i[0]:void 0,v=C.useCallback(T=>{const M=T;u({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:M,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...M!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,u]),w=C.useCallback(T=>{u({...n,...T})},[n,u]);C.useEffect(()=>{b&&n.mode!=="semanticDomain"&&v("semanticDomain")},[b,n.mode,v]),C.useEffect(()=>{y&&!n.semanticDomainId&&w({semanticDomainId:y})},[y,n.semanticDomainId,w]),C.useEffect(()=>{e?l(s||[]):(p.current=null,g(!1))},[e,n==null?void 0:n.selectedEntities,r,u,s,n]);const j=T=>{const M=a.filter(P=>!(P.name===T.name&&P.type===T.type));l(M)},S=()=>{l([])},N=C.useCallback(T=>{l(T)},[]),E=C.useCallback(()=>{p.current&&p.current()},[]),_=C.useCallback(T=>{p.current=T,g(!0)},[]);function k(){var T,M;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const P=(T=a==null?void 0:a[0])==null?void 0:T.connectionId,A=(M=a==null?void 0:a[0])==null?void 0:M.connectionType;u({...n,connectionId:P,connectionType:A,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return c.jsx(rs,{open:e,onOpenChange:t,children:c.jsx(Vr,{className:"flex max-w-2xl flex-col",children:c.jsxs("div",{children:[c.jsxs(Hr,{className:"flex-shrink-0",children:[c.jsx(Ur,{children:r==="aiContext"?"Data Context":"Select Data Source"}),c.jsx(vs,{children:r==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),c.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:c.jsxs("div",{className:"space-y-4",children:[x&&c.jsx("div",{className:"space-y-2",children:c.jsx(Bs,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:v,className:"w-full",children:c.jsxs(ws,{className:"grid w-full grid-cols-2",children:[c.jsx(Kt,{value:"database",children:"Direct Source"}),c.jsx(Kt,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&c.jsx(bZe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:N,allowedDomainIds:i||[],isRestricted:b,autoSelectedDomainId:y,onRegisterSelectAll:_}),(n==null?void 0:n.mode)==="database"&&x&&c.jsx(gZe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:N,onRegisterSelectAll:_})]})}),c.jsx(aZe,{selectedEntities:a,onDeselectEntity:j}),c.jsx(ys,{className:"flex-shrink-0",children:c.jsx("div",{className:"flex w-full justify-between",children:c.jsxs("div",{className:"flex grow justify-end gap-2",children:[c.jsx(se,{variant:"outline",onClick:E,disabled:!m,children:"Select All"}),c.jsx(se,{variant:"outline",onClick:S,disabled:a.length===0,children:"Clear All"}),c.jsxs(se,{variant:"outline",onClick:()=>t(!1),children:[c.jsx(vt,{className:"mr-2 h-4 w-4"}),"Close"]}),c.jsxs(se,{onClick:k,children:[c.jsx(Mr,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function xZe({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=C.useRef(null),o=async a=>{const l=Array.from(a.target.files||[]);if(l.length===0)return;const u=Ja-n;if(l.length>u){Pe.error(`You can only attach ${Ja} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=vQ(l);if(f.forEach(({file:h,error:p})=>{Pe.error(`${h.name}: ${p}`)}),d.length>0)try{const h=await Promise.all(d.map(p=>MI(p)));e(h)}catch(h){console.error("Failed to process files:",h),Pe.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:s,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:o,className:"hidden",disabled:t||n>=Ja}),c.jsx(se,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=Ja,title:n>=Ja?`Maximum ${Ja} files allowed`:"Attach files",children:c.jsx(oM,{className:"h-4 w-4 text-muted-foreground"})})]})}function yZe({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=C.useState(!1),a=C.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),l=C.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),p=f.clientX,m=f.clientY;(p<h.left||p>=h.right||m<h.top||m>=h.bottom)&&i(!1)},[]),u=C.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=C.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const p=Ja-r;if(h.length>p){Pe.error(`You can only attach ${Ja} files per message. You have ${p} slot(s) remaining.`);return}const{valid:m,errors:g}=vQ(h);if(g.forEach(({file:b,error:x})=>{Pe.error(`${b.name}: ${x}`)}),m.length>0)try{const b=await Promise.all(m.map(x=>MI(x)));t(b),Pe.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),Pe.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:K("relative",s),onDragEnter:a,onDragLeave:l,onDragOver:u,onDrop:d,children:[e,o&&!n&&c.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-lg border-2 border-dashed border-primary bg-primary/5 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-2",children:[c.jsx(pM,{className:"h-8 w-8 text-primary"}),c.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ja-r," slot(s) available"]})]})})]})}const BI=C.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:l},u)=>{const[d,f]=C.useState(!1),[h,p]=C.useState(!1),[m,g]=C.useState(!1),b=C.useRef(null),x=Lp();pCe(),hCe();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:w,setShowReasoning:j}=dS(),{queueMessage:S}=zp(),{addFileAttachment:N,removeFileAttachment:E,clearFileAttachments:_,getFileAttachments:k}=lD(),T=aD(l),M=Me(H=>H.card.dataSource),P=X(H=>H.dashboard.aiContext),A=X(H=>{var G;return(G=H.dashboard.aiContext)==null?void 0:G.selectedEntities});C.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const R=C.useCallback(()=>{const H=b.current;if(H){if(!e||e.length===0){H.style.height="10px";return}H.style.height="auto";const G=Math.min(Math.max(H.scrollHeight,10),200);H.style.height=`${G}px`}},[e]);C.useEffect(()=>{R()},[R]),C.useEffect(()=>{const H=setTimeout(()=>{R()},0);return()=>clearTimeout(H)},[R]);const L=()=>{const H=e.trim();!H&&T.length===0||(a!=="ready"?(S(l,H,T),t(""),_(l)):r({preventDefault:()=>{}}))},F=H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),L()),H.key==="@"&&(W(),f(!0))},U=C.useCallback(H=>{const G=HHe(H.nativeEvent);G.length>0&&(H.preventDefault(),G.forEach(async Z=>{const J=await MI(Z);N(l,J)}))},[N,l]),$=C.useCallback(H=>{H.forEach(G=>{N(l,G)})},[N,l]),I=C.useCallback(H=>{H.forEach(G=>{N(l,G)})},[N,l]),B=C.useCallback(H=>{E(l,H)},[E,l]),z=H=>{if(x.selectedEntities.some(Z=>Z.id&&Z.id===H.id||Z.name===H.name)){const Z=x.selectedEntities.filter(J=>!(J.id&&J.id===H.id||J.name===H.name));y({selectedEntities:Z})}else{const Z=[...x.selectedEntities,H];y({selectedEntities:Z})}},O=H=>{z(H)},q=H=>{var J;if(!x.selectedEntities.some(Q=>Q.id&&Q.id===H.id||Q.name===H.name)){const Q=[...x.selectedEntities,H];y({selectedEntities:Q})}const Z="label"in H?H.label:H.name;t(e+`@${Z} `),f(!1),(J=b.current)==null||J.focus()},V=H=>{const G=x.selectedEntities.filter(Q=>!(Q.id&&Q.id===H.id||Q.name===H.name));y({selectedEntities:G});const J=`@${"label"in H?H.label:H.name}`;e.includes(J)&&t(e.replace(J,"").trim())},Y=H=>{const G=new Set(H.map(Q=>Q.id||Q.name)),Z=x.selectedEntities.filter(Q=>!G.has(Q.id||Q.name));y({selectedEntities:Z});let J=e;H.forEach(Q=>{const ie=`@${"label"in Q?Q.label:Q.name}`;J=J.replace(ie,"").trim()}),t(J)},W=C.useCallback(()=>{x.selectedEntities.length===0&&y({selectedEntities:(P==null?void 0:P.selectedEntities)||[]})},[x.selectedEntities.length,P==null?void 0:P.selectedEntities,y]);return c.jsxs(yZe,{onFilesDropped:$,currentFileCount:T.length,disabled:s,className:"space-y-4",children:[c.jsx(oZe,{entities:x.selectedEntities,availableEntities:A||[],onRemoveEntity:V,onRemoveEntities:Y}),T.length>0&&c.jsx(UHe,{files:T,onRemove:B,showRemove:!s,className:"mb-2"}),c.jsxs("div",{className:"rounded-lg border border-border bg-background shadow-sm focus-within:ring-1 focus-within:ring-foreground/40",children:[c.jsx("textarea",{ref:b,value:e,onChange:n,onKeyDown:F,onPaste:U,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"}}),c.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[l==="dashboard"&&c.jsxs(Qr,{open:d,onOpenChange:H=>{H&&W(),f(H)},children:[c.jsx(Jr,{asChild:!0,children:c.jsx(se,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:c.jsx(Pse,{className:"h-4 w-4 text-muted-foreground"})})}),c.jsx(es,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:H=>H.preventDefault(),children:c.jsx(rZe,{isOpen:!0,onSelect:z,onDeselect:O,onClose:()=>{var H;f(!1),(H=b.current)==null||H.focus()},availableEntities:A||[],selectedEntities:x.selectedEntities,onTabComplete:q,onSelectAll:()=>{A&&y({selectedEntities:A})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),p(!0)}})})]}),c.jsx(xZe,{onFilesSelected:I,disabled:s,currentFileCount:T.length})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[s&&c.jsx(se,{className:"rounded-full",size:"sm",onClick:o,children:c.jsx(Qse,{className:"size-3.5 bg-background"})}),!s&&c.jsx(se,{disabled:!e.trim()&&T.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:L,title:a!=="ready"?"Message will be queued":void 0,children:c.jsx(wz,{className:"size-4"})})]})]})]}),c.jsx(zI,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:p,dataSource:M||uC,dialogMode:"aiContext"})]})});BI.displayName="ChatInputWithContext";function FJ({assistantType:e,className:t}){const n=MW(e),{removeFromQueue:r}=zp();return n.length===0?null:c.jsxs("div",{className:K("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(Ml,{className:"h-3 w-3"}),c.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),c.jsx("div",{className:"space-y-2",children:n.map(s=>c.jsx("div",{className:"group relative rounded-lg border border-dashed border-muted-foreground/30 bg-muted/30 px-3 py-2 text-sm animate-in fade-in-0 slide-in-from-bottom-1",children:c.jsxs("div",{className:"flex items-start justify-between gap-2",children:[c.jsx("div",{className:"flex-1 space-y-1",children:c.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),c.jsx(se,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:c.jsx(vt,{className:"h-3 w-3"})})]})},s.id))})]})}function $J({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=MW(e),{dequeueMessage:o}=zp();C.useEffect(()=>{if(t!=="ready"||n||!(s&&s.length>0))return;const a=o(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,s,o,r,e])}function LJ(e,t={}){const{threshold:n=50,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=C.useRef(null),[a,l]=C.useState(!0),[u,d]=C.useState(!0),[f,h]=C.useState(!1),[p,m]=C.useState(0),g=C.useRef(0),b=C.useRef(!1),x=C.useRef(0),y=C.useRef(a),v=C.useRef(void 0),w=C.useRef({key:null,count:0,length:0}),j=C.useCallback(()=>{const _=i.current;return _?_.scrollHeight-_.scrollTop-_.clientHeight:0},[]),S=C.useCallback((_={})=>{if(!i.current)return;const{force:T=!1,instant:M=!1}=_;if(!T&&!y.current||!a&&!T)return;const P=M||r==="auto"||r==="instant"?"auto":r;v.current&&cancelAnimationFrame(v.current),b.current=!0,v.current=requestAnimationFrame(()=>{if(!T&&!y.current){b.current=!1,v.current=void 0;return}const A=i.current;if(!A){b.current=!1,v.current=void 0;return}const R=A.scrollHeight;P==="smooth"&&"scrollTo"in A?A.scrollTo({top:R,behavior:P}):A.scrollTop=R,g.current=A.scrollTop,d(!0),l(!0),y.current=!0,h(!1),m(0),b.current=!1,v.current=void 0})},[r,a]),N=C.useCallback(()=>{const _=i.current;if(!_)return;const k=g.current,T=_.scrollTop,M=T-k;if(g.current=T,M<-1){v.current&&(cancelAnimationFrame(v.current),v.current=void 0),b.current=!1,y.current=!1,l(!1),d(!1);return}if(b.current)return;const P=j()<=n;d(P),l(P),y.current=P,P&&(h(!1),m(0))},[j,n]),E=C.useCallback(()=>{m(0),h(!1)},[]);return C.useEffect(()=>{y.current=a},[a]),C.useEffect(()=>{const _=i.current;if(!_||!e||e.length===0){h(!1),m(0),w.current={key:null,count:0,length:0},g.current=_?_.scrollTop:0,x.current=_?_.scrollHeight:0;return}g.current=_.scrollTop,x.current=_.scrollHeight;const k=w.current,T=e[e.length-1],M=(T==null?void 0:T.id)??(T==null?void 0:T.messageId)??(T==null?void 0:T.createdAt)??(T==null?void 0:T.timestamp)??e.length,P=Array.isArray(T==null?void 0:T.parts)?T.parts.reduce(($,I)=>I?typeof I=="string"?$+I.length:typeof I.text=="string"?$+I.text.length:typeof I.content=="string"?$+I.content.length:typeof I.value=="string"?$+I.value.length:$:$,0):typeof(T==null?void 0:T.content)=="string"?T.content.length:typeof(T==null?void 0:T.text)=="string"?T.text.length:0,A=e.length>k.count,R=M!==k.key,L=P>k.length,F=s&&(T==null?void 0:T.role)==="assistant"&&!A&&(R||L),U=o||F;if(w.current={key:M,count:e.length,length:P},a&&(A||R||L||U)){S({force:!1,instant:U});return}if(!a&&A){const $=e.length-k.count;$>0&&(h(!0),m(I=>I+$))}else!a&&L&&(h(!0),m($=>$>0?$:1))},[e,S,a,s,o]),C.useEffect(()=>{S({instant:!0})},[S]),C.useEffect(()=>{if(typeof ResizeObserver>"u")return;const _=i.current;if(!_)return;x.current=_.scrollHeight;const k=new ResizeObserver(()=>{const T=i.current;if(!T)return;const M=x.current,P=T.scrollHeight;x.current=P,!b.current&&y.current&&P>M&&S({force:!1,instant:!0})});return k.observe(_),()=>{k.disconnect()}},[S]),C.useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:u,hasNewMessages:f,newMessageCount:p,scrollToBottom:S,handleScroll:N,resetNewMessageCount:E}}function zJ(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=C.useState(r),a=C.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),l=e.length>o,u=o>=e.length,d=C.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=C.useCallback(()=>{i(r)},[r]);return C.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:l,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}function BJ(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:wQ(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const vZe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function wZe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=C.useState(!1),[a,l]=C.useState(E_),[u,d]=C.useState(!1),[f,h]=C.useState(!1),[p,m]=C.useState(!1),g=n??p,{isLocalDev:b,isConsoleMode:x}=dp(),y=C.useRef(null);X(He=>He.dashboard.aiScopeTables),X(He=>He.isDashboardEditing);const v=X(He=>He.selectedSheetId),{setDataSource:w}=Qn(),{addFrame:j,setSelectedFrameId:S,setIsDashboardEditing:N}=Ft(),E=Lp(),{setCurrentAIContext:_,updateSelectedEntities:k,setReasoningEffort:T,setShowReasoning:M}=dS(),{clearQueue:P}=zp(),{clearFileAttachments:A,getFileAttachments:R}=lD(),L=aD("dashboard"),F=X(He=>He.dashboard.aiContext),U=Me(He=>He.card.dataSource),{assistantProfile:$}=RJ(),I=X(He=>He.handleOpenAssistantProfile),{sendMessage:B,isLoading:z,messages:O,setMessages:q,status:V,stop:Y,errorMessage:W,clearError:H}=nZe(),G=C.useCallback(He=>{r==null||r(He),n===void 0&&m(He)},[n,r]),Z=C.useCallback(()=>{G(!g)},[g,G]);C.useEffect(()=>{if(!g)return;function He(en){en.key==="Escape"&&G(!1)}return window.addEventListener("keydown",He),()=>{window.removeEventListener("keydown",He)}},[g,G]);const[J,Q]=C.useState(""),re=He=>{Q(He.target.value)};function ie({sql:He,cardTitle:en,connectionId:Ke,cardType:Qe,python:Le,cardConfig:ve,dataSource:Be,customVisualPreferences:we}){if(!v)return;const We={id:yr(),title:en||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Qe==="horizontalBar"?"y":"x"}},type:Qe,sql:He,python:Le,dataSource:Be,config:ve,connectionId:Ke,customCardPreferences:we?{url:we.url,componentName:we.componentName,pluginChartType:we.pluginChartType,settings:we.settings,type:"component"}:void 0},at={id:yr(),cards:[We],activeCardId:We.id};N(!0),j(v,at,"end"),S(at.id)}const fe=He=>{He.preventDefault();const en=J.trim();if(!en&&L.length===0)return;const Ke=[];en&&Ke.push({type:"text",text:en}),L.forEach(Qe=>{Qe.data&&Ke.push({type:"file",mediaType:Qe.type,filename:Qe.name,url:`data:${Qe.type};base64,${Qe.data}`})}),B({role:"user",parts:Ke}),Q(""),A("dashboard"),ae({force:!0})};C.useEffect(()=>{var He;e&&((He=y.current)==null||He.focus())},[e]),$J({assistantType:"dashboard",status:V,isLoading:z,sendMessage:B});const{hasActiveTools:le}=BJ(O),{visibleMessages:Ce,hasMoreMessages:he,totalMessageCount:te,loadMoreMessages:oe,resetMessageWindow:me}=zJ(O,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:_e,isAtBottom:ue,hasNewMessages:De,newMessageCount:Ue,scrollToBottom:ae,handleScroll:ye,resetNewMessageCount:$e}=LJ(Ce,{threshold:50,behavior:"smooth",isStreaming:z});function pe(He){Ae();const en={role:"user",parts:[{type:"text",text:He.title+" "+He.subtitle}]};B(en)}function Ee(He){Ae(),B({role:"user",parts:[{type:"text",text:He}]})}function Ve(He){Ae(),B({role:"user",parts:[{type:"text",text:He}]}),ae({force:!0})}const qe=C.useCallback(async()=>{const He=JSON.stringify(O??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(He),Pe.success("Conversation copied")}catch(en){console.error("Failed to copy conversation",en),Pe.error("Unable to copy conversation")}},[O]);function Ae(){E.selectedEntities.length===0&&_({selectedEntities:(F==null?void 0:F.selectedEntities)||[]})}const yt=(J==null?void 0:J.length)===0&&(O==null?void 0:O.filter(He=>He.role==="user").length)===0;function je(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function mt(){return c.jsxs(cp,{children:[c.jsx(up,{asChild:!0,children:c.jsx(jc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(tp,{className:"size-3.5"})})}),c.jsxs(Qd,{align:"end",children:[c.jsx(Xf,{children:"Options"}),c.jsx(Ed,{}),c.jsx(rg,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(rg,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(rg,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const Mt=c.jsxs("div",{"data-role":"dashboard-assistant",className:K("flex h-full grow flex-col justify-between break-words px-6 py-4",g&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[c.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[je(),I&&c.jsx(se,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:I,children:($==null?void 0:$.name)||"Default Profile"}),c.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[x&&mt(),a&&c.jsx(se,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:qe,children:"Copy Conversation"}),c.jsx(jc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:Z,children:g?c.jsx(sM,{className:"size-4"}):c.jsx(h1,{className:"size-4"})}),c.jsx(jc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{q([]),P("dashboard"),H(),me()},children:c.jsx(p1,{className:"size-4"})}),c.jsx(jc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(vt,{className:"size-4"})})]})]}),c.jsxs(zl,{"data-role":"dashboard-assistant-scroll-area",ref:_e,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:ye,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[he&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(se,{variant:"outline",size:"sm",onClick:oe,className:"text-xs",children:["Load ",Math.min(5,te-Ce.length)," ","more messages (",te-Ce.length," ","hidden)"]})}),c.jsx(CQ,{showTools:a,showSystemMessage:u,messages:Ce,onAddToDashboard:ie,onQuickReply:Ve,disableQuickReplies:z}),!le&&c.jsx(SQ,{status:V,errorMessage:W})]}),c.jsx(ti,{orientation:"horizontal"})]}),e&&!ue&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(se,{onClick:()=>{ae({force:!0}),$e()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(fr,{className:"h-4 w-4"}),De&&Ue>0&&c.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:Ue>9?"9+":Ue})]})}),c.jsxs("div",{className:"space-y-3",children:[!$&&yt&&c.jsx(jQ,{onClick:pe,placeholders:vZe}),c.jsx("div",{children:yt&&$&&c.jsx(IJ,{seedQuestions:$.seedQuestions||[],handleSeedQuestionClick:Ee})}),c.jsx(FJ,{assistantType:"dashboard",className:"mb-3"}),c.jsx(BI,{ref:y,setInput:Q,stop:Y,input:J,handleInputChange:re,handleSubmit:He=>{Ae(),fe(He),ae({force:!0})},isLoading:z,status:V,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx(zI,{incomingSelectedEntities:(F==null?void 0:F.selectedEntities)||[],open:f,onOpenChange:h,dataSource:U||uC,dialogMode:"aiContext"})]});return g&&s?Ln.createPortal(c.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:c.jsx("div",{className:"flex h-full w-full",children:Mt})}),s):Mt}function SZe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Ft(),o=X(d=>d.dashboard.sheets),a=X(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),l=X(d=>d.isDashboardEditing),u=X(d=>d.isVisualEditing);C.useEffect(()=>{if(!l||u)return;async function d(p){const m=p.ctrlKey||p.metaKey;m&&p.key==="c"?(await f(),Pe.success("Card copied to clipboard"),p.preventDefault()):m&&p.key==="v"&&(await h(),p.preventDefault())}async function f(){try{const p=n();p&&await navigator.clipboard.writeText(JSON.stringify(p))}catch(p){console.error("Failed to copy text:",p)}}async function h(){if(!a)return null;try{const p=await navigator.clipboard.readText();try{const m=JSON.parse(p);if(m!=null&&m.id){const g=AR(m),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),Pe.success("Card pasted from clipboard")}}catch(m){console.error("Failed to parse clipboard contents: ",m)}return p}catch(p){return console.error("Failed to paste text:",p),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[r,n,s,a,l,u,t])}function CZe(e,t){switch(e.interactionMode){case"drillToDetail":jZe(e,t);break;case"drillThrough":NZe(e,t);break;case"drillToURL":kZe(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 jZe(e,t){var l;const{targetInsightId:n,contextMode:r,displayMode:s,filterGroups:o}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=o.flatMap(u=>u.filters);break;case"full":{const u=((l=t.getCurrentFilters)==null?void 0:l.call(t))||[],d=o.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}s==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function NZe(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:s,sourceCardId:o}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=s.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",l=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:l,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:l,filters:i,contextMode:r})}function kZe(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 EZe({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(rs,{open:e,onOpenChange:t,children:c.jsxs(Vr,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(Hr,{children:[c.jsx(Ur,{children:i||"Insight Detail"}),c.jsx(vs,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(HK,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(YK,{insightId:n,filters:r,contextMode:o}):c.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function _Ze(){const e=At(w=>w.interactionStates),t=At(w=>w.setInteractionState),n=At(w=>w.clearLastInteractionEvent),r=At(w=>w.replaceCardWithInsight),s=At(w=>w.setPendingDrillThrough),o=At(w=>w.pendingDrillThrough),i=At(w=>w.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Ft(),{selectDashboard:u}=qb(),d=X(w=>w.dashboard),f=X(w=>w.filterValues),{data:h,isLoading:p}=O9((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[m,g]=C.useState({open:!1,insightId:""}),b=GK(m.insightId,{enabled:m.open&&!!m.insightId}),x=C.useRef(new Set),y=C.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:w,filters:j,contextMode:S})=>{g({open:!0,insightId:w,filters:j,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:S})},replaceCardContent:({cardId:w,insightId:j,filters:S,contextMode:N})=>{r(w,j,S,N)},getCurrentFilters:()=>f||[],navigateWithDrill:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:w,contextMode:j,sourceDashboardId:S,sourceDashboardTitle:N,targetDashboardId:E})=>{const k={sourceCardId:pa,interactionMode:"clickFilter",filterGroups:[{filters:w}]},T={...Ho(),appliedClickFilters:[k],contextMode:j,sourceDashboardId:S,sourceDashboardTitle:N,targetDashboardId:E};t(pa,T)}}),[a,r,f,l,d,s,t]);C.useEffect(()=>{Object.entries(e).forEach(([w,j])=>{if(j!=null&&j.lastInteractionEvent){const S=j.lastInteractionEvent,N=`${w}-${S.interactionMode}-${S.sourceCardId}-${Date.now()}`;if(x.current.has(N))return;x.current.add(N);try{CZe(S,y)}catch(E){console.error("Error executing interaction event:",E)}finally{n(w),setTimeout(()=>{x.current.delete(N)},5e3)}}})},[e,n,y]),C.useEffect(()=>{if(!(!o||!h||p))try{u(h),l(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(w){console.error("[DrillThrough] Error during automatic navigation:",w),i()}},[o,h,p,u,l,i]);const v=()=>{g({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(EZe,{open:m.open,onOpenChange:v,insightId:m.insightId,filters:m.filters,filterDefinitions:m.filterDefinitions,contextMode:m.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&p&&c.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border bg-background p-6 shadow-lg",children:[c.jsx(an,{className:"h-8 w-8 animate-spin text-primary"}),c.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function MZe(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=TZe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function TZe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function DZe(e){return e?`Back to ${e}`:"Back"}function RZe(){var x,y,v,w,j;const e=At(S=>S.interactionStates[pa]),t=X(S=>S.actions.goBackFromDrill),n=X(S=>S.actions.clearDrillContext),{selectDashboard:r}=qb(),[s,o]=C.useState({x:16,y:16}),[i,a]=C.useState(!1),l=C.useRef({x:0,y:0});C.useEffect(()=>{if(!i)return;const S=E=>{o({x:E.clientX-l.current.x,y:E.clientY-l.current.y})},N=()=>{a(!1)};return document.addEventListener("mousemove",S),document.addEventListener("mouseup",N),()=>{document.removeEventListener("mousemove",S),document.removeEventListener("mouseup",N)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((w=(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:w.filters)||[],h=u?{id:u,title:d||"Previous Dashboard",description:"",isPrivate:!1,isPublic:!1,version:"",createdBy:null,createdByTenantUser:"",tenantId:"",projectId:"",createdAt:"",updatedAt:"",lastModified:"",lastModifiedBy:"",createdByUser:null,createdByTenantUserRel:{name:"",email:""},permissions:{canEdit:!0,canShare:!0,canDelete:!0},ownership:{status:"private",isOwner:!0,sharedCount:0,createdBy:{type:"user",userId:"",name:"",email:""}}}:null;if(!e||!((j=e.appliedClickFilters)!=null&&j.length))return null;const p=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(S){console.error("[DrillBack] Error during back navigation:",S)}},m=()=>{n()},g=S=>{S.target.closest("button")||(a(!0),l.current={x:S.clientX-s.x,y:S.clientY-s.y})};MZe(f);const b=DZe(d);return c.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:c.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:g,style:{cursor:i?"grabbing":"grab"},children:[c.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((S,N)=>{const E=S.field.label||S.field.name,_=String(S.value);return c.jsxs(Fe,{variant:"secondary",className:"pointer-events-none text-xs",children:[E," = ",_]},N)})})]}),c.jsx(se,{variant:"ghost",size:"sm",onClick:m,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(vt,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(se,{variant:"secondary",size:"sm",onClick:p,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(tz,{className:"mr-2 h-4 w-4"}),b]})})]})})}function VJ(){var he;const{showAssistant:e,tokenProps:t}=Ge(),{preferences:n,isConsoleMode:r}=dp(),s=((he=n==null?void 0:n.cardDisplay)==null?void 0:he.mode)==="print",o=C.useRef(null),i=C.useRef(null),[a,l]=C.useState(!1),{handleDragStart:u,isDraggingRef:d,getStyle:f,getPositionClasses:h}=FLe({initialPosition:"bottom-right"}),p=pd(te=>te.setFullscreen),m=pd(te=>te.setPanelOpen),g=pd(te=>te.setContainer),b=NW("dashboard"),x=kW(),y=EW("dashboard"),v=b.isOpen,w=x==="dashboard",j=X(te=>te.isVisualEditing),S=X(te=>te.themeStyle),N=X(te=>{var oe;return(oe=te.dashboard)==null?void 0:oe.sheets}),E=X(te=>te.showFilters),_=X(te=>te.isDashboardEditing),k=X(te=>te.selectedSheetId),T=X(te=>{var oe;return(oe=te.dashboard)==null?void 0:oe.id}),M=X(te=>te.isDashboardPanelOpen),P=X(te=>te.actions.setIsDashboardPanelOpen),{getDefaultSheetId:A,setDefaultSheetId:R,clearDefaultSheetId:L}=Z6(T),[F,U]=C.useState(null);E1(Ot.DASHBOARD);const{setSelectedSheetId:$,setSheetTitle:I,addSheet:B,setSheets:z}=Ft();SZe(i);const{setActiveAssistantType:O}=dS();C.useEffect(()=>{if(T){const te=A();U(te)}},[T,A]),C.useEffect(()=>{v?O("dashboard"):x==="dashboard"&&p(null)},[v,O,x,p]),C.useEffect(()=>{var te;v||(te=o.current)==null||te.resize(0)},[v]);function q(te){var oe,me;te?((oe=o.current)==null||oe.resize(40),m("dashboard",!0),O("dashboard")):(m("dashboard",!1),p(null),(me=o.current)==null||me.resize(0),O(null))}function V(){const te={id:yr(),title:"New Sheet"};B(te),$(te.id)}function Y(te,oe){if(!T)return;F===te?(L(),U(null),Pe.success("Default sheet cleared")):(R(te),U(te),Pe.success(`"${oe}" set as default sheet`))}function W(te){var oe;te<1?(m("dashboard",!1),p(null),O(null),(oe=o.current)==null||oe.resize(0)):(v||m("dashboard",!0),O("dashboard"))}function H(){return(S==null?void 0:S.canvasTheme)==="muted"||!(S!=null&&S.canvasTheme)?"hsl(var(--semaphor-muted))":(S==null?void 0:S.canvasTheme)==="clear"?"":S==null?void 0:S.canvasTheme}const G=(te,oe)=>{te.dataTransfer.setData("tabIndex",oe.toString())},Z=te=>{te.preventDefault()},J=(te,oe)=>{const me=te.dataTransfer.getData("tabIndex");if(me===oe.toString())return;const _e=Array.from(N||[]),[ue]=_e.splice(parseInt(me),1);_e.splice(oe,0,ue),z(_e)},Q=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail,re=e===!0&&!s&&!v&&!j&&!E;function ie(){var te,oe;if(N&&N.length>1||_)return c.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&&Q&&c.jsx(se,{style:{borderRadius:S==null?void 0:S.controlInputRadius},variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{P(!M)},className:"h-8 shrink-0 p-2",children:M?c.jsx(iz,{className:"h-4 w-4"}):c.jsx(az,{className:"h-4 w-4"})}),N==null?void 0:N.map((me,_e)=>{const ue=k===me.id,De=F===me.id;return c.jsxs(Kt,{draggable:!0,onDragStart:Ue=>G(Ue,_e),onDragOver:Z,onDrop:Ue=>J(Ue,_e),style:{borderRadius:S==null?void 0:S.controlInputRadius},onClick:()=>$(me.id),className:"flex shrink-0 items-center gap-1 border px-2 py-1",value:me.id,children:[c.jsx(gb,{enabled:_&&ue,text:me.title,onSave:Ue=>I(me.id,Ue),children:me.title},me.id),!_&&ue&&c.jsx("div",{title:De?"Clear default sheet":"Set as default sheet",children:c.jsx(cM,{className:K("ml-1 size-3 cursor-pointer transition-all",De?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:Ue=>{Ue.stopPropagation(),Y(me.id,me.title||"Sheet")}})}),_&&ue&&N.length>1&&c.jsx(vt,{className:"ml-1 size-3",onClick:()=>l(!0)})]},me.id)}),_&&c.jsx("div",{style:{borderRadius:(oe=(te=S==null?void 0:S.chart)==null?void 0:te.options)==null?void 0:oe.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:V,children:c.jsx(wr,{className:"size-3"})})]})}function fe(){return c.jsx("div",{ref:i,style:{},className:"grow",children:N==null?void 0:N.map(te=>c.jsx(rr,{style:{backgroundColor:H()},className:K("mt-0",{}),value:te.id,children:c.jsx(aLe,{sheet:te})},te.id))})}function le(){var te;return c.jsxs(Bs,{"data-role":"dashboard-tabs-container",className:K("relative flex h-full flex-col",S==null?void 0:S.dashboardTabsContainer),onValueChange:oe=>{$(oe)},value:k||((te=N==null?void 0:N[0])==null?void 0:te.id),children:[ie(),c.jsx(zl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:fe()}),c.jsx($Le,{open:a,setOpen:l})]})}const Ce=C.useCallback(te=>{g("dashboard",te)},[g]);return N?c.jsxs(c.Fragment,{children:[c.jsx(_Ze,{}),c.jsx(RZe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(sX,{className:K("flex-1 basis-0 overflow-y-auto transition-opacity",w&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(HE,{children:le()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx(OLe,{open:v,onTabClick:q,withHandle:!0,disabled:!v}),c.jsx(HE,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:W,defaultSize:v?40:0,ref:o,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(wZe,{open:v,setOpen:q,isFullscreen:w,onFullscreenChange:te=>p(te?"dashboard":null),fullscreenContainer:y})})})]})]}),c.jsx("div",{ref:Ce,className:K("absolute inset-0",!w&&"pointer-events-none")}),re&&c.jsx("div",{className:K("absolute z-50 transition-all duration-300 ease-in-out",h().horizontal,h().vertical),style:f(),children:c.jsx(se,{size:"sm",variant:"outline",className:"h-12 w-12 cursor-grab rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted active:cursor-grabbing",onClick:()=>{d.current||q(!0)},onMouseDown:u,onTouchStart:u,title:"Open Assistant (drag to move)",children:c.jsx(lM,{className:"h-5 w-5"})})})]})]}):null}function VI({children:e}){return c.jsx(Aa,{style:{height:"100%",width:"100%"},children:c.jsx(Kre,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(Mn,{delayDuration:0,children:e})})})}function HJ({children:e,preferences:t}){const{currentUser:n}=oo(),r=C.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return c.jsx(h9.Provider,{value:r,children:c.jsx(HR,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function IZe(e=2e3,t=500){const n=jse(),[r,s]=C.useState(!1),[o,i]=C.useState(!1),a=C.useRef(null);return C.useEffect(()=>{const l=setTimeout(()=>s(!0),e);return()=>clearTimeout(l)},[e]),C.useEffect(()=>{if(r){if(n>0){i(!1),a.current&&(clearTimeout(a.current),a.current=null);return}return a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i(!0)},t),()=>{a.current&&clearTimeout(a.current)}}},[r,n,t]),o}function HI({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=IZe(e,t);return C.useEffect(()=>(s&&(window.__SEMAPHOR_READY__={ready:!0,type:n,componentId:r||null,timestamp:Date.now()}),()=>{window.__SEMAPHOR_READY__={ready:!1,type:n,componentId:r||null,timestamp:Date.now()}}),[s,n,r]),c.jsx("div",{id:"idle-check","aria-hidden":"true",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s?"ready":""})}function UJ(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(Ba,{FallbackComponent:FS,children:c.jsxs(q_,{dashboardProps:e,children:[c.jsx(HI,{componentType:"dashboard",componentId:e.id}),c.jsx(VI,{children:c.jsx(HJ,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(cD,{...e,type:"dashboard",children:c.jsx(VJ,{})})})})})]})})}function UI(e){const{tokenProps:t,authToken:n}=Ge(),r=t==null?void 0:t.apiServiceUrl;return pn({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return qn(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 WJ(e,t,n){if(t==="source")return{isValid:!0};const r=Tr(e.dataType);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 qJ(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=(t==null?void 0:t.comparisonType)==="none";!o&&i||n(r,{groupByColumns:[],comparisonType:"none"})}const YJ=e=>{var P;const t=(P=e==null?void 0:e.dataSource)==null?void 0:P.semanticDomainId,{data:n}=UI(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=Qn(),h=Me(A=>A.card.type),p=e==null?void 0:e.id,m=C.useCallback(A=>{if(!(e!=null&&e.config))return[];switch(A){case"groupBy":return(e.config.groupByColumns||[]).map(R=>({id:R.id,name:R.name,dataType:R.dataType,label:R.label!==void 0?R.label:R.name,qualifiedEntityName:R.qualifiedEntityName,entityId:R.entityId,entityName:R.entityName,entityType:R.entityType,dateFormat:R.dateFormat,customFormat:R.customFormat,granularity:R.granularity}));case"metrics":return e.config.metricColumns||[];case"pivotBy":return(e.config.pivotByColumns||[]).map(R=>({id:R.id,name:R.name,dataType:R.dataType,label:R.label!==void 0?R.label:R.name,qualifiedEntityName:R.qualifiedEntityName,entityId:R.entityId,entityName:R.entityName,entityType:R.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map(R=>({id:R.id,name:R.name,dataType:R.dataType,label:R.label!==void 0?R.label:R.name,qualifiedEntityName:R.qualifiedEntityName,entityId:R.entityId,entityName:R.entityName,entityType:R.entityType,direction:R.direction}));case"source":return[];default:return[]}},[e]),g=C.useCallback((A,R)=>{if(p)switch(A){case"groupBy":{r(p,{groupByColumns:R});break}case"metrics":{r(p,{metricColumns:R});break}case"pivotBy":{r(p,{pivotByColumns:R});break}case"sortBy":{r(p,{sortByColumns:R});break}}},[p,r]),b=C.useCallback((A,R,L)=>{if(!p)return;const U=m(A)[R];if(U)switch(A){case"groupBy":s(p,U.id,{label:L});break;case"metrics":o(p,U.id,{label:L});break;case"pivotBy":i(p,U.id,{label:L});break;case"sortBy":a(p,U.id,{label:L});break}},[p,m,s,o,i,a]),x=C.useCallback((A,R)=>{if(!p)return;const F=m("metrics")[A];F&&o(p,F.id,{aggregate:R,label:MH(F.name,R)})},[p,m,o]),y=C.useCallback((A,R,L)=>{if(!p)return;const U=m("groupBy")[A];if(!U)return;const $={dateFormat:R};R==="custom"&&L?$.customFormat=L:$.customFormat=void 0,s(p,U.id,$)},[p,m,s]),v=C.useCallback((A,R)=>{if(!p)return;const F=m("groupBy")[A];F&&s(p,F.id,{granularity:R})},[p,m,s]),w=C.useCallback((A,R)=>{if(!p)return;const F=m("metrics")[A];F&&o(p,F.id,{aliasTemplate:R})},[p,m,o]),j=C.useCallback((A,R)=>{if(console.log("handleValueAliasesChange",A,R),!p)return;console.log("handleValueAliasesChange",A,R);const F=m("metrics")[A];F&&(console.log("handleValueAliasesChange",R),o(p,F.id,{valueAliases:R}))},[p,m,o]),S=C.useCallback(A=>{if(!p)return;if(m("metrics").length===0){Pe.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(p,{comparisonType:A})},[p,r,m]),N=C.useCallback(A=>{p&&r(p,{showTrendline:A})},[p,r]),E=C.useCallback(A=>{p&&r(p,{trendlineWindow:A})},[p,r]),_=C.useCallback(A=>{p&&r(p,{trendlineGranularity:A})},[p,r]),k=C.useCallback(A=>{p&&r(p,{targetValue:A})},[p,r]),T=C.useCallback(A=>{var B;if(!p)return;const R=[...m("groupBy"),...m("pivotBy"),...m("metrics"),...m("sortBy")],L=Wwe(A,R,{joinPlan:(B=e==null?void 0:e.config)==null?void 0:B.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!L.isValid){L.showError&&kH();return}const F=Gwe(A,R,h);if(!F){Pe.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const U=WJ(A,F,h);if(!U.isValid){Pe.error("Invalid Field Type",{description:U.reason,position:"top-center",duration:3e3});return}const $=m(F);if(EH(A,$))return;const I=TH(A,F,$);if(I){const z=[...$,I];g(F,z),F==="metrics"&&qJ(h,e==null?void 0:e.config,r,p,z)}},[p,e==null?void 0:e.config,m,g,t,n,h,r]),M=C.useCallback((A,R)=>{if(!p)return;const F=m(A)[R];if(F){if(A!=="sortBy"){const U=m("sortBy"),$=U.filter(I=>!(I.name===F.name&&I.qualifiedEntityName===F.qualifiedEntityName));$.length!==U.length&&r(p,{sortByColumns:$})}switch(A){case"groupBy":l(p,F.id);break;case"metrics":u(p,F.id);break;case"pivotBy":d(p,F.id);break;case"sortBy":f(p,F.id);break}}},[p,m,l,u,d,f,r]);return{getFieldsForContainer:m,setFieldsForContainer:g,updateLabel:b,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:v,handleAliasTemplateChange:w,handleValueAliasesChange:j,removeField:M,handleFieldClick:T,handleKpiComparisonTypeChange:S,handleKpiShowTrendlineChange:N,handleKpiTrendlineWindowChange:E,handleKpiTrendlineGranularityChange:_,handleKpiTargetValueChange:k,cardType:h}};function oy(e,t){var Ee,Ve,qe,Ae,yt;const{tokenProps:n}=Ge(),r=zs(),s=Ge().authToken||e,o=Me(je=>je.selectedConnectionId),i=Me(je=>je.card),{queryKey:a}=ffe(i),l=Me(je=>je.selectedDatamodelId),u=Me(je=>je.isDevMode),d=Me(je=>je.selectedDatabaseName),f=Me(je=>je.selectedSchemaName),h=Me(je=>je.selectedTableName),p=Me(je=>je.actions.setSelectedConnectionId),m=Me(je=>je.actions.setSelectedDatamodelId),g=Me(je=>je.actions.setSelectedDatabaseName),b=Me(je=>je.actions.setSelectedSchemaName),x=Me(je=>je.actions.setSelectedTableName);Me(je=>je.actions.setCardSql);const{setQueryConfig:y}=Qn();function v(je){var Mt;return o&&je==="API"?!1:o&&je==="S3"?!0:!(!o||!d||d==="NA"||((Mt=_==null?void 0:_.capabilities)==null?void 0:Mt.path.includes("schema"))&&!f)}function w(je){return o&&je?!(je==="API"||je==="S3"):!1}const{refetchConnections:j,connectionsData:S,isConnectionsLoading:N,isConnectionsError:E,selectedConnection:_}=Pa(e),{refetch:k,data:T,isLoading:M,isError:P}=pn({queryKey:["models",o],queryFn:()=>qn(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),A=_==null?void 0:_.type,R=(_==null?void 0:_.type)==="API"||(_==null?void 0:_.type)==="S3",{data:L,isLoading:F,isFetching:U,isError:$,refetch:I}=pn({queryKey:["databases",o],queryFn:()=>qn(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:w(A)}),{data:B,isLoading:z,isFetching:O,isError:q,refetch:V}=pn({queryKey:["schemas",o,d],queryFn:()=>qn(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&!R&&d!=="NA"}),{data:Y,isLoading:W,isFetching:H,isError:G,refetch:Z}=pn({queryKey:["tables",o,d,f],queryFn:()=>qn(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(A)}),{columns:J,isColumnsLoading:Q,isColumnsFetching:re,isColumnsError:ie,refetchColumns:fe}=DH(e);C.useEffect(()=>{(A==="S3"||A==="API")&&(g(""),b(""),m(""),A==="API"&&x("api"))},[A,x,g,b,m]);const le=(_==null?void 0:_.type)==="API"?(Ee=_==null?void 0:_.type)==null?void 0:Ee.toLowerCase():h||"",Ce=R?"":f||"";function he(je){x(je),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function te(je){b(je),x("")}function oe(je){g(je==="none"?"":je),b(""),x(""),je!=="none"&&je!==""&&m("")}function me(je){p(je)}function _e(je){m(je==="none"?"":je),je!=="none"&&je!==""&&g("")}L&&((Ve=L==null?void 0:L.databases)==null?void 0:Ve.length)>0,B&&((qe=B==null?void 0:B.schemas)==null?void 0:qe.length)>0;const ue=S==null?void 0:S.connections.map(je=>({id:je.id,name:je.name,type:je.type})),De=(Ae=T==null?void 0:T.datamodels)==null?void 0:Ae.map(je=>({id:je.id,name:je.name})),Ue=L==null?void 0:L.databases.map(je=>({id:je.database_name,name:je.database_name})),ae=B==null?void 0:B.schemas.map(je=>({id:je.schema_name,name:je.schema_name})),ye=Y==null?void 0:Y.tables.map(je=>({id:je.table_name,name:je.table_name})),$e=(yt=T==null?void 0:T.datamodels.find(je=>je.id===l))==null?void 0:yt.name,pe=mv({schemaName:Ce,tableName:le,modelName:$e,connectionType:A,databaseName:d||""});return{connectionItems:ue,selectedConnectionId:o,selectedConnection:_,isConnectionsLoading:N,isConnectionsError:E,modelItems:De,selectedDatamodelId:l,selectedDatamodelName:$e,isModelsLoading:M,isModelsError:P,selectedDatabaseName:d,databaseItems:Ue,isDatabasesLoadingOrFetching:F||U,isDatabaseError:$,schemaItems:ae,selectedSchemaName:f,isSchemaLoadingOrFetching:z||O,isSchemaError:q,tableItems:ye,selectedTableName:h,isTableLoadingOrFetching:W||H,isTableError:G,columns:J,isColumnsLoadingOrFetching:Q||re,isColumnsError:ie,isNonDbConnection:R,connectionType:A,tableName:le,formattedTableName:pe,schemaName:Ce,refetchConnections:j,refetchModels:k,refetchDatabases:I,refetchSchemas:V,refetchTables:Z,refetchColumns:fe,handleConnectionChange:me,handleDatamodelChange:_e,handleDatabaseChange:oe,handleSchemaChange:te,handleTableChange:he}}function P0(e){return`${e}-${yr()}`}function kL(e,t){const n=Jo(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 AZe(e,t){const n=Jo(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 WI(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 GJ(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function KJ(){const e=Me(S=>S.sqlGen),t=Me(S=>S.isDevMode),n=Me(S=>S.card.dataSource),r=Me(S=>{var N,E;return(E=(N=S.card)==null?void 0:N.queryConfig)==null?void 0:E.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=WI(n),a=GJ(n),l=Me(S=>S.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:p,setIsShowingVisual:m}=Qn(),{connectionType:g,modelItems:b,selectedDatamodelName:x}=oy(),y=S=>({column_name:S.name,data_type:S.dataType,label:S.label,description:S.description});return{handleDevModeFieldClick:S=>{var E;if(!t)return;const N=y(S);if(t&&a&&s){const _=I_(N,e);p(_);const k=(E=b==null?void 0:b.find(M=>M.id===l))==null?void 0:E.name,T=R_(_,vi(o||""),vi(s),k||"",g,i||"");T&&(f(T),h(!0))}else if(!t){if(Hb(N.data_type))if(r&&r.length>0){const _={...N,role:"groupby",id:P0(N.column_name),name:N.column_name,type:N.data_type};d(_)}else{const _={...N,role:"metric",id:P0(N.column_name),name:N.column_name,label:kL(N.column_name,"COUNT"),type:N.data_type,aggregate:"COUNT"};u(_)}if(Ti(N.data_type)){const _={...N,role:"groupby",id:P0(N.column_name),name:N.column_name,type:N.data_type,label:AZe(N.column_name,"month"),granularity:"month"};d(_)}if(Mi(N.data_type)){const _={...N,role:"metric",id:P0(N.column_name),name:N.column_name,label:kL(N.column_name,"SUM"),type:N.data_type,aggregate:"SUM"};u(_)}}},handleShowSample:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const S=mv({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});m(!1);const N=g==="MSSQL"?`SELECT top 10 * FROM ${S}`:`SELECT * FROM ${S} LIMIT 10`;f(N),h(!0)},handleShowCount:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const S=mv({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});f(`SELECT COUNT(*) as count FROM ${S}`),h(!0)},isNumberField:S=>Mi(S.dataType)}}function PZe({columnName:e,database:t,schemaName:n,tableName:r,connectionType:s,datamodelId:o,modelName:i,field:a}){const l=vi(e),u=vi(t||""),d=vi(n||""),f=vi(r);let h=n1({schemaName:d,tableName:f,connectionType:s,databaseName:u}),p=`${h}.${l}`;return o&&o!=="none"&&i&&(p=`${Ag}.${i}.${l}`,h=`${Ag}.${i}`),a!=null&&a.qualifiedFieldName&&(p=a.qualifiedFieldName,h=a.qualifiedFieldName.split(".").slice(0,-1).join(".")),{qualifiedColumnName:p,qualifiedTableName:h,formattedColumnName:l,formattedTableName:f,formattedDatabase:u,formattedSchemaName:d}}function ZJ(){const e=Me(m=>m.selectedConnectionId),t=Me(m=>m.selectedDatamodelId),n=Me(m=>m.selectedDatabaseName),r=Me(m=>m.selectedSchemaName),s=Me(m=>m.selectedTableName),o=X(m=>m.dashboard.filters)||[],i=X(m=>m.selectedSheetId),a=X(m=>m.actions.addFilter),l=X(m=>m.actions.removeFilter),{removeFilterValues:u}=Ft(),{modelItems:d,tableName:f,connectionType:h}=oy();function p(m,g="sheet",b){var E;const x=(E=d==null?void 0:d.find(_=>_.id===t))==null?void 0:E.name,{qualifiedColumnName:y,qualifiedTableName:v,formattedColumnName:w,formattedTableName:j,formattedDatabase:S}=PZe({columnName:m.column_name,database:n,schemaName:r,tableName:f,connectionType:h,datamodelId:t,modelName:x,field:b});let N;if(g==="sheet"&&i?N=r2e(o,y,j,n||"",S,i):N=o==null?void 0:o.find(_=>_.column===y&&_.table===j&&(_.database===S||_.database===n)),N)u(N.id),l(N.id);else{const _=yr(),k=g==="sheet"&&i?[i]:void 0;return f==="api"&&e?(a({location:g,id:_,column:y,title:m.label||m.column_name,dataType:m.data_type,table:"api",database:"",connectionId:e,operation:"in",applyToSheetIds:k,sql:vE(m.data_type,v,w)}),_):(a({id:_,location:g,column:y,title:m.label||m.column_name,dataType:m.data_type,table:s||"",database:n||"",connectionId:e||"",operation:"in",applyToSheetIds:k,sql:vE(m.data_type,v,(b==null?void 0:b.qualifiedFieldName)||w)}),_)}}return{assignFilter:p}}function OZe({column:e}){const[t,n]=C.useState(!1),r=Me(x=>x.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=WI(r),a=Me(x=>x.selectedDatamodelId),l=Me(x=>x.sqlGen),{modelItems:u,connectionType:d}=oy(),f=Me(x=>x.actions.setSqlGen),h=Me(x=>x.actions.setCardSql),p=Me(x=>x.actions.setRunSql),m=GJ(r);function g(x,y){var S;if(!m||!s){console.warn("Cannot generate SQL: missing table metadata");return}const v=I_(x,l,y),w=(S=u==null?void 0:u.find(N=>N.id===a))==null?void 0:S.name;f(v);const j=R_(v,vi(o||""),vi(s),w||"",d,i||"");j&&(h(j),p(!0)),n(!1)}function b(){return c.jsxs("ul",{className:"text-xs",children:[c.jsx("li",{onClick:()=>g(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),c.jsx("li",{onClick:()=>g(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),c.jsx("li",{onClick:()=>g(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),c.jsx("li",{onClick:()=>g(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),c.jsx("li",{onClick:()=>g(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return m?c.jsxs(yp,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(vp,{asChild:!0,children:c.jsx(tp,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(ef,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]}):null}function FZe({field:e,fieldState:t}){return c.jsxs("div",{className:"w-64 bg-background p-0",children:[c.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[c.jsx("h3",{className:"text-sm font-medium text-foreground",children:e.label||e.name}),c.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:e.dataType})]}),e.description&&c.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:e.description}),t&&t.tooltip&&c.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:c.jsx("p",{className:"text-xs text-muted-foreground",children:t.tooltip})}),c.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:c.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:e.name})})]})}function $Ze({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s}){const o=Me(Y=>Y.isDevMode),i=t==="filter"||t==="inline-filter",a=o||i||(n==null?void 0:n.state)==="unreachable"&&!i,l=X(Y=>Y.dashboard.filters),u=X(Y=>Y.selectedSheetId),d=X(Y=>Y.actions.removeFilter),{removeFilterValues:f}=Ft(),{assignFilter:h}=ZJ(),p=t==="filter"?Ll(l,u):l,m=t==="filter"?p==null?void 0:p.find(Y=>{var W;return Y.title===e.name||((W=Y.column)==null?void 0:W.includes(e.name))}):void 0,g=!!m,b=t==="inline-filter"&&(s==null?void 0:s.some(Y=>Y.column===e.qualifiedFieldName||Y.column===e.name)),x=g||b,y=m&&i?l==null?void 0:l.find(Y=>Y.id===m.id):void 0,v=y&&(y.applyToSheetIds&&y.applyToSheetIds.length>1||y.excludeSheetIds&&y.excludeSheetIds.length>0||!y.applyToSheetIds&&!y.excludeSheetIds&&!y.sheetId);i&&x&&console.log("[SourceField Debug]",{fieldName:e.name,hasActiveFilter:x,activeFilterOnSheet:m?{id:m.id,title:m.title,column:m.column,applyToSheetIds:m.applyToSheetIds,excludeSheetIds:m.excludeSheetIds}:null,activeFilterForField:y?{id:y.id,title:y.title,column:y.column,applyToSheetIds:y.applyToSheetIds,excludeSheetIds:y.excludeSheetIds}:null,isMultiSheetFilter:v,selectedSheetId:u});const[w,j]=C.useState(!1),[S,N]=C.useState(null),{attributes:E,listeners:_,setNodeRef:k,transform:T,transition:M,isDragging:P}=Xx({id:e.id,disabled:a}),[A,R]=C.useState(!1),L=Me(Y=>Y.card),{handleFieldClick:F}=YJ(L),{handleDevModeFieldClick:U,isNumberField:$}=KJ(),I=()=>{y&&(console.log("[SourceField] Removing multi-sheet filter:",y.id),f(y.id),d(y.id)),N(null),j(!1)},B=()=>{if(t==="inline-filter"&&r){r(e);return}if(t==="filter"){const Y={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description,qualifiedFieldName:e.qualifiedFieldName};x&&v?(N({column:Y,field:e}),j(!0)):h(Y,"sheet",e)}else o?U(e):F(e)},z={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},O={transform:ri.Transform.toString(T),transition:M},V=(()=>{if(!n||i)return{};const W={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",...W},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...W},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...W}}[n.state]||W})();return c.jsxs("div",{ref:k,style:O,...a?{}:E,...a?{}:_,className:K("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",P&&"scale-95 opacity-50",!P&&"border",V.borderColor||"border-transparent",V.bgColor||"",V.hoverBorderColor,V.hoverBgColor||"hover:bg-muted",V.opacity,V.cursor,g&&"border-accent-foreground/20 bg-accent",b&&"border-primary/20 bg-primary/10",{"cursor-pointer":o||i,"cursor-grab active:cursor-grabbing":!a&&!o&&!i}),title:n==null?void 0:n.tooltip,children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:B,children:[xb(e.dataType),c.jsx(Mn,{children:c.jsxs(Xt,{children:[c.jsx(Qt,{asChild:!0,children:c.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:c.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${A?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),c.jsx(tn,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:c.jsx(FZe,{field:e,fieldState:n})})]})}),o&&!i&&$(e)&&c.jsx("div",{onClick:Y=>Y.stopPropagation(),children:c.jsx(OZe,{column:z})})]}),A&&c.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:c.jsx(Eo,{className:"",children:c.jsxs(Ii,{className:"space-y-2 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Cz,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.label||e.name})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(roe,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.name})]}),c.jsx(Fe,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),c.jsx(ax,{open:w,onOpenChange:j,children:c.jsxs(fp,{children:[c.jsxs(hp,{children:[c.jsx(mp,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(gp,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(pp,{children:[c.jsx(xp,{children:"Cancel"}),c.jsx(bp,{onClick:I,children:"Remove Filter"})]})]})})]})}const LZe="SEMAPHOR_CALCULATED_FIELD",zZe=["MM-DD-YYYY","YYYY-MM-DD","MM/DD/YYYY","DD/MM/YYYY","MMMM DD, YYYY","MMM DD, YYYY","DD MMM YYYY","Week of MMM DD, YYYY","Week of MMMM DD, YYYY","YYYY-WW","MMM YYYY","MMMM YYYY","YYYY-MM","MM/YYYY","YYYY MMM","Q1 YYYY","YYYY Q1","1st Quarter YYYY","YYYY-Q1","Quarter 1, YYYY","YYYY","YY","custom"];function XJ(e){return!!e.expression}function BZe(e){return!!e.expression}function VZe(e){return!!e.expression}var QJ=(e=>(e.SUBTOTAL="__SUBTOTAL__",e.TOTAL="__TOTAL__",e.ALL="__ALL__",e))(QJ||{}),Yi="Accordion",HZe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[qI,UZe,WZe]=Zb(Yi),[pC]=Nr(Yi,[WZe,fU]),YI=fU(),JJ=C.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(qI.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(KZe,{...o,ref:t}):c.jsx(GZe,{...s,ref:t})})});JJ.displayName=Yi;var[eee,qZe]=pC(Yi),[tee,YZe]=pC(Yi,{collapsible:!1}),GZe=C.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,l]=Br({prop:n,defaultProp:r??"",onChange:s,caller:Yi});return c.jsx(eee,{scope:e.__scopeAccordion,value:C.useMemo(()=>a?[a]:[],[a]),onItemOpen:l,onItemClose:C.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(tee,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(nee,{...i,ref:t})})})}),KZe=C.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i,a]=Br({prop:n,defaultProp:r??[],onChange:s,caller:Yi}),l=C.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=C.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return c.jsx(eee,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(tee,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(nee,{...o,ref:t})})})}),[ZZe,mC]=pC(Yi),nee=C.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=C.useRef(null),l=rt(a,t),u=UZe(n),f=Zc(s)==="ltr",h=ke(e.onKeyDown,p=>{var E;if(!HZe.includes(p.key))return;const m=p.target,g=u().filter(_=>{var k;return!((k=_.ref.current)!=null&&k.disabled)}),b=g.findIndex(_=>_.ref.current===m),x=g.length;if(b===-1)return;p.preventDefault();let y=b;const v=0,w=x-1,j=()=>{y=b+1,y>w&&(y=v)},S=()=>{y=b-1,y<v&&(y=w)};switch(p.key){case"Home":y=v;break;case"End":y=w;break;case"ArrowRight":o==="horizontal"&&(f?j():S());break;case"ArrowDown":o==="vertical"&&j();break;case"ArrowLeft":o==="horizontal"&&(f?S():j());break;case"ArrowUp":o==="vertical"&&S();break}const N=y%x;(E=g[N].ref.current)==null||E.focus()});return c.jsx(ZZe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(qI.Slot,{scope:n,children:c.jsx(ze.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),Gw="AccordionItem",[XZe,GI]=pC(Gw),ree=C.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=mC(Gw,n),i=qZe(Gw,n),a=YI(n),l=ir(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(XZe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(mU,{"data-orientation":o.orientation,"data-state":cee(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});ree.displayName=Gw;var see="AccordionHeader",oee=C.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=mC(Yi,n),o=GI(see,n);return c.jsx(ze.h3,{"data-orientation":s.orientation,"data-state":cee(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});oee.displayName=see;var p_="AccordionTrigger",iee=C.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=mC(Yi,n),o=GI(p_,n),i=YZe(p_,n),a=YI(n);return c.jsx(qI.ItemSlot,{scope:n,children:c.jsx(oSe,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});iee.displayName=p_;var aee="AccordionContent",lee=C.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=mC(Yi,n),o=GI(aee,n),i=YI(n);return c.jsx(iSe,{role:"region","aria-labelledby":o.triggerId,"data-orientation":s.orientation,...i,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...e.style}})});lee.displayName=aee;function cee(e){return e?"open":"closed"}var QZe=JJ,JZe=ree,eXe=oee,uee=iee,dee=lee;const fee=QZe,KI=D.forwardRef(({className:e,...t},n)=>c.jsx(JZe,{ref:n,className:K("border-b",e),...t}));KI.displayName="AccordionItem";const ZI=D.forwardRef(({className:e,children:t,...n},r)=>c.jsx(eXe,{className:"flex",children:c.jsxs(uee,{ref:r,className:K("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,c.jsx(fr,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));ZI.displayName=uee.displayName;const XI=D.forwardRef(({className:e,children:t,...n},r)=>c.jsx(dee,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:c.jsx("div",{className:K("pb-4 pt-0",e),children:t})}));XI.displayName=dee.displayName;function hee({context:e="editor",onFieldSelect:t,inlineFilters:n}={}){var R,L,F,U;const[r,s]=C.useState(""),[o,i]=C.useState("all");Me($=>$.isDevMode);const a=Me($=>$.card.dataSource),l=Me($=>$.card.config),u=Me($=>$.card),{autoJoinMetadata:d}=ka(u),{columns:f=[],columnGroups:h=[],isLoading:p,error:m}=OT(),g=(a==null?void 0:a.mode)==="semanticDomain"?a.semanticDomainId:void 0,{data:b}=UI(g),x=[...(l==null?void 0:l.groupByColumns)||[],...(l==null?void 0:l.metricColumns)||[]];(L=(R=l==null?void 0:l.joinPlan)==null?void 0:R.baseEntity)==null||L.name,(U=(F=d==null?void 0:d.resolvedJoinPlan)==null?void 0:F.baseEntity)==null||U.name,KJ();const y=f.filter($=>$.name.toLowerCase().includes(r.toLowerCase())||$.dataType.toLowerCase().includes(r.toLowerCase())||$.label&&$.label.toLowerCase().includes(r.toLowerCase())||$.qualifiedEntityName&&$.qualifiedEntityName.toLowerCase().includes(r.toLowerCase())),v=$=>{if($.role==="metric"&&XJ($)||$.role==="groupby"&&$.expression)return"calculated";if($.dataType==="number"||$.dataType==="integer"||$.dataType==="float"||$.dataType==="decimal"||$.dataType==="currency")return"metrics";const I=Tr($.dataType);return["date","string","boolean"].includes(I)?"dimensions":I==="number"?"metrics":"dimensions"},j=(o==="all"?y:y.filter($=>v($)===o)).reduce(($,I)=>{const B=I.qualifiedEntityName||"Other Fields";return $[B]||($[B]={label:L_(I.entityName),fields:[]}),$[B].fields.push(I),$},{}),N=Object.keys(j),E=y.filter($=>v($)==="dimensions").length,_=y.filter($=>v($)==="metrics").length,k=y.filter($=>v($)==="calculated").length,T=y.length>0&&e!=="inline-filter",M=e==="inline-filter"?"w-full":"w-[290px]";if(p)return c.jsx("div",{className:K("flex h-full flex-col items-center justify-center py-8",M),children:c.jsx(Wc,{size:"md",color:"muted","aria-label":"Loading data"})});if(m)return c.jsxs("div",{className:K("flex h-full flex-col items-center justify-center py-8",M),children:[c.jsx(vl,{className:"mb-4 h-12 w-12 text-red-300"}),c.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),c.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:m.message||"Failed to load column data"})]});if(!a||!a.selectedEntities||a.selectedEntities.length===0)return c.jsxs("div",{className:K("flex flex-col items-center justify-center py-8 text-center",M),children:[c.jsx(vl,{className:"mb-4 h-12 w-12 text-gray-300"}),c.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),c.jsx("p",{className:"px-4 text-xs text-gray-400",children:e==="filter"||e==="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 P=e==="inline-filter"?"px-3 pb-3":"px-6 pb-6",A=e==="inline-filter"?"overflow-hidden":"";return c.jsxs("div",{className:K("mt-2 flex h-full w-full grow flex-col gap-2",P,A),children:[c.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[f.length>0&&c.jsxs("div",{className:"relative",children:[c.jsx(Vi,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),c.jsx(xn,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:r,onChange:$=>s($.target.value)}),r&&c.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>s(""),type:"button",children:c.jsx(vt,{className:"size-3.5"})})]}),T&&c.jsx(Bs,{defaultValue:"all",value:o,onValueChange:$=>i($),className:"mb-4",children:c.jsxs(ws,{className:"grid h-9 w-full grid-cols-4",children:[c.jsxs(Kt,{value:"all",className:"text-xs",children:["All",c.jsx("span",{className:"ml-2 text-xs font-semibold",children:y.length})]}),c.jsxs(Kt,{value:"dimensions",className:"text-xs",children:[c.jsx(f1,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:E})]}),c.jsxs(Kt,{value:"metrics",className:"text-xs",children:[c.jsx(ep,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:_})]}),c.jsxs(Kt,{value:"calculated",className:"text-xs",children:[c.jsx(Y_,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:k})]})]})})]}),c.jsxs(zl,{className:"min-h-0 overflow-auto",children:[c.jsx(fee,{type:"multiple",defaultValue:N,className:"space-y-2",children:Object.entries(j).map(([$,I])=>{const B=h.find(z=>z.entityName===$)||{entityName:$,label:I.label};return c.jsxs(KI,{value:$,className:"border-none",children:[c.jsx(ZI,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{title:B.label||B.entityName,className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:B.label||B.entityName}),c.jsx(Fe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:I.fields.length})]})}),c.jsx(XI,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:I.fields.map(z=>{const O=FT(z,{joinabilityMap:(b==null?void 0:b.joinabilityMap)||null,selectedFields:x,cardConfig:l,autoJoinMetadata:d});return c.jsx($Ze,{field:z,context:e,fieldState:O,onFieldSelect:t,inlineFilters:e==="inline-filter"?n:void 0},z.id)})})})]},$)})}),Object.keys(j).length===0&&f.length===0&&c.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[c.jsx("p",{children:"No fields found for selected data source"}),c.jsx("p",{className:"mt-1 text-xs text-gray-400",children:e==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),Object.keys(j).length===0&&f.length>0&&c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),c.jsx(ti,{orientation:"horizontal"}),c.jsx(ti,{orientation:"vertical"})]})]})}function pee({context:e="editor"}={}){return c.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",c.jsx(hee,{context:e})," "]})}function mee(){const e=Me(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=Qn();C.useEffect(()=>{var p;if(!e)return;const{tableName:i,schemaName:a,databaseName:l,connectionId:u}=WI(e),d=(p=e.selectedEntities)==null?void 0:p[0],h=(d==null?void 0:d.type)==="model"&&"id"in d?d.id:"";t(u||""),n(l||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function tXe(){mee();const e=X(l=>l.selectedSheetId),t=X(l=>l.selectedFrameId),n=X(l=>l.dashboard),r=X(l=>l.actions.getSelectedFrame),{setSelectedFrameId:s}=Ft(),{setCard:o}=Qn(),i=Me(l=>l.card.dataSource);return C.useEffect(()=>{var u,d;let l=r();if(!l){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(p=>p.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),l=h)}if(l){const f=l.cards.find(h=>h.id===l.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function nXe(){const e=X(o=>o.dashboard.filterLayout),{setFilterLayout:t}=Ft(),n=(e==null?void 0:e.displayMode)||"canvas",r=(e==null?void 0:e.toolbarWrap)??!1,s=(e==null?void 0:e.showDownloadButton)??!1;return c.jsxs(Qr,{children:[c.jsx(Jr,{asChild:!0,children:c.jsx(se,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0","aria-label":"Filter display settings",children:c.jsx(wl,{className:"h-4 w-4"})})}),c.jsx(es,{className:"w-[280px]",align:"end",children:c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{children:[c.jsx("h4",{className:"mb-3 text-sm font-medium",children:"Filter Display"}),c.jsxs(ro,{value:n,onValueChange:o=>t({displayMode:o}),className:"space-y-2",children:[c.jsxs("div",{className:"flex items-start space-x-3",children:[c.jsx(Cn,{value:"canvas",id:"canvas",className:"mt-0.5"}),c.jsxs("div",{className:"grid gap-0.5",children:[c.jsx(ce,{htmlFor:"canvas",className:"cursor-pointer font-normal",children:"Canvas Cards"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Filters as draggable, resizable cards on the dashboard"})]})]}),c.jsxs("div",{className:"flex items-start space-x-3",children:[c.jsx(Cn,{value:"toolbar",id:"toolbar",className:"mt-0.5"}),c.jsxs("div",{className:"grid gap-0.5",children:[c.jsx(ce,{htmlFor:"toolbar",className:"cursor-pointer font-normal",children:"Toolbar"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Compact horizontal toolbar below dashboard controls"})]})]})]})]}),n==="toolbar"&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-center space-x-2 border-t pt-4",children:[c.jsx(Jt,{id:"wrap",checked:r,onCheckedChange:o=>t({toolbarWrap:o===!0})}),c.jsx(ce,{htmlFor:"wrap",className:"cursor-pointer text-sm font-normal",children:"Wrap filters to multiple lines"})]}),c.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[c.jsx(Jt,{id:"download",checked:s,onCheckedChange:o=>t({showDownloadButton:o===!0})}),c.jsx(ce,{htmlFor:"download",className:"cursor-pointer text-sm font-normal",children:"Show download button"})]})]}),c.jsx("p",{className:"border-t pt-3 text-xs text-muted-foreground",children:"Individual filters can override this setting in their configuration."})]})})]})}function rXe(){const e=X(n=>n.actions.setShowFilters),{hasEntities:t}=tXe();return c.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col overflow-hidden border-l",children:[c.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[c.jsx(ce,{className:"px-2 text-base",children:"Dashboard Filters"}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(nXe,{}),c.jsx(se,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:c.jsx(ZK,{})})]})]}),!t&&c.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[c.jsx(vl,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),c.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&c.jsx("div",{className:"flex grow overflow-y-auto",children:c.jsx(Kx,{collisionDetection:qx,children:c.jsx(Zx,{items:[],strategy:eI,children:c.jsx(pee,{context:"filter"})})})})]})}function sXe(){const e=X(r=>r.dashboard.filters),t=X(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?c.jsx("div",{className:K("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>c.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[c.jsx(YR,{filter:r}),c.jsx(Xp,{filter:r})]},r.id))}):null}function oXe(){const e=X(r=>r.showFilters),t=X(r=>r.isVisualEditing),n=X(r=>r.isDashboardEditing);return c.jsxs("div",{role:"dashboard-plus-main",className:K("",{"max-h-0 overflow-hidden":t,"flex grow overflow-hidden":!t}),children:[c.jsxs("section",{className:"flex grow flex-col overflow-y-auto",children:[n&&c.jsx(sXe,{}),c.jsx(VJ,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:c.jsx(rXe,{})})]})}const iXe=C.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-uTcIgnwr.js"))),aXe=C.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-DEedEtg4.js"))),lXe=C.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-Yy1p-xw4.js"))),cXe=C.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-CihSUDmt.js")).then(e=>({default:e.ResourceManagementPanel})));function uXe({showControls:e=!1,showFooter:t=!0,...n}){const r=X(l=>l.isDashboardPanelOpen),s=X(l=>l.isVisualEditing),o=X(l=>l.showDashboardJSON),i=X(l=>l.actions.setIsDashboardPanelOpen),{preferences:a}=n;return c.jsx(Ba,{FallbackComponent:FS,children:c.jsxs(q_,{dashboardProps:n,children:[c.jsx(Qce,{}),c.jsx(HI,{componentType:"surfboard",componentId:n.id}),c.jsx(VI,{children:c.jsxs(HJ,{preferences:a,children:[o&&c.jsx(C.Suspense,{fallback:null,children:c.jsx(lXe,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&c.jsx(C.Suspense,{fallback:null,children:c.jsx(iXe,{})}),c.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&c.jsx(C.Suspense,{fallback:null,children:c.jsx(cXe,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),c.jsx("div",{className:"flex min-w-0 flex-1",children:c.jsxs(cD,{...n,type:"dashboard",children:[s&&c.jsx(C.Suspense,{fallback:null,children:c.jsx(aXe,{})}),c.jsx(oXe,{})]})})]})]})]})})]})})}var dXe=Object.defineProperty,fXe=(e,t,n)=>t in e?dXe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,O0=(e,t,n)=>fXe(e,typeof t!="symbol"?t+"":t,n);const hXe={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},pXe={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}},mXe={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function gXe(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function gee(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const bXe={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=gee(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},xXe={stringify:e=>`${e}`,parse:e=>parseFloat(e)},yXe={stringify:e=>e,parse:e=>e},a2={string:yXe,number:xXe,boolean:hXe,function:pXe,method:bXe,json:mXe},Mm=Symbol.for("r2wc.render"),F0=Symbol.for("r2wc.connected"),Eu=Symbol.for("r2wc.context"),fo=Symbol.for("r2wc.props");function vXe(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),l={},u={},d={},f={};for(const p of i){l[p]=Array.isArray(t.props)?"string":t.props[p];const m=gXe(p);d[p]=m,f[m]=p}for(const p of a)u[p]=Array.isArray(t.events)?{}:t.events[p];class h extends HTMLElement{constructor(){super(),O0(this,o,!0),O0(this,s),O0(this,r,{}),O0(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[fo].container=this.container;for(const m of i){const g=d[m],b=this.getAttribute(g),x=l[m],y=x?a2[x]:null;if(x==="method"){const v=gee(g);Object.defineProperty(this[fo].container,v,{enumerable:!0,configurable:!0,get(){return this[fo][v]},set(w){this[fo][v]=w,this[Mm]()}}),this[fo][m]=y.parse(b,g,this)}y!=null&&y.parse&&b&&(this[fo][m]=y.parse(b,g,this))}for(const m of a)this[fo][m]=g=>{const b=m.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[m]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[F0]=!0,this[Mm]()}disconnectedCallback(){this[F0]=!1,this[Eu]&&n.unmount(this[Eu]),delete this[Eu]}attributeChangedCallback(m,g,b){const x=f[m],y=l[x],v=y?a2[y]:null;x in l&&v!=null&&v.parse&&b&&(this[fo][x]=v.parse(b,m,this),this[Mm]())}[(o=F0,s=Eu,r=fo,Mm)](){this[F0]&&(this[Eu]?n.update(this[Eu],this[fo]):this[Eu]=n.mount(this.container,e,this[fo]))}}for(const p of i){const m=d[p],g=l[p];Object.defineProperty(h.prototype,p,{enumerable:!0,configurable:!0,get(){return this[fo][p]},set(b){this[fo][p]=b;const x=g?a2[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,m,this);this.getAttribute(m)!==y&&this.setAttribute(m,y)}else this[Mm]()}})}return h}function wXe(e,t,n){const r=Pte.createRoot(e),s=C.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function SXe({root:e,ReactComponent:t},n){const r=C.createElement(t,n);e.render(r)}function CXe({root:e}){e.unmount()}function jXe(e,t={}){return vXe(e,t,{mount:wXe,update:SXe,unmount:CXe})}const NXe={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"},kXe=jXe(UJ,{props:NXe});function EL(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 EXe(e){if(Array.isArray(e))return e}function _Xe(e,t,n){return(t=PXe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function MXe(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,s,o,i,a=[],l=!0,u=!1;try{if(o=(n=n.call(e)).next,t!==0)for(;!(l=(r=o.call(n)).done)&&(a.push(r.value),a.length!==t);l=!0);}catch(d){u=!0,s=d}finally{try{if(!l&&n.return!=null&&(i=n.return(),Object(i)!==i))return}finally{if(u)throw s}}return a}}function TXe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1073
1073
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function _L(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 ML(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?_L(Object(n),!0).forEach(function(r){_Xe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):_L(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function DXe(e,t){if(e==null)return{};var n,r,s=RXe(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 RXe(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 IXe(e,t){return EXe(e)||MXe(e,t)||OXe(e,t)||TXe()}function AXe(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 PXe(e){var t=AXe(e,"string");return typeof t=="symbol"?t:t+""}function OXe(e,t){if(e){if(typeof e=="string")return EL(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)?EL(e,t):void 0}}function FXe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function TL(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 DL(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?TL(Object(n),!0).forEach(function(r){FXe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):TL(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function $Xe(){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 ng(e){return function t(){for(var n=this,r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return s.length>=e.length?e.apply(this,s):function(){for(var i=arguments.length,a=new Array(i),l=0;l<i;l++)a[l]=arguments[l];return t.apply(n,[].concat(s,a))}}}function Kw(e){return{}.toString.call(e).includes("Object")}function LXe(e){return!Object.keys(e).length}function Db(e){return typeof e=="function"}function zXe(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function BXe(e,t){return Kw(t)||Ic("changeType"),Object.keys(t).some(function(n){return!zXe(e,n)})&&Ic("changeField"),t}function VXe(e){Db(e)||Ic("selectorType")}function HXe(e){Db(e)||Kw(e)||Ic("handlerType"),Kw(e)&&Object.values(e).some(function(t){return!Db(t)})&&Ic("handlersType")}function UXe(e){e||Ic("initialIsRequired"),Kw(e)||Ic("initialType"),LXe(e)&&Ic("initialContent")}function WXe(e,t){throw new Error(e[t]||e.default)}var qXe={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"},Ic=ng(WXe)(qXe),$0={changes:BXe,selector:VXe,handler:HXe,initial:UXe};function YXe(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};$0.initial(e),$0.handler(t);var n={current:e},r=ng(ZXe)(n,t),s=ng(KXe)(n),o=ng($0.changes)(e),i=ng(GXe)(n);function a(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(d){return d};return $0.selector(u),u(n.current)}function l(u){$Xe(r,s,o,i)(u)}return[a,l]}function GXe(e,t){return Db(t)?t(e.current):t}function KXe(e,t){return e.current=DL(DL({},e.current),t),t}function ZXe(e,t,n){return Db(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 XXe={create:YXe},QXe={paths:{vs:"https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs"}};function JXe(e){return function t(){for(var n=this,r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return s.length>=e.length?e.apply(this,s):function(){for(var i=arguments.length,a=new Array(i),l=0;l<i;l++)a[l]=arguments[l];return t.apply(n,[].concat(s,a))}}}function eQe(e){return{}.toString.call(e).includes("Object")}function tQe(e){return e||RL("configIsRequired"),eQe(e)||RL("configType"),e.urls?(nQe(),{paths:{vs:e.urls.monacoBase}}):e}function nQe(){console.warn(bee.deprecation)}function rQe(e,t){throw new Error(e[t]||e.default)}var bee={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!
1074
1074
  You are using deprecated way of configuration.
1075
1075