react-semaphor 0.1.167 → 0.1.168

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-Bp5qe0eo.js → dashboard-controls-BuFxkJ0D.js} +1 -1
  2. package/dist/chunks/{dashboard-controls-ominVbei.js → dashboard-controls-D8BgZpHI.js} +4 -4
  3. package/dist/chunks/{dashboard-json-Dx_6Ejec.js → dashboard-json-BDsvX0Uu.js} +1 -1
  4. package/dist/chunks/{dashboard-json-C4i7Yq69.js → dashboard-json-DD4VYypW.js} +1 -1
  5. package/dist/chunks/{edit-dashboard-visual-C8JlV4-w.js → edit-dashboard-visual-CTa1kTTW.js} +9 -9
  6. package/dist/chunks/{edit-dashboard-visual-Cd-a5PlC.js → edit-dashboard-visual-DayNtZNn.js} +1093 -1093
  7. package/dist/chunks/{editor-action-buttons-BbqakkOy.js → editor-action-buttons-D6DTq3d_.js} +2 -2
  8. package/dist/chunks/{editor-action-buttons-DgLZlX3X.js → editor-action-buttons-ehW5MaXE.js} +1 -1
  9. package/dist/chunks/{index-DK6LMjBA.js → index-3bJviLws.js} +4 -4
  10. package/dist/chunks/{index-o_l1PmNv.js → index-hyyoLCzh.js} +1 -1
  11. package/dist/chunks/{resource-management-panel-Bcr9R2mo.js → resource-management-panel-BlS2ewdv.js} +3 -3
  12. package/dist/chunks/{resource-management-panel-C-ijbO2j.js → resource-management-panel-f5hj1d5z.js} +1 -1
  13. package/dist/chunks/{schedule-dashboard-_UAuGQ_4.js → schedule-dashboard-CmPbp16F.js} +1 -1
  14. package/dist/chunks/{schedule-dashboard-DwdOvSX8.js → schedule-dashboard-DDFyZ7H6.js} +3 -3
  15. package/dist/chunks/{use-role-aware-display-preferences-Bg5K1xOj.js → use-role-aware-display-preferences-BnJ9ANkQ.js} +1 -1
  16. package/dist/chunks/{use-role-aware-display-preferences-D-icyP5A.js → use-role-aware-display-preferences-C5ZuE5cf.js} +1 -1
  17. package/dist/chunks/{use-visual-utils-BwfHhd-4.js → use-visual-utils-BWVI4_SZ.js} +1 -1
  18. package/dist/chunks/{use-visual-utils--qc4n_jK.js → use-visual-utils-Cj6Qddve.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 +4 -4
  23. package/dist/surfboard/index.cjs +1 -1
  24. package/dist/surfboard/index.js +1 -1
  25. package/package.json +1 -1
@@ -1095,7 +1095,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
1095
1095
 
1096
1096
  `)},flush(e){e.enqueue(`data: [DONE]
1097
1097
 
1098
- `)}})}});var TQe=NXe(()=>See(ai([Kn({type:Tt("text-start"),id:st(),providerMetadata:ur.optional()}),Kn({type:Tt("text-delta"),id:st(),delta:st(),providerMetadata:ur.optional()}),Kn({type:Tt("text-end"),id:st(),providerMetadata:ur.optional()}),Kn({type:Tt("error"),errorText:st()}),Kn({type:Tt("tool-input-start"),toolCallId:st(),toolName:st(),providerExecuted:Ys().optional(),dynamic:Ys().optional()}),Kn({type:Tt("tool-input-delta"),toolCallId:st(),inputTextDelta:st()}),Kn({type:Tt("tool-input-available"),toolCallId:st(),toolName:st(),input:sa(),providerExecuted:Ys().optional(),providerMetadata:ur.optional(),dynamic:Ys().optional()}),Kn({type:Tt("tool-input-error"),toolCallId:st(),toolName:st(),input:sa(),providerExecuted:Ys().optional(),providerMetadata:ur.optional(),dynamic:Ys().optional(),errorText:st()}),Kn({type:Tt("tool-output-available"),toolCallId:st(),output:sa(),providerExecuted:Ys().optional(),dynamic:Ys().optional(),preliminary:Ys().optional()}),Kn({type:Tt("tool-output-error"),toolCallId:st(),errorText:st(),providerExecuted:Ys().optional(),dynamic:Ys().optional()}),Kn({type:Tt("reasoning-start"),id:st(),providerMetadata:ur.optional()}),Kn({type:Tt("reasoning-delta"),id:st(),delta:st(),providerMetadata:ur.optional()}),Kn({type:Tt("reasoning-end"),id:st(),providerMetadata:ur.optional()}),Kn({type:Tt("source-url"),sourceId:st(),url:st(),title:st().optional(),providerMetadata:ur.optional()}),Kn({type:Tt("source-document"),sourceId:st(),mediaType:st(),title:st(),filename:st().optional(),providerMetadata:ur.optional()}),Kn({type:Tt("file"),url:st(),mediaType:st(),providerMetadata:ur.optional()}),Kn({type:bee(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:st().optional(),data:sa(),transient:Ys().optional()}),Kn({type:Tt("start-step")}),Kn({type:Tt("finish-step")}),Kn({type:Tt("start"),messageId:st().optional(),messageMetadata:sa().optional()}),Kn({type:Tt("finish"),finishReason:mee(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:sa().optional()}),Kn({type:Tt("abort")}),Kn({type:Tt("message-metadata"),messageMetadata:sa()})])));function RQe(e){return e.type.startsWith("data-")}function Mee(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]=Mee(o,s):n[r]=s}return n}function IQe(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 Tee(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await a1({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await a1({text:IQe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function yv(e){return e.type.startsWith("tool-")}function AQe(e){return e.type==="dynamic-tool"}function L_(e){return yv(e)||AQe(e)}function y6(e){return e.type.split("-").slice(1).join("-")}function PQe({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 OQe({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await r(async({state:u,write:d})=>{var f,h,m,p;function g(w){const S=u.message.parts.filter(yv).find(j=>j.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(j=>j.type==="dynamic-tool").find(j=>j.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 N;const S=u.message.parts.find(_=>yv(_)&&_.toolCallId===w.toolCallId),j=w,E=S;S!=null?(S.state=w.state,E.input=j.input,E.output=j.output,E.errorText=j.errorText,E.rawInput=j.rawInput,E.preliminary=j.preliminary,E.providerExecuted=(N=j.providerExecuted)!=null?N:S.providerExecuted,j.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.state,input:j.input,output:j.output,rawInput:j.rawInput,errorText:j.errorText,providerExecuted:j.providerExecuted,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}function y(w){var N,S;const j=u.message.parts.find(k=>k.type==="dynamic-tool"&&k.toolCallId===w.toolCallId),E=w,_=j;j!=null?(j.state=w.state,_.toolName=w.toolName,_.input=E.input,_.output=E.output,_.errorText=E.errorText,_.rawInput=(N=E.rawInput)!=null?N:_.rawInput,_.preliminary=E.preliminary,_.providerExecuted=(S=E.providerExecuted)!=null?S:j.providerExecuted,E.providerMetadata!=null&&j.state==="input-available"&&(j.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 N=u.message.metadata!=null?Mee(u.message.metadata,w):w;t!=null&&await m6({value:N,schema:t}),u.message.metadata=N}}switch(a.type){case"text-start":{const w={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=w,u.message.parts.push(w),d();break}case"text-delta":{const w=u.activeTextParts[a.id];w.text+=a.delta,w.providerMetadata=(f=a.providerMetadata)!=null?f:w.providerMetadata,d();break}case"text-end":{const w=u.activeTextParts[a.id];w.state="done",w.providerMetadata=(h=a.providerMetadata)!=null?h:w.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const w={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=w,u.message.parts.push(w),d();break}case"reasoning-delta":{const w=u.activeReasoningParts[a.id];w.text+=a.delta,w.providerMetadata=(m=a.providerMetadata)!=null?m:w.providerMetadata,d();break}case"reasoning-end":{const w=u.activeReasoningParts[a.id];w.providerMetadata=(p=a.providerMetadata)!=null?p:w.providerMetadata,w.state="done",delete u.activeReasoningParts[a.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),d();break}case"tool-input-start":{const w=u.message.parts.filter(yv);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:N}=await Tee(w.text);w.dynamic?y({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:N}):x({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:N}),d();break}case"tool-input-available":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d();break}case"tool-output-available":{if(a.dynamic){const 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:y6(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:y6(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(RQe(a)){(n==null?void 0:n[a.type])!=null&&await m6({value:a.data,schema:n[a.type]});const w=a;if(w.transient){i==null||i(w);break}const N=w.id!=null?u.message.parts.find(S=>w.type===S.type&&w.id===S.id):void 0;N!=null?N.data=w.data:u.message.parts.push(w),i==null||i(w),d()}}l.enqueue(a)})}}))}async function FQe({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()}}fy({prefix:"aitxt",size:24});fy({prefix:"aiobj",size:24});var $Qe=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()})}};fy({prefix:"aiobj",size:24});var LQe={};wQe(LQe,{object:()=>BQe,text:()=>zQe});var zQe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),BQe=({schema:e})=>{const t=yQe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await Tee(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 a1({text:n});if(!s.success)throw new b6({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 pA({value:s.value,schema:t});if(!o.success)throw new b6({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 VQe(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 HQe=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 If(this.body),l=await If(this.headers),u=await If(this.credentials),d={...$u(l),...$u(t.headers)},f=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:d,credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),h=(r=f==null?void 0:f.api)!=null?r:this.api,m=(f==null?void 0:f.headers)!==void 0?$u(f.headers):d,p=(f==null?void 0:f.body)!==void 0?f.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},g=(s=f==null?void 0:f.credentials)!=null?s:u,x=await((o=this.fetch)!=null?o:globalThis.fetch)(h,{method:"POST",headers:f6({"Content-Type":"application/json",...m},`ai-sdk/${x6}`,d6()),body:JSON.stringify(p),credentials:g,signal:e});if(!x.ok)throw new Error((i=await x.text())!=null?i:"Failed to fetch the chat response.");if(!x.body)throw new Error("The response body is empty.");return this.processResponseStream(x.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await If(this.body),a=await If(this.headers),l=await If(this.credentials),u={...$u(a),...$u(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?$u(d.headers):u,m=(r=d==null?void 0:d.credentials)!=null?r:l,g=await((s=this.fetch)!=null?s:globalThis.fetch)(f,{method:"GET",headers:f6(h,`ai-sdk/${x6}`,d6()),credentials:m});if(g.status===204)return null;if(!g.ok)throw new Error((o=await g.text())!=null?o:"Failed to fetch the chat response.");if(!g.body)throw new Error("The response body is empty.");return this.processResponseStream(g.body)}},bA=class extends HQe{constructor(e={}){super(e)}processResponseStream(e){return EXe({stream:e,schema:TQe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},UQe=class{constructor({generateId:e=bXe,id:t=e(),transport:n=new bA,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new $Qe,this.sendMessage=async(f,h)=>{var m,p,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(m=this.lastMessage)==null?void 0:m.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await VQe(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:x=f,f.messageId!=null){const y=this.state.messages.findIndex(v=>v.id===f.messageId);if(y===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[y].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,y+1),this.state.replaceMessage(y,{...x,id:f.messageId,role:(p=x.role)!=null?p:"user",metadata:f.metadata})}else this.state.pushMessage({...x,id:(g=x.id)!=null?g:this.generateId(),role:(b=x.role)!=null?b:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const m=f==null?this.state.messages.length-1:this.state.messages.findIndex(p=>p.id===f);if(m===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[m].role==="assistant"?m:m+1),await this.makeRequest({trigger:"regenerate-message",messageId:f,...h})},this.resumeStream=async(f={})=>{await this.makeRequest({trigger:"resume-stream",...f})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolOutput=async({state:f="output-available",tool:h,toolCallId:m,output:p,errorText:g})=>this.jobExecutor.run(async()=>{var b,x;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(w=>L_(w)&&w.toolCallId===m?{...w,state:f,output:p,errorText:g}:w)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(w=>L_(w)&&w.toolCallId===m?{...w,state:f,output:p,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 m={state:PQe({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};m.abortController.signal.addEventListener("abort",()=>{d=!0}),this.activeResponse=m;let p;if(e==="resume-stream"){const b=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(b==null){this.setStatus({status:"ready"});return}p=b}else p=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:m.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const g=b=>this.jobExecutor.run(()=>b({state:m.state,write:()=>{var x;this.setStatus({status:"streaming"}),m.state.message.id===((x=this.lastMessage)==null?void 0:x.id)?this.state.replaceMessage(this.state.messages.length-1,m.state.message):this.state.pushMessage(m.state.message)}}));await FQe({stream:OQe({stream:p,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:g,onError:b=>{throw b}}),onError:b=>{throw b}}),this.setStatus({status:"ready"})}catch(m){if(d||m.name==="AbortError")return d=!0,this.setStatus({status:"ready"}),null;h=!0,m instanceof TypeError&&(m.message.toLowerCase().includes("fetch")||m.message.toLowerCase().includes("network"))&&(f=!0),this.onError&&m instanceof Error&&this.onError(m),this.setStatus({status:"error",error:m})}finally{try{(i=this.onFinish)==null||i.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:d,isDisconnect:f,isError:h,finishReason:(o=this.activeResponse)==null?void 0:o.state.finishReason})}catch(m){console.error(m)}this.activeResponse=void 0}(a=this.sendAutomaticallyWhen)!=null&&a.call(this,{messages:this.state.messages})&&!h&&await this.makeRequest({trigger:"submit-message",messageId:(l=this.lastMessage)==null?void 0:l.id,metadata:t,headers:n,body:r})}};function WQe({messages:e}){const t=e[e.length-1];if(!t||t.role!=="assistant")return!1;const n=t.parts.reduce((s,o,i)=>o.type==="step-start"?i:s,-1),r=t.parts.slice(n+1).filter(L_).filter(s=>!s.providerExecuted);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function YQe(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 qQe=YQe;const GQe=Jc(qQe);var Ree=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Fn=(e,t,n)=>(Ree(e,t,"read from private field"),n?n.call(e):t.get(e)),Ji=(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)},tc=(e,t,n,r)=>(Ree(e,t,"write to private field"),t.set(e,n),n);function KQe(e,t){return t!=null?GQe(e,t):e}var Fo,vv,wv,lg,cg,ug,Lf,z_,B_,ZQe=class{constructor(e=[]){Ji(this,Fo,void 0),Ji(this,vv,"ready"),Ji(this,wv,void 0),Ji(this,lg,new Set),Ji(this,cg,new Set),Ji(this,ug,new Set),this.pushMessage=t=>{tc(this,Fo,Fn(this,Fo).concat(t)),Fn(this,Lf).call(this)},this.popMessage=()=>{tc(this,Fo,Fn(this,Fo).slice(0,-1)),Fn(this,Lf).call(this)},this.replaceMessage=(t,n)=>{tc(this,Fo,[...Fn(this,Fo).slice(0,t),this.snapshot(n),...Fn(this,Fo).slice(t+1)]),Fn(this,Lf).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?KQe(t,n):t;return Fn(this,lg).add(r),()=>{Fn(this,lg).delete(r)}},this["~registerStatusCallback"]=t=>(Fn(this,cg).add(t),()=>{Fn(this,cg).delete(t)}),this["~registerErrorCallback"]=t=>(Fn(this,ug).add(t),()=>{Fn(this,ug).delete(t)}),Ji(this,Lf,()=>{Fn(this,lg).forEach(t=>t())}),Ji(this,z_,()=>{Fn(this,cg).forEach(t=>t())}),Ji(this,B_,()=>{Fn(this,ug).forEach(t=>t())}),tc(this,Fo,e)}get status(){return Fn(this,vv)}set status(e){tc(this,vv,e),Fn(this,z_).call(this)}get error(){return Fn(this,wv)}set error(e){tc(this,wv,e),Fn(this,B_).call(this)}get messages(){return Fn(this,Fo)}set messages(e){tc(this,Fo,[...e]),Fn(this,Lf).call(this)}};Fo=new WeakMap;vv=new WeakMap;wv=new WeakMap;lg=new WeakMap;cg=new WeakMap;ug=new WeakMap;Lf=new WeakMap;z_=new WeakMap;B_=new WeakMap;var zf,v6=class extends UQe{constructor({messages:e,...t}){const n=new ZQe(e);super({...t,state:n}),Ji(this,zf,void 0),this["~registerMessagesCallback"]=(r,s)=>Fn(this,zf)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>Fn(this,zf)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>Fn(this,zf)["~registerErrorCallback"](r),tc(this,zf,n)}};zf=new WeakMap;function Iee({experimental_throttle:e,resume:t=!1,...n}={}){const r=C.useRef("chat"in n?n.chat:new v6(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new v6(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 XQe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function QQe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function JQe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function eJe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function Aee(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:eJe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function Pee(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 tJe(){var b;const{authToken:e,tokenProps:t}=Ge(),n=X(x=>x.dashboard.aiScopeTables),r=(b=C1().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=Iee({transport:new bA({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=Yi.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:IY(x)}})}),onToolCall:m,sendAutomaticallyWhen:WQe,onFinish({isAbort:x,isDisconnect:y,isError:v}){console.log(x?"[Dashboard Assistant] Stream aborted by user":y?"[Dashboard Assistant] Stream disconnected (network error)":v?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully")},onError(x){var y;if(x.name==="AbortError"||(y=x.message)!=null&&y.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)");return}console.error("[Dashboard Assistant] Stream error:",x)}});async function m({toolCall:x}){if(x.toolName==="getCurrentTableScope"&&u({tool:x.toolName,toolCallId:x.toolCallId,output:{tables:Aee(n||[])}}),x.toolName==="getDashboardContext"){const y=X.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const p=!["ready","error"].includes(l),g=Pee(d);return{sendMessage:s,regenerate:a,isLoading:p,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function Oee(){var u;const{authToken:e,tokenProps:t}=Ge(),n=(u=C1().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=hn({queryKey:["assistant-profile",n],queryFn:()=>Yn(`${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 Fee({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(p8,{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(re,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function l1(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(HD,{className:r});case"view":return c.jsx(Fc,{className:r});case"materialized view":return c.jsx(nle,{className:r});case"model":return c.jsx(D1,{className:r});case"file":return c.jsx(Fi,{className:r});case"dataset":return c.jsx(Cl,{className:r});case"upload":return c.jsx(qD,{className:r});case"url":return c.jsx(w8,{className:r});default:return c.jsx(E1,{className:r})}}const $ee=T.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(Ui,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(Ss.Input,{ref:n,className:Z("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})]}));$ee.displayName=Ss.Input.displayName;const U0=e=>e.label||(e==null?void 0:e.name),w6=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function nJe({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,m]=C.useState(""),[p,g]=C.useState(""),b=s.filter(S=>{if(!h)return!0;const j=U0(S).toLowerCase(),E=w6(S).toLowerCase(),_=h.toLowerCase();return j.includes(_)||E.includes(_)});C.useEffect(()=>{e||(m(""),g(""))},[e]),C.useEffect(()=>{b.length>0&&!p&&g(U0(b[0]))},[b,p]);const x=()=>{if(!p)return;const S=b.find(j=>U0(j)===p);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(j=>"id"in S&&"id"in j?S.id===j.id:S.name===j.name&&S.connectionId===j.connectionId),w=o.length===s.length,N=o.length>0;return c.jsx(c.Fragment,{children:c.jsxs(Lm,{shouldFilter:!1,value:p,onValueChange:g,onKeyDown:y,children:[s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[c.jsx($ee,{placeholder:"Search entities...",value:h,onValueChange:m,className:"flex-1 border-0",autoFocus:!0}),!f&&c.jsxs(re,{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(Sr,{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(re,{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"}),N&&c.jsxs(re,{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(yt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),c.jsxs(zm,{className:"min-h-60",children:[c.jsx(Bm,{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(re,{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(Sr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx(Vm,{children:b.map((S,j)=>{const E=v(S),_="id"in S?S.id:`${S.connectionId}-${S.name}`,k=U0(S);return c.jsxs(Hm,{value:k,onSelect:()=>{E?n==null||n(S):t(S)},onMouseDown:M=>{M.preventDefault(),M.stopPropagation()},className:Z("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:l1(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:w6(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 V_=e=>e.name||e.name,rJe=e=>{const t=V_(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 sJe({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(_n,{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(Zt,{children:[c.jsx(Xt,{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:[l1(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:V_(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(yt,{className:"h-3 w-3"})})]})}),c.jsx(en,{side:"top",className:"max-w-xs",children:rJe(d)})]},h)}),u&&c.jsxs(Zt,{open:s,onOpenChange:o,children:[c.jsx(Xt,{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(rle,{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(yt,{className:"h-3 w-3"})})]})}),c.jsx(en,{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:l1(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:V_(d)}),c.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),c.jsx(re,{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(yt,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function Lee(e){return e.type==="dataset"&&e.label||e.name}function oJe(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 iJe({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,"]"]}),Lee(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(yt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function aJe(e){const{tokenProps:t}=Ge(),n=X(l=>l.authToken)||e;_e(l=>l.selectedConnectionId),_e(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}=hn({queryKey:["semantic-domains"],queryFn:()=>Yn(`${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 lJe(e,t){const{tokenProps:n}=Ge(),r=X(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:l}=hn({queryKey:["datasets",e],queryFn:()=>Yn(`${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 cJe(e){var g,b;const{tokenProps:t}=Ge(),n=X(x=>x.authToken)||e,{connections:r}=$a(e),s=_e(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:m}=hn({queryKey:["databases",s],queryFn:()=>Yn(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),p=(b=d==null?void 0:d.databases)==null?void 0:b.map(x=>({id:x.database_name,name:x.database_name}));return{isPending:f,error:h,databases:p||[],refetch:m,label:l}}function uJe(e){var g;const{tokenProps:t}=Ge(),n=X(b=>b.authToken)||e,{connections:r}=$a(e),s=_e(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=_e(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:m}=hn({queryKey:["schemas",s,o],queryFn:()=>Yn(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),p=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:p||[],refetch:m,label:l}}function zee(e){const{tokenProps:t}=Ge(),n=X(h=>h.authToken)||e,{connections:r}=$a(e),s=_e(h=>{var m,p;return(p=(m=h==null?void 0:h.card)==null?void 0:m.dataSource)==null?void 0:p.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:l,error:u,refetch:d}=hn({queryKey:["dataModels",s],queryFn:()=>Yn(`${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 dJe(){var N,S,j;const e=_e(E=>E.card.dataSource);_e(E=>E.actions.updateDirectSource);const t=_e(E=>E.actions.updateDataSource),[n,r]=C.useState(""),{selectedConnection:s,error:o}=$a(),{databases:i,isPending:a,error:l,label:u}=cJe(),{schemas:d,isPending:f,error:h,label:m}=uJe(),{error:p}=zee(),g=s==null?void 0:s.capabilities.path.includes("schema"),b=s==null?void 0:s.capabilities.path.includes("database"),x=u==null?void 0:u.toLowerCase(),y=m==null?void 0:m.toLowerCase(),v=E=>{e&&t({...e,dbSelection:{database:E,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},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||p)&&c.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[c.jsx("div",{className:"flex items-center",children:c.jsxs("div",{className:"text-sm text-red-800",children:[c.jsx("strong",{children:"Error loading data:"}),c.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&c.jsxs("li",{children:["Connections: ",o]}),l&&c.jsxs("li",{children:[u,": ",l.message]}),h&&c.jsxs("li",{children:[m,": ",h.message]}),p&&c.jsxs("li",{children:["Data Models: ",p.message]})]})]})}),c.jsx(re,{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:((N=e==null?void 0:e.dbSelection)==null?void 0:N.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(ge,{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:m}),c.jsxs(nt,{value:((j=e==null?void 0:e.dbSelection)==null?void 0:j.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(ge,{className:"hover:bg-muted",value:E.id,children:E.name},E.id))})]})]})]})]})}function fJe(){const e=_e(l=>l.card.dataSource),t=_e(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(qD,{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(re,{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(Fi,{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(re,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(l.id),children:c.jsx(yt,{className:"h-3 w-3"})})]},l.id))})]})]})}function hJe(){const e=_e(f=>f.card.dataSource),t=_e(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(m=>m.id!==f);t({...e,selectedEntities:h})},d=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(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(re,{onClick:l,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[c.jsx(Sr,{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(E1,{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(re,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:c.jsx(yt,{className:"h-3 w-3"})})]},f.id))})]})]})}function mJe(e,t){var y,v;const{tokenProps:n}=Ge(),r=X(w=>w.authToken)||t,{connections:s}=$a(t),o=_e(w=>{var N,S;return(S=(N=w==null?void 0:w.card)==null?void 0:N.dataSource)==null?void 0:S.connectionId}),i=_e(w=>{var N,S,j;return(j=(S=(N=w==null?void 0:w.card)==null?void 0:N.dataSource)==null?void 0:S.dbSelection)==null?void 0:j.database}),a=_e(w=>{var N,S,j;return(j=(S=(N=w==null?void 0:w.card)==null?void 0:N.dataSource)==null?void 0:S.dbSelection)==null?void 0:j.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:m,isLoading:p,error:g,refetch:b}=hn({queryKey:[e,o,i,a],queryFn:()=>Yn(`${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 N;return{connectionId:l==null?void 0:l.id,connectionType:l==null?void 0:l.type,dialect:l==null?void 0:l.dialect,type:e,dbObjectType:(N=w==null?void 0:w.table_type)==null?void 0:N.toLowerCase(),id:w[`${e}_name`],database:i,schema:a,name:w[`${e}_name`]}});return{isPending:m,isLoading:p,error:g,entities:x||[],refetch:b,label:d}}function c1({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(Oc,{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 pJe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=$a(),[i,a]=C.useState(""),[l,u]=C.useState(""),[d,f]=C.useState("tables"),{updateDataSource:h,setSelectedConnectionId:m}=Qn(),{entities:p,isLoading:g,error:b}=mJe("table"),{dataModels:x,isPending:y,error:v}=zee(),w=k=>{const M=s.find(R=>R.id===k);if(!M)return;const D=M.type==="upload"?"upload":M.type==="url"?"url":"database";h({...e,connectionId:k,connectionType:M.type,mode:D,dbSelection:{database:"",schema:"",entityType:"table"}}),m(k)},N=k=>{var I,A;const M=n||[],D=M.some(L=>L.name===k.name&&L.type===k.type);let R;if(D)R=M.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:((I=e.dbSelection)==null?void 0:I.database)||"",schema:((A=e.dbSelection)==null?void 0:A.schema)||"",name:k.name,dialect:k.dialect};R=[...M,L]}t==null||t(R)},S=k=>{const M=n||[],D=M.some(I=>I.type==="model"&&I.name===k.name);let R;D?R=M.filter(I=>!(I.type==="model"&&I.name===k.name)):R=[...M,k],t==null||t(R)},j=p.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 M=[...k];if(d==="tables"){const R=j.filter(I=>!k.some(A=>A.name===I.name&&A.type==="table")).map(I=>{var A,L;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:I.dbObjectType,database:((A=e.dbSelection)==null?void 0:A.database)||"",schema:((L=e.dbSelection)==null?void 0:L.schema)||"",name:I.name,dialect:I.dialect}});M=[...k,...R]}else if(d==="datamodels"){const D=E.filter(R=>!k.some(I=>I.name===R.name&&I.type==="model"));M=[...k,...D]}t(M)},[d,j,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(ge,{className:"hover:bg-muted",value:k.id,children:c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(Cl,{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(fJe,{}),e.connectionType==="url"&&c.jsx(hJe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(dJe,{}),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(vs,{className:"grid w-full grid-cols-2",children:[c.jsxs(Gt,{value:"tables",children:["Tables & Views (",j.length,")"]}),c.jsxs(Gt,{value:"datamodels",children:["Data Models (",E.length,")"]})]}),c.jsxs(sr,{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(c1,{title:"Error loading tables",message:b.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):j.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):j.map(k=>{const M=n.some(D=>D.name===k.name&&D.type==="table");return c.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>N(k),children:[c.jsx(Qt,{id:`table-${k.name}`,checked:M,onCheckedChange:()=>N(k),onClick:D=>D.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(sr,{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(c1,{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 M=n.some(D=>D.name===k.name&&D.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(Qt,{id:`dataModel-${k.name}`,checked:M,onCheckedChange:()=>S(k),onClick:D=>D.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 gJe({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:s=[],isRestricted:o=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var N;const[l,u]=C.useState(""),d=C.useCallback(S=>{const j={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:S};t({...j})},[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:m}=aJe(),p=o?f.filter(S=>s.includes(S.id)):f,{datasets:g,isPending:b,error:x}=lJe(e==null?void 0:e.semanticDomainId),y=S=>{const j=r||[],E=j.some(k=>k.id===S.id&&k.type==="dataset");let _;if(E)_=j.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};_=[...j,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(M=>M.id===k.id&&M.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:((N=p.find(S=>S.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:N.label)||"Select semantic domain"})}),c.jsx(tt,{children:p.map(S=>c.jsx(ge,{className:"hover:bg-muted",value:S.id,children:c.jsxs("div",{className:"flex flex-col items-start",children:[c.jsx("span",{className:"font-medium",children:S.label}),c.jsx("span",{className:"text-xs",children:S.description})]})},S.id))})]}),m&&c.jsx(c1,{title:"Error loading semantic models",message:m.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(c1,{title:"Error loading datasets",message:x.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):v.length===0?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:l?"No datasets match your search":"No datasets available"}):v.map(S=>{const j=r.some(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(Qt,{id:`dataset-${S.id}`,checked:j,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 xA({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(M=>M.isVisualEditing),f=X(M=>M.dashboard.aiContext),{setAiContext:h}=Ot(),m=C.useRef(null),[p,g]=C.useState(!1),b=i&&i.length>0,x=!b,y=b&&i.length===1?i[0]:void 0,v=C.useCallback(M=>{const D=M;u({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:D,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...D!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,u]),w=C.useCallback(M=>{u({...n,...M})},[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||[]):(m.current=null,g(!1))},[e,n==null?void 0:n.selectedEntities,r,u,s,n]);const N=M=>{const D=a.filter(R=>!(R.name===M.name&&R.type===M.type));l(D)},S=()=>{l([])},j=C.useCallback(M=>{l(M)},[]),E=C.useCallback(()=>{m.current&&m.current()},[]),_=C.useCallback(M=>{m.current=M,g(!0)},[]);function k(){var M,D;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const R=(M=a==null?void 0:a[0])==null?void 0:M.connectionId,I=(D=a==null?void 0:a[0])==null?void 0:D.connectionType;u({...n,connectionId:R,connectionType:I,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return c.jsx(ns,{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(ys,{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(vs,{className:"grid w-full grid-cols-2",children:[c.jsx(Gt,{value:"database",children:"Direct Source"}),c.jsx(Gt,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&c.jsx(gJe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,allowedDomainIds:i||[],isRestricted:b,autoSelectedDomainId:y,onRegisterSelectAll:_}),(n==null?void 0:n.mode)==="database"&&x&&c.jsx(pJe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,onRegisterSelectAll:_})]})}),c.jsx(iJe,{selectedEntities:a,onDeselectEntity:N}),c.jsx(xs,{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(re,{variant:"outline",onClick:E,disabled:!p,children:"Select All"}),c.jsx(re,{variant:"outline",onClick:S,disabled:a.length===0,children:"Clear All"}),c.jsxs(re,{variant:"outline",onClick:()=>t(!1),children:[c.jsx(yt,{className:"mr-2 h-4 w-4"}),"Close"]}),c.jsxs(re,{onClick:k,children:[c.jsx(Mr,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function bJe({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=tl-n;if(l.length>u){Oe.error(`You can only attach ${tl} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=NJ(l);if(f.forEach(({file:h,error:m})=>{Oe.error(`${h.name}: ${m}`)}),d.length>0)try{const h=await Promise.all(d.map(m=>aA(m)));e(h)}catch(h){console.error("Failed to process files:",h),Oe.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>=tl}),c.jsx(re,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=tl,title:n>=tl?`Maximum ${tl} files allowed`:"Attach files",children:c.jsx($D,{className:"h-4 w-4 text-muted-foreground"})})]})}function xJe({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(),m=f.clientX,p=f.clientY;(m<h.left||m>=h.right||p<h.top||p>=h.bottom)&&i(!1)},[]),u=C.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=C.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const m=tl-r;if(h.length>m){Oe.error(`You can only attach ${tl} files per message. You have ${m} slot(s) remaining.`);return}const{valid:p,errors:g}=NJ(h);if(g.forEach(({file:b,error:x})=>{Oe.error(`${b.name}: ${x}`)}),p.length>0)try{const b=await Promise.all(p.map(x=>aA(x)));t(b),Oe.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),Oe.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:Z("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(qD,{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:[tl-r," slot(s) available"]})]})})]})}const yA=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,m]=C.useState(!1),[p,g]=C.useState(!1),b=C.useRef(null),x=Wm();b2e(),g2e();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:w,setShowReasoning:N}=_S(),{queueMessage:S}=Ym(),{addFileAttachment:j,removeFileAttachment:E,clearFileAttachments:_,getFileAttachments:k}=BT(),M=zT(l),D=_e(V=>V.card.dataSource),R=X(V=>V.dashboard.aiContext),I=X(V=>{var G;return(G=V.dashboard.aiContext)==null?void 0:G.selectedEntities});C.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const A=C.useCallback(()=>{const V=b.current;if(V){if(!e||e.length===0){V.style.height="10px";return}V.style.height="auto";const G=Math.min(Math.max(V.scrollHeight,10),200);V.style.height=`${G}px`}},[e]);C.useEffect(()=>{A()},[A]),C.useEffect(()=>{const V=setTimeout(()=>{A()},0);return()=>clearTimeout(V)},[A]);const L=()=>{const V=e.trim();!V&&M.length===0||(a!=="ready"?(S(l,V,M),t(""),_(l)):r({preventDefault:()=>{}}))},F=V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),L()),V.key==="@"&&(U(),f(!0))},H=C.useCallback(V=>{const G=VYe(V.nativeEvent);G.length>0&&(V.preventDefault(),G.forEach(async K=>{const ee=await aA(K);j(l,ee)}))},[j,l]),$=C.useCallback(V=>{V.forEach(G=>{j(l,G)})},[j,l]),P=C.useCallback(V=>{V.forEach(G=>{j(l,G)})},[j,l]),Y=C.useCallback(V=>{E(l,V)},[E,l]),z=V=>{if(x.selectedEntities.some(K=>K.id&&K.id===V.id||K.name===V.name)){const K=x.selectedEntities.filter(ee=>!(ee.id&&ee.id===V.id||ee.name===V.name));y({selectedEntities:K})}else{const K=[...x.selectedEntities,V];y({selectedEntities:K})}},O=V=>{z(V)},W=V=>{var ee;if(!x.selectedEntities.some(Q=>Q.id&&Q.id===V.id||Q.name===V.name)){const Q=[...x.selectedEntities,V];y({selectedEntities:Q})}const K="label"in V?V.label:V.name;t(e+`@${K} `),f(!1),(ee=b.current)==null||ee.focus()},B=V=>{const G=x.selectedEntities.filter(Q=>!(Q.id&&Q.id===V.id||Q.name===V.name));y({selectedEntities:G});const ee=`@${"label"in V?V.label:V.name}`;e.includes(ee)&&t(e.replace(ee,"").trim())},q=V=>{const G=new Set(V.map(Q=>Q.id||Q.name)),K=x.selectedEntities.filter(Q=>!G.has(Q.id||Q.name));y({selectedEntities:K});let ee=e;V.forEach(Q=>{const oe=`@${"label"in Q?Q.label:Q.name}`;ee=ee.replace(oe,"").trim()}),t(ee)},U=C.useCallback(()=>{x.selectedEntities.length===0&&y({selectedEntities:(R==null?void 0:R.selectedEntities)||[]})},[x.selectedEntities.length,R==null?void 0:R.selectedEntities,y]);return c.jsxs(xJe,{onFilesDropped:$,currentFileCount:M.length,disabled:s,className:"space-y-4",children:[c.jsx(sJe,{entities:x.selectedEntities,availableEntities:I||[],onRemoveEntity:B,onRemoveEntities:q}),M.length>0&&c.jsx(HYe,{files:M,onRemove:Y,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:H,onFocus:()=>{A(),i==null||i()},placeholder:"Ask a question...",className:"max-h-[200px] min-h-[40px] w-full resize-none overflow-y-auto border-0 bg-transparent px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),c.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[l==="dashboard"&&c.jsxs(Xr,{open:d,onOpenChange:V=>{V&&U(),f(V)},children:[c.jsx(Qr,{asChild:!0,children:c.jsx(re,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:c.jsx(Zae,{className:"h-4 w-4 text-muted-foreground"})})}),c.jsx(Jr,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:V=>V.preventDefault(),children:c.jsx(nJe,{isOpen:!0,onSelect:z,onDeselect:O,onClose:()=>{var V;f(!1),(V=b.current)==null||V.focus()},availableEntities:I||[],selectedEntities:x.selectedEntities,onTabComplete:W,onSelectAll:()=>{I&&y({selectedEntities:I})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),m(!0)}})})]}),c.jsx(bJe,{onFilesSelected:P,disabled:s,currentFileCount:M.length})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[s&&c.jsx(re,{className:"rounded-full",size:"sm",onClick:o,children:c.jsx(hle,{className:"size-3.5 bg-background"})}),!s&&c.jsx(re,{disabled:!e.trim()&&M.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:L,title:a!=="ready"?"Message will be queued":void 0,children:c.jsx(_8,{className:"size-4"})})]})]})]}),c.jsx(xA,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:m,dataSource:D||kC,dialogMode:"aiContext"})]})});yA.displayName="ChatInputWithContext";function Bee({assistantType:e,className:t}){const n=AY(e),{removeFromQueue:r}=Ym();return n.length===0?null:c.jsxs("div",{className:Z("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(Tl,{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(re,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:c.jsx(yt,{className:"h-3 w-3"})})]})},s.id))})]})}function Vee({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=AY(e),{dequeueMessage:o}=Ym();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 Hee(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),[m,p]=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}),N=C.useCallback(()=>{const _=i.current;return _?_.scrollHeight-_.scrollTop-_.clientHeight:0},[]),S=C.useCallback((_={})=>{if(!i.current)return;const{force:M=!1,instant:D=!1}=_;if(!M&&!y.current||!a&&!M)return;const R=D||r==="auto"||r==="instant"?"auto":r;v.current&&cancelAnimationFrame(v.current),b.current=!0,v.current=requestAnimationFrame(()=>{if(!M&&!y.current){b.current=!1,v.current=void 0;return}const I=i.current;if(!I){b.current=!1,v.current=void 0;return}const A=I.scrollHeight;R==="smooth"&&"scrollTo"in I?I.scrollTo({top:A,behavior:R}):I.scrollTop=A,g.current=I.scrollTop,d(!0),l(!0),y.current=!0,h(!1),p(0),b.current=!1,v.current=void 0})},[r,a]),j=C.useCallback(()=>{const _=i.current;if(!_)return;const k=g.current,M=_.scrollTop,D=M-k;if(g.current=M,D<-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 R=N()<=n;d(R),l(R),y.current=R,R&&(h(!1),p(0))},[N,n]),E=C.useCallback(()=>{p(0),h(!1)},[]);return C.useEffect(()=>{y.current=a},[a]),C.useEffect(()=>{const _=i.current;if(!_||!e||e.length===0){h(!1),p(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,M=e[e.length-1],D=(M==null?void 0:M.id)??(M==null?void 0:M.messageId)??(M==null?void 0:M.createdAt)??(M==null?void 0:M.timestamp)??e.length,R=Array.isArray(M==null?void 0:M.parts)?M.parts.reduce(($,P)=>P?typeof P=="string"?$+P.length:typeof P.text=="string"?$+P.text.length:typeof P.content=="string"?$+P.content.length:typeof P.value=="string"?$+P.value.length:$:$,0):typeof(M==null?void 0:M.content)=="string"?M.content.length:typeof(M==null?void 0:M.text)=="string"?M.text.length:0,I=e.length>k.count,A=D!==k.key,L=R>k.length,F=s&&(M==null?void 0:M.role)==="assistant"&&!I&&(A||L),H=o||F;if(w.current={key:D,count:e.length,length:R},a&&(I||A||L||H)){S({force:!1,instant:H});return}if(!a&&I){const $=e.length-k.count;$>0&&(h(!0),p(P=>P+$))}else!a&&L&&(h(!0),p($=>$>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 M=i.current;if(!M)return;const D=x.current,R=M.scrollHeight;x.current=R,!b.current&&y.current&&R>D&&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:m,scrollToBottom:S,handleScroll:j,resetNewMessageCount:E}}function Uee(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 Wee(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:jJ(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const yJe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function vJe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=C.useState(!1),[a,l]=C.useState(rD),[u,d]=C.useState(!1),[f,h]=C.useState(!1),[m,p]=C.useState(!1),g=n??m,{isLocalDev:b,isConsoleMode:x}=xm(),y=C.useRef(null);X(He=>He.dashboard.aiScopeTables),X(He=>He.isDashboardEditing);const v=X(He=>He.selectedSheetId),{setDataSource:w}=Qn(),{addFrame:N,setSelectedFrameId:S,setIsDashboardEditing:j}=Ot(),E=Wm(),{setCurrentAIContext:_,updateSelectedEntities:k,setReasoningEffort:M,setShowReasoning:D}=_S(),{clearQueue:R}=Ym(),{clearFileAttachments:I,getFileAttachments:A}=BT(),L=zT("dashboard"),F=X(He=>He.dashboard.aiContext),H=_e(He=>He.card.dataSource),{assistantProfile:$}=Oee(),P=X(He=>He.handleOpenAssistantProfile),{sendMessage:Y,isLoading:z,messages:O,setMessages:W,status:B,stop:q,errorMessage:U,clearError:V}=tJe(),G=C.useCallback(He=>{r==null||r(He),n===void 0&&p(He)},[n,r]),K=C.useCallback(()=>{G(!g)},[g,G]);C.useEffect(()=>{if(!g)return;function He(Jt){Jt.key==="Escape"&&G(!1)}return window.addEventListener("keydown",He),()=>{window.removeEventListener("keydown",He)}},[g,G]);const[ee,Q]=C.useState(""),J=He=>{Q(He.target.value)};function oe({sql:He,cardTitle:Jt,connectionId:Ke,cardType:Qe,python:Le,cardConfig:ye,dataSource:Be,customVisualPreferences:ve}){if(!v)return;const Ue={id:vr(),title:Jt||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Qe==="horizontalBar"?"y":"x"}},type:Qe,sql:He,python:Le,dataSource:Be,config:ye,connectionId:Ke,customCardPreferences:ve?{url:ve.url,componentName:ve.componentName,pluginChartType:ve.pluginChartType,settings:ve.settings,type:"component"}:void 0},at={id:vr(),cards:[Ue],activeCardId:Ue.id};j(!0),N(v,at,"end"),S(at.id)}const ue=He=>{He.preventDefault();const Jt=ee.trim();if(!Jt&&L.length===0)return;const Ke=[];Jt&&Ke.push({type:"text",text:Jt}),L.forEach(Qe=>{Qe.data&&Ke.push({type:"file",mediaType:Qe.type,filename:Qe.name,url:`data:${Qe.type};base64,${Qe.data}`})}),Y({role:"user",parts:Ke}),Q(""),I("dashboard"),ie({force:!0})};C.useEffect(()=>{var He;e&&((He=y.current)==null||He.focus())},[e]),Vee({assistantType:"dashboard",status:B,isLoading:z,sendMessage:Y});const{hasActiveTools:ae}=Wee(O),{visibleMessages:Ce,hasMoreMessages:me,totalMessageCount:se,loadMoreMessages:de,resetMessageWindow:Se}=Uee(O,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Re,isAtBottom:fe,hasNewMessages:Ie,newMessageCount:qe,scrollToBottom:ie,handleScroll:be,resetNewMessageCount:$e}=Hee(Ce,{threshold:50,behavior:"smooth",isStreaming:z});function he(He){Ae();const Jt={role:"user",parts:[{type:"text",text:He.title+" "+He.subtitle}]};Y(Jt)}function Ee(He){Ae(),Y({role:"user",parts:[{type:"text",text:He}]})}function Ve(He){Ae(),Y({role:"user",parts:[{type:"text",text:He}]}),ie({force:!0})}const We=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),Oe.success("Conversation copied")}catch(Jt){console.error("Failed to copy conversation",Jt),Oe.error("Unable to copy conversation")}},[O]);function Ae(){E.selectedEntities.length===0&&_({selectedEntities:(F==null?void 0:F.selectedEntities)||[]})}const xt=(ee==null?void 0:ee.length)===0&&(O==null?void 0:O.filter(He=>He.role==="user").length)===0;function Ne(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function mt(){return c.jsxs(gm,{children:[c.jsx(bm,{asChild:!0,children:c.jsx(kc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(lm,{className:"size-3.5"})})}),c.jsxs(rf,{align:"end",children:[c.jsx(sh,{children:"Options"}),c.jsx(Ad,{}),c.jsx(fg,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(fg,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(fg,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const _t=c.jsxs("div",{"data-role":"dashboard-assistant",className:Z("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:[Ne(),P&&c.jsx(re,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:P,children:($==null?void 0:$.name)||"Default Profile"}),c.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[x&&mt(),a&&c.jsx(re,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:We,children:"Copy Conversation"}),c.jsx(kc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:K,children:g?c.jsx(FD,{className:"size-4"}):c.jsx(M1,{className:"size-4"})}),c.jsx(kc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{W([]),R("dashboard"),V(),Se()},children:c.jsx(T1,{className:"size-4"})}),c.jsx(kc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(yt,{className:"size-4"})})]})]}),c.jsxs(Bl,{"data-role":"dashboard-assistant-scroll-area",ref:Re,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:be,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[me&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(re,{variant:"outline",size:"sm",onClick:de,className:"text-xs",children:["Load ",Math.min(5,se-Ce.length)," ","more messages (",se-Ce.length," ","hidden)"]})}),c.jsx(EJ,{showTools:a,showSystemMessage:u,messages:Ce,onAddToDashboard:oe,onQuickReply:Ve,disableQuickReplies:z}),!ae&&c.jsx(kJ,{status:B,errorMessage:U})]}),c.jsx(si,{orientation:"horizontal"})]}),e&&!fe&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(re,{onClick:()=>{ie({force:!0}),$e()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(hr,{className:"h-4 w-4"}),Ie&&qe>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:qe>9?"9+":qe})]})}),c.jsxs("div",{className:"space-y-3",children:[!$&&xt&&c.jsx(_J,{onClick:he,placeholders:yJe}),c.jsx("div",{children:xt&&$&&c.jsx(Fee,{seedQuestions:$.seedQuestions||[],handleSeedQuestionClick:Ee})}),c.jsx(Bee,{assistantType:"dashboard",className:"mb-3"}),c.jsx(yA,{ref:y,setInput:Q,stop:q,input:ee,handleInputChange:J,handleSubmit:He=>{Ae(),ue(He),ie({force:!0})},isLoading:z,status:B,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx(xA,{incomingSelectedEntities:(F==null?void 0:F.selectedEntities)||[],open:f,onOpenChange:h,dataSource:H||kC,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:_t})}),s):_t}function wJe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Ot(),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(m){const p=m.ctrlKey||m.metaKey;p&&m.key==="c"?(await f(),Oe.success("Card copied to clipboard"),m.preventDefault()):p&&m.key==="v"&&(await h(),m.preventDefault())}async function f(){try{const m=n();m&&await navigator.clipboard.writeText(JSON.stringify(m))}catch(m){console.error("Failed to copy text:",m)}}async function h(){if(!a)return null;try{const m=await navigator.clipboard.readText();try{const p=JSON.parse(m);if(p!=null&&p.id){const g=dI(p),b=g.cards.findIndex(x=>x.id===g.activeCardId);b!==-1&&(g.cards[b].title=`${g.cards[b].title} (Copy)`),r(a,g),s(g.id),Oe.success("Card pasted from clipboard")}}catch(p){console.error("Failed to parse clipboard contents: ",p)}return m}catch(m){return console.error("Failed to paste text:",m),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[r,n,s,a,l,u,t])}function SJe(e,t){switch(e.interactionMode){case"drillToDetail":CJe(e,t);break;case"drillThrough":NJe(e,t);break;case"drillToURL":jJe(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 CJe(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 NJe(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 jJe(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 kJe({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(ns,{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(ys,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(qZ,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(XZ,{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 EJe(){const e=It(w=>w.interactionStates),t=It(w=>w.setInteractionState),n=It(w=>w.clearLastInteractionEvent),r=It(w=>w.replaceCardWithInsight),s=It(w=>w.setPendingDrillThrough),o=It(w=>w.pendingDrillThrough),i=It(w=>w.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Ot(),{selectDashboard:u}=tx(),d=X(w=>w.dashboard),f=X(w=>w.filterValues),{data:h,isLoading:m}=H7((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[p,g]=C.useState({open:!1,insightId:""}),b=QZ(p.insightId,{enabled:p.open&&!!p.insightId}),x=C.useRef(new Set),y=C.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:w,filters:N,contextMode:S})=>{g({open:!0,insightId:w,filters:N,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:S})},replaceCardContent:({cardId:w,insightId:N,filters:S,contextMode:j})=>{r(w,N,S,j)},getCurrentFilters:()=>f||[],navigateWithDrill:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:w,contextMode:N,sourceDashboardId:S,sourceDashboardTitle:j,targetDashboardId:E})=>{const k={sourceCardId:ga,interactionMode:"clickFilter",filterGroups:[{filters:w}]},M={...Wo(),appliedClickFilters:[k],contextMode:N,sourceDashboardId:S,sourceDashboardTitle:j,targetDashboardId:E};t(ga,M)}}),[a,r,f,l,d,s,t]);C.useEffect(()=>{Object.entries(e).forEach(([w,N])=>{if(N!=null&&N.lastInteractionEvent){const S=N.lastInteractionEvent,j=`${w}-${S.interactionMode}-${S.sourceCardId}-${Date.now()}`;if(x.current.has(j))return;x.current.add(j);try{SJe(S,y)}catch(E){console.error("Error executing interaction event:",E)}finally{n(w),setTimeout(()=>{x.current.delete(j)},5e3)}}})},[e,n,y]),C.useEffect(()=>{if(!(!o||!h||m))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,m,u,l,i]);const v=()=>{g({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(kJe,{open:p.open,onOpenChange:v,insightId:p.insightId,filters:p.filters,filterDefinitions:p.filterDefinitions,contextMode:p.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&m&&c.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border bg-background p-6 shadow-lg",children:[c.jsx(an,{className:"h-8 w-8 animate-spin text-primary"}),c.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function _Je(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=DJe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function DJe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function MJe(e){return e?`Back to ${e}`:"Back"}function TJe(){var x,y,v,w,N;const e=It(S=>S.interactionStates[ga]),t=X(S=>S.actions.goBackFromDrill),n=X(S=>S.actions.clearDrillContext),{selectDashboard:r}=tx(),[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})},j=()=>{a(!1)};return document.addEventListener("mousemove",S),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",S),document.removeEventListener("mouseup",j)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((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||!((N=e.appliedClickFilters)!=null&&N.length))return null;const m=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(S){console.error("[DrillBack] Error during back navigation:",S)}},p=()=>{n()},g=S=>{S.target.closest("button")||(a(!0),l.current={x:S.clientX-s.x,y:S.clientY-s.y})};_Je(f);const b=MJe(d);return c.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:c.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:g,style:{cursor:i?"grabbing":"grab"},children:[c.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((S,j)=>{const E=S.field.label||S.field.name,_=String(S.value);return c.jsxs(Fe,{variant:"secondary",className:"pointer-events-none text-xs",children:[E," = ",_]},j)})})]}),c.jsx(re,{variant:"ghost",size:"sm",onClick:p,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(yt,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(re,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(l8,{className:"mr-2 h-4 w-4"}),b]})})]})})}function Yee(){var Q;const{showAssistant:e,tokenProps:t}=Ge(),{preferences:n,isConsoleMode:r}=xm(),s=((Q=n==null?void 0:n.cardDisplay)==null?void 0:Q.mode)==="print",o=C.useRef(null),i=C.useRef(null),[a,l]=C.useState(!1),u=vd(J=>J.setFullscreen),d=vd(J=>J.setPanelOpen),f=vd(J=>J.setContainer),h=MY("dashboard"),m=TY(),p=RY("dashboard"),g=h.isOpen,b=m==="dashboard",x=X(J=>J.isVisualEditing),y=X(J=>J.themeStyle),v=X(J=>{var oe;return(oe=J.dashboard)==null?void 0:oe.sheets}),w=X(J=>J.isDashboardEditing),N=X(J=>J.selectedSheetId),S=X(J=>{var oe;return(oe=J.dashboard)==null?void 0:oe.id}),j=X(J=>J.isDashboardPanelOpen),E=X(J=>J.actions.setIsDashboardPanelOpen),{getDefaultSheetId:_,setDefaultSheetId:k,clearDefaultSheetId:M}=r8(S),[D,R]=C.useState(null);W1(Pt.DASHBOARD);const{setSelectedSheetId:I,setSheetTitle:A,addSheet:L,setSheets:F}=Ot();wJe(i);const{setActiveAssistantType:H}=_S();C.useEffect(()=>{if(S){const J=_();R(J)}},[S,_]),C.useEffect(()=>{g?H("dashboard"):m==="dashboard"&&u(null)},[g,H,m,u]);function $(J){var oe,ue;J?((oe=o.current)==null||oe.resize(40),d("dashboard",!0),H("dashboard")):(d("dashboard",!1),u(null),(ue=o.current)==null||ue.resize(0),H(null))}function P(){const J={id:vr(),title:"New Sheet"};L(J),I(J.id)}function Y(J,oe){if(!S)return;D===J?(M(),R(null),Oe.success("Default sheet cleared")):(k(J),R(J),Oe.success(`"${oe}" set as default sheet`))}function z(J){J<1?(d("dashboard",!1),u(null),H(null)):(g||d("dashboard",!0),H("dashboard"))}function O(){return(y==null?void 0:y.canvasTheme)==="muted"||!(y!=null&&y.canvasTheme)?"hsl(var(--semaphor-muted))":(y==null?void 0:y.canvasTheme)==="clear"?"":y==null?void 0:y.canvasTheme}const W=(J,oe)=>{J.dataTransfer.setData("tabIndex",oe.toString())},B=J=>{J.preventDefault()},q=(J,oe)=>{const ue=J.dataTransfer.getData("tabIndex");if(ue===oe.toString())return;const ae=Array.from(v||[]),[Ce]=ae.splice(parseInt(ue),1);ae.splice(oe,0,Ce),F(ae)},U=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail;function V(){var J,oe;if(v&&v.length>1||w)return c.jsxs(vs,{role:"tab-list",className:"flex h-11 items-center justify-start gap-2 rounded-none border-b border-b-muted bg-transparent px-2.5 py-3",children:[r&&U&&c.jsx(re,{variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{E(!j)},className:"h-8 p-2",children:j?c.jsx(h8,{className:"h-4 w-4"}):c.jsx(m8,{className:"h-4 w-4"})}),v==null?void 0:v.map((ue,ae)=>{const Ce=N===ue.id,me=D===ue.id;return c.jsxs(Gt,{draggable:!0,onDragStart:se=>W(se,ae),onDragOver:B,onDrop:se=>q(se,ae),style:{borderRadius:y==null?void 0:y.controlInputRadius},onClick:()=>I(ue.id),className:"flex items-center gap-1 rounded-none border px-2 py-1",value:ue.id,children:[c.jsx(jb,{enabled:w&&Ce,text:ue.title,onSave:se=>A(ue.id,se),children:ue.title},ue.id),!w&&Ce&&c.jsx("div",{title:me?"Clear default sheet":"Set as default sheet",children:c.jsx(VD,{className:Z("ml-1 size-3 cursor-pointer transition-all",me?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:se=>{se.stopPropagation(),Y(ue.id,ue.title||"Sheet")}})}),w&&Ce&&v.length>1&&c.jsx(yt,{className:"ml-1 size-3",onClick:()=>l(!0)})]},ue.id)}),w&&c.jsx("div",{style:{borderRadius:(oe=(J=y==null?void 0:y.chart)==null?void 0:J.options)==null?void 0:oe.borderRadius},className:"flex h-7 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:P,children:c.jsx(Sr,{className:"size-3"})})]})}function G(){return c.jsx("div",{ref:i,style:{},className:"grow",children:v==null?void 0:v.map(J=>c.jsx(sr,{style:{backgroundColor:O()},className:Z("mt-0",{}),value:J.id,children:c.jsx(a8e,{sheet:J})},J.id))})}function K(){var J;return c.jsxs(Bs,{"data-role":"dashboard-tabs-container",className:Z("relative flex h-full flex-col",y==null?void 0:y.dashboardTabsContainer),onValueChange:oe=>{I(oe)},value:N||((J=v==null?void 0:v[0])==null?void 0:J.id),children:[V(),c.jsx(Bl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:G()}),c.jsx(F8e,{open:a,setOpen:l})]})}const ee=C.useCallback(J=>{f("dashboard",J)},[f]);return v?c.jsxs(c.Fragment,{children:[c.jsx(EJe,{}),c.jsx(TJe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(lQ,{className:Z("flex-1 basis-0 overflow-y-auto transition-opacity",b&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(x_,{children:K()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx(O8e,{open:g,onTabClick:$,withHandle:!0}),c.jsx(x_,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:z,defaultSize:g?40:0,ref:o,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(vJe,{open:g,setOpen:$,isFullscreen:b,onFullscreenChange:J=>u(J?"dashboard":null),fullscreenContainer:p})})})]})]}),c.jsx("div",{ref:ee,className:Z("absolute inset-0",!b&&"pointer-events-none")}),e===!0&&!s&&!g&&!x&&c.jsx("div",{className:"fixed bottom-6 right-6 z-50",children:c.jsx(re,{size:"sm",variant:"outline",className:"h-12 w-12 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>$(!0),title:"Open Assistant",children:c.jsx(BD,{className:"h-5 w-5"})})})]})]}):null}function vA({children:e}){return c.jsx(Fa,{style:{height:"100%",width:"100%"},children:c.jsx(uae,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(_n,{delayDuration:0,children:e})})})}function qee({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(v7.Provider,{value:r,children:c.jsx(wI,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function RJe(e=2e3,t=500){const n=Lae(),[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 wA({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=RJe(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 Gee(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(Ua,{FallbackComponent:eC,children:c.jsxs(jD,{dashboardProps:e,children:[c.jsx(wA,{componentType:"dashboard",componentId:e.id}),c.jsx(vA,{children:c.jsx(qee,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(VT,{...e,type:"dashboard",children:c.jsx(Yee,{})})})})})]})})}function SA(e){const{tokenProps:t,authToken:n}=Ge(),r=t==null?void 0:t.apiServiceUrl;return hn({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return Yn(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 Kee(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 Zee(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 Xee=e=>{var R;const t=(R=e==null?void 0:e.dataSource)==null?void 0:R.semanticDomainId,{data:n}=SA(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=Qn(),h=_e(I=>I.card.type),m=e==null?void 0:e.id,p=C.useCallback(I=>{if(!(e!=null&&e.config))return[];switch(I){case"groupBy":return(e.config.groupByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType,dateFormat:A.dateFormat,customFormat:A.customFormat,granularity:A.granularity}));case"metrics":return e.config.metricColumns||[];case"pivotBy":return(e.config.pivotByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType,direction:A.direction}));case"source":return[];default:return[]}},[e]),g=C.useCallback((I,A)=>{if(m)switch(I){case"groupBy":{r(m,{groupByColumns:A});break}case"metrics":{r(m,{metricColumns:A});break}case"pivotBy":{r(m,{pivotByColumns:A});break}case"sortBy":{r(m,{sortByColumns:A});break}}},[m,r]),b=C.useCallback((I,A,L)=>{if(!m)return;const H=p(I)[A];if(H)switch(I){case"groupBy":s(m,H.id,{label:L});break;case"metrics":o(m,H.id,{label:L});break;case"pivotBy":i(m,H.id,{label:L});break;case"sortBy":a(m,H.id,{label:L});break}},[m,p,s,o,i,a]),x=C.useCallback((I,A)=>{if(!m)return;const F=p("metrics")[I];F&&o(m,F.id,{aggregate:A,label:OU(F.name,A)})},[m,p,o]),y=C.useCallback((I,A,L)=>{if(!m)return;const H=p("groupBy")[I];if(!H)return;const $={dateFormat:A};A==="custom"&&L?$.customFormat=L:$.customFormat=void 0,s(m,H.id,$)},[m,p,s]),v=C.useCallback((I,A)=>{if(!m)return;const F=p("groupBy")[I];F&&s(m,F.id,{granularity:A})},[m,p,s]),w=C.useCallback((I,A)=>{if(!m)return;const F=p("metrics")[I];F&&o(m,F.id,{aliasTemplate:A})},[m,p,o]),N=C.useCallback((I,A)=>{if(console.log("handleValueAliasesChange",I,A),!m)return;console.log("handleValueAliasesChange",I,A);const F=p("metrics")[I];F&&(console.log("handleValueAliasesChange",A),o(m,F.id,{valueAliases:A}))},[m,p,o]),S=C.useCallback(I=>{if(!m)return;if(p("metrics").length===0){Oe.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(m,{comparisonType:I})},[m,r,p]),j=C.useCallback(I=>{m&&r(m,{showTrendline:I})},[m,r]),E=C.useCallback(I=>{m&&r(m,{trendlineWindow:I})},[m,r]),_=C.useCallback(I=>{m&&r(m,{trendlineGranularity:I})},[m,r]),k=C.useCallback(I=>{m&&r(m,{targetValue:I})},[m,r]),M=C.useCallback(I=>{var Y;if(!m)return;const A=[...p("groupBy"),...p("pivotBy"),...p("metrics"),...p("sortBy")],L=rNe(I,A,{joinPlan:(Y=e==null?void 0:e.config)==null?void 0:Y.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!L.isValid){L.showError&&IU();return}const F=iNe(I,A,h);if(!F){Oe.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const H=Kee(I,F,h);if(!H.isValid){Oe.error("Invalid Field Type",{description:H.reason,position:"top-center",duration:3e3});return}const $=p(F);if(AU(I,$))return;const P=FU(I,F,$);if(P){const z=[...$,P];g(F,z),F==="metrics"&&Zee(h,e==null?void 0:e.config,r,m,z)}},[m,e==null?void 0:e.config,p,g,t,n,h,r]),D=C.useCallback((I,A)=>{if(!m)return;const F=p(I)[A];if(F){if(I!=="sortBy"){const H=p("sortBy"),$=H.filter(P=>!(P.name===F.name&&P.qualifiedEntityName===F.qualifiedEntityName));$.length!==H.length&&r(m,{sortByColumns:$})}switch(I){case"groupBy":l(m,F.id);break;case"metrics":u(m,F.id);break;case"pivotBy":d(m,F.id);break;case"sortBy":f(m,F.id);break}}},[m,p,l,u,d,f,r]);return{getFieldsForContainer:p,setFieldsForContainer:g,updateLabel:b,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:v,handleAliasTemplateChange:w,handleValueAliasesChange:N,removeField:D,handleFieldClick:M,handleKpiComparisonTypeChange:S,handleKpiShowTrendlineChange:j,handleKpiTrendlineWindowChange:E,handleKpiTrendlineGranularityChange:_,handleKpiTargetValueChange:k,cardType:h}};function hy(e,t){var Ee,Ve,We,Ae,xt;const{tokenProps:n}=Ge(),r=zs(),s=Ge().authToken||e,o=_e(Ne=>Ne.selectedConnectionId),i=_e(Ne=>Ne.card),{queryKey:a}=Epe(i),l=_e(Ne=>Ne.selectedDatamodelId),u=_e(Ne=>Ne.isDevMode),d=_e(Ne=>Ne.selectedDatabaseName),f=_e(Ne=>Ne.selectedSchemaName),h=_e(Ne=>Ne.selectedTableName),m=_e(Ne=>Ne.actions.setSelectedConnectionId),p=_e(Ne=>Ne.actions.setSelectedDatamodelId),g=_e(Ne=>Ne.actions.setSelectedDatabaseName),b=_e(Ne=>Ne.actions.setSelectedSchemaName),x=_e(Ne=>Ne.actions.setSelectedTableName);_e(Ne=>Ne.actions.setCardSql);const{setQueryConfig:y}=Qn();function v(Ne){var _t;return o&&Ne==="API"?!1:o&&Ne==="S3"?!0:!(!o||!d||d==="NA"||((_t=_==null?void 0:_.capabilities)==null?void 0:_t.path.includes("schema"))&&!f)}function w(Ne){return o&&Ne?!(Ne==="API"||Ne==="S3"):!1}const{refetchConnections:N,connectionsData:S,isConnectionsLoading:j,isConnectionsError:E,selectedConnection:_}=$a(e),{refetch:k,data:M,isLoading:D,isError:R}=hn({queryKey:["models",o],queryFn:()=>Yn(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),I=_==null?void 0:_.type,A=(_==null?void 0:_.type)==="API"||(_==null?void 0:_.type)==="S3",{data:L,isLoading:F,isFetching:H,isError:$,refetch:P}=hn({queryKey:["databases",o],queryFn:()=>Yn(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:w(I)}),{data:Y,isLoading:z,isFetching:O,isError:W,refetch:B}=hn({queryKey:["schemas",o,d],queryFn:()=>Yn(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&!A&&d!=="NA"}),{data:q,isLoading:U,isFetching:V,isError:G,refetch:K}=hn({queryKey:["tables",o,d,f],queryFn:()=>Yn(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(I)}),{columns:ee,isColumnsLoading:Q,isColumnsFetching:J,isColumnsError:oe,refetchColumns:ue}=$U(e);C.useEffect(()=>{(I==="S3"||I==="API")&&(g(""),b(""),p(""),I==="API"&&x("api"))},[I,x,g,b,p]);const ae=(_==null?void 0:_.type)==="API"?(Ee=_==null?void 0:_.type)==null?void 0:Ee.toLowerCase():h||"",Ce=A?"":f||"";function me(Ne){x(Ne),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function se(Ne){b(Ne),x("")}function de(Ne){g(Ne==="none"?"":Ne),b(""),x(""),Ne!=="none"&&Ne!==""&&p("")}function Se(Ne){m(Ne)}function Re(Ne){p(Ne==="none"?"":Ne),Ne!=="none"&&Ne!==""&&g("")}L&&((Ve=L==null?void 0:L.databases)==null?void 0:Ve.length)>0,Y&&((We=Y==null?void 0:Y.schemas)==null?void 0:We.length)>0;const fe=S==null?void 0:S.connections.map(Ne=>({id:Ne.id,name:Ne.name,type:Ne.type})),Ie=(Ae=M==null?void 0:M.datamodels)==null?void 0:Ae.map(Ne=>({id:Ne.id,name:Ne.name})),qe=L==null?void 0:L.databases.map(Ne=>({id:Ne.database_name,name:Ne.database_name})),ie=Y==null?void 0:Y.schemas.map(Ne=>({id:Ne.schema_name,name:Ne.schema_name})),be=q==null?void 0:q.tables.map(Ne=>({id:Ne.table_name,name:Ne.table_name})),$e=(xt=M==null?void 0:M.datamodels.find(Ne=>Ne.id===l))==null?void 0:xt.name,he=kv({schemaName:Ce,tableName:ae,modelName:$e,connectionType:I,databaseName:d||""});return{connectionItems:fe,selectedConnectionId:o,selectedConnection:_,isConnectionsLoading:j,isConnectionsError:E,modelItems:Ie,selectedDatamodelId:l,selectedDatamodelName:$e,isModelsLoading:D,isModelsError:R,selectedDatabaseName:d,databaseItems:qe,isDatabasesLoadingOrFetching:F||H,isDatabaseError:$,schemaItems:ie,selectedSchemaName:f,isSchemaLoadingOrFetching:z||O,isSchemaError:W,tableItems:be,selectedTableName:h,isTableLoadingOrFetching:U||V,isTableError:G,columns:ee,isColumnsLoadingOrFetching:Q||J,isColumnsError:oe,isNonDbConnection:A,connectionType:I,tableName:ae,formattedTableName:he,schemaName:Ce,refetchConnections:N,refetchModels:k,refetchDatabases:P,refetchSchemas:B,refetchTables:K,refetchColumns:ue,handleConnectionChange:Se,handleDatamodelChange:Re,handleDatabaseChange:de,handleSchemaChange:se,handleTableChange:me}}function W0(e){return`${e}-${vr()}`}function S6(e,t){const n=ni(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 IJe(e,t){const n=ni(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 CA(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 Qee(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Jee(){const e=_e(S=>S.sqlGen),t=_e(S=>S.isDevMode),n=_e(S=>S.card.dataSource),r=_e(S=>{var j,E;return(E=(j=S.card)==null?void 0:j.queryConfig)==null?void 0:E.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=CA(n),a=Qee(n),l=_e(S=>S.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:m,setIsShowingVisual:p}=Qn(),{connectionType:g,modelItems:b,selectedDatamodelName:x}=hy(),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 j=y(S);if(t&&a&&s){const _=cD(j,e);m(_);const k=(E=b==null?void 0:b.find(D=>D.id===l))==null?void 0:E.name,M=lD(_,Ci(o||""),Ci(s),k||"",g,i||"");M&&(f(M),h(!0))}else if(!t){if(Qb(j.data_type))if(r&&r.length>0){const _={...j,role:"groupby",id:W0(j.column_name),name:j.column_name,type:j.data_type};d(_)}else{const _={...j,role:"metric",id:W0(j.column_name),name:j.column_name,label:S6(j.column_name,"COUNT"),type:j.data_type,aggregate:"COUNT"};u(_)}if(Ii(j.data_type)){const _={...j,role:"groupby",id:W0(j.column_name),name:j.column_name,type:j.data_type,label:IJe(j.column_name,"month"),granularity:"month"};d(_)}if(Ri(j.data_type)){const _={...j,role:"metric",id:W0(j.column_name),name:j.column_name,label:S6(j.column_name,"SUM"),type:j.data_type,aggregate:"SUM"};u(_)}}},handleShowSample:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const S=kv({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});p(!1);const j=g==="MSSQL"?`SELECT top 10 * FROM ${S}`:`SELECT * FROM ${S} LIMIT 10`;f(j),h(!0)},handleShowCount:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const S=kv({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});f(`SELECT COUNT(*) as count FROM ${S}`),h(!0)},isNumberField:S=>Ri(S.dataType)}}function AJe({columnName:e,database:t,schemaName:n,tableName:r,connectionType:s,datamodelId:o,modelName:i,field:a}){const l=Ci(e),u=Ci(t||""),d=Ci(n||""),f=Ci(r);let h=x1({schemaName:d,tableName:f,connectionType:s,databaseName:u}),m=`${h}.${l}`;return o&&o!=="none"&&i&&(m=`${Vg}.${i}.${l}`,h=`${Vg}.${i}`),a!=null&&a.qualifiedFieldName&&(m=a.qualifiedFieldName,h=a.qualifiedFieldName.split(".").slice(0,-1).join(".")),{qualifiedColumnName:m,qualifiedTableName:h,formattedColumnName:l,formattedTableName:f,formattedDatabase:u,formattedSchemaName:d}}function ete(){const e=_e(p=>p.selectedConnectionId),t=_e(p=>p.selectedDatamodelId),n=_e(p=>p.selectedDatabaseName),r=_e(p=>p.selectedSchemaName),s=_e(p=>p.selectedTableName),o=X(p=>p.dashboard.filters)||[],i=X(p=>p.selectedSheetId),a=X(p=>p.actions.addFilter),l=X(p=>p.actions.removeFilter),{removeFilterValues:u}=Ot(),{modelItems:d,tableName:f,connectionType:h}=hy();function m(p,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:N,formattedDatabase:S}=AJe({columnName:p.column_name,database:n,schemaName:r,tableName:f,connectionType:h,datamodelId:t,modelName:x,field:b});let j;if(g==="sheet"&&i?j=i_e(o,y,N,n||"",S,i):j=o==null?void 0:o.find(_=>_.column===y&&_.table===N&&(_.database===S||_.database===n)),j)u(j.id),l(j.id);else{const _=vr(),k=g==="sheet"&&i?[i]:void 0;return f==="api"&&e?(a({location:g,id:_,column:y,title:p.label||p.column_name,dataType:p.data_type,table:"api",database:"",connectionId:e,operation:"in",applyToSheetIds:k,sql:KE(p.data_type,v,w)}),_):(a({id:_,location:g,column:y,title:p.label||p.column_name,dataType:p.data_type,table:s||"",database:n||"",connectionId:e||"",operation:"in",applyToSheetIds:k,sql:KE(p.data_type,v,(b==null?void 0:b.qualifiedFieldName)||w)}),_)}}return{assignFilter:m}}function PJe({column:e}){const[t,n]=C.useState(!1),r=_e(x=>x.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=CA(r),a=_e(x=>x.selectedDatamodelId),l=_e(x=>x.sqlGen),{modelItems:u,connectionType:d}=hy(),f=_e(x=>x.actions.setSqlGen),h=_e(x=>x.actions.setCardSql),m=_e(x=>x.actions.setRunSql),p=Qee(r);function g(x,y){var S;if(!p||!s){console.warn("Cannot generate SQL: missing table metadata");return}const v=cD(x,l,y),w=(S=u==null?void 0:u.find(j=>j.id===a))==null?void 0:S.name;f(v);const N=lD(v,Ci(o||""),Ci(s),w||"",d,i||"");N&&(h(N),m(!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 p?c.jsxs(km,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(Em,{asChild:!0,children:c.jsx(lm,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(of,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]}):null}function OJe({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 FJe({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s}){const o=_e(q=>q.isDevMode),i=t==="filter"||t==="inline-filter",a=o||i||(n==null?void 0:n.state)==="unreachable"&&!i,l=X(q=>q.dashboard.filters),u=X(q=>q.selectedSheetId),d=X(q=>q.actions.removeFilter),{removeFilterValues:f}=Ot(),{assignFilter:h}=ete(),m=t==="filter"?zl(l,u):l,p=t==="filter"?m==null?void 0:m.find(q=>{var U;return q.title===e.name||((U=q.column)==null?void 0:U.includes(e.name))}):void 0,g=!!p,b=t==="inline-filter"&&(s==null?void 0:s.some(q=>q.column===e.qualifiedFieldName||q.column===e.name)),x=g||b,y=p&&i?l==null?void 0:l.find(q=>q.id===p.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:p?{id:p.id,title:p.title,column:p.column,applyToSheetIds:p.applyToSheetIds,excludeSheetIds:p.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,N]=C.useState(!1),[S,j]=C.useState(null),{attributes:E,listeners:_,setNodeRef:k,transform:M,transition:D,isDragging:R}=oy({id:e.id,disabled:a}),[I,A]=C.useState(!1),L=_e(q=>q.card),{handleFieldClick:F}=Xee(L),{handleDevModeFieldClick:H,isNumberField:$}=Jee(),P=()=>{y&&(console.log("[SourceField] Removing multi-sheet filter:",y.id),f(y.id),d(y.id)),j(null),N(!1)},Y=()=>{if(t==="inline-filter"&&r){r(e);return}if(t==="filter"){const q={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description,qualifiedFieldName:e.qualifiedFieldName};x&&v?(j({column:q,field:e}),N(!0)):h(q,"sheet",e)}else o?H(e):F(e)},z={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},O={transform:ii.Transform.toString(M),transition:D},B=(()=>{if(!n||i)return{};const U={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",...U},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...U},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...U}}[n.state]||U})();return c.jsxs("div",{ref:k,style:O,...a?{}:E,...a?{}:_,className:Z("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",R&&"scale-95 opacity-50",!R&&"border",B.borderColor||"border-transparent",B.bgColor||"",B.hoverBorderColor,B.hoverBgColor||"hover:bg-muted",B.opacity,B.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:Y,children:[Eb(e.dataType),c.jsx(_n,{children:c.jsxs(Zt,{children:[c.jsx(Xt,{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 ${I?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),c.jsx(en,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:c.jsx(OJe,{field:e,fieldState:n})})]})}),o&&!i&&$(e)&&c.jsx("div",{onClick:q=>q.stopPropagation(),children:c.jsx(PJe,{column:z})})]}),I&&c.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:c.jsx(Do,{className:"",children:c.jsxs(Oi,{className:"space-y-2 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(M8,{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(xle,{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(px,{open:w,onOpenChange:N,children:c.jsxs(ym,{children:[c.jsxs(vm,{children:[c.jsx(Sm,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(Cm,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(wm,{children:[c.jsx(jm,{children:"Cancel"}),c.jsx(Nm,{onClick:P,children:"Remove Filter"})]})]})})]})}const $Je="SEMAPHOR_CALCULATED_FIELD",LJe=["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 tte(e){return!!e.expression}function zJe(e){return!!e.expression}function BJe(e){return!!e.expression}var nte=(e=>(e.SUBTOTAL="__SUBTOTAL__",e.TOTAL="__TOTAL__",e.ALL="__ALL__",e))(nte||{}),Ki="Accordion",VJe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[NA,HJe,UJe]=sx(Ki),[MC]=kr(Ki,[UJe,bW]),jA=bW(),rte=C.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(NA.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(GJe,{...o,ref:t}):c.jsx(qJe,{...s,ref:t})})});rte.displayName=Ki;var[ste,WJe]=MC(Ki),[ote,YJe]=MC(Ki,{collapsible:!1}),qJe=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:Ki});return c.jsx(ste,{scope:e.__scopeAccordion,value:C.useMemo(()=>a?[a]:[],[a]),onItemOpen:l,onItemClose:C.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(ote,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(ite,{...i,ref:t})})})}),GJe=C.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i,a]=Br({prop:n,defaultProp:r??[],onChange:s,caller:Ki}),l=C.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=C.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return c.jsx(ste,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(ote,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(ite,{...o,ref:t})})})}),[KJe,TC]=MC(Ki),ite=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=HJe(n),f=eu(s)==="ltr",h=ke(e.onKeyDown,m=>{var E;if(!VJe.includes(m.key))return;const p=m.target,g=u().filter(_=>{var k;return!((k=_.ref.current)!=null&&k.disabled)}),b=g.findIndex(_=>_.ref.current===p),x=g.length;if(b===-1)return;m.preventDefault();let y=b;const v=0,w=x-1,N=()=>{y=b+1,y>w&&(y=v)},S=()=>{y=b-1,y<v&&(y=w)};switch(m.key){case"Home":y=v;break;case"End":y=w;break;case"ArrowRight":o==="horizontal"&&(f?N():S());break;case"ArrowDown":o==="vertical"&&N();break;case"ArrowLeft":o==="horizontal"&&(f?S():N());break;case"ArrowUp":o==="vertical"&&S();break}const j=y%x;(E=g[j].ref.current)==null||E.focus()});return c.jsx(KJe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(NA.Slot,{scope:n,children:c.jsx(ze.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),u1="AccordionItem",[ZJe,kA]=MC(u1),ate=C.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=TC(u1,n),i=WJe(u1,n),a=jA(n),l=ar(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(ZJe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(vW,{"data-orientation":o.orientation,"data-state":hte(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});ate.displayName=u1;var lte="AccordionHeader",cte=C.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=TC(Ki,n),o=kA(lte,n);return c.jsx(ze.h3,{"data-orientation":s.orientation,"data-state":hte(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});cte.displayName=lte;var H_="AccordionTrigger",ute=C.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=TC(Ki,n),o=kA(H_,n),i=YJe(H_,n),a=jA(n);return c.jsx(NA.ItemSlot,{scope:n,children:c.jsx(lje,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});ute.displayName=H_;var dte="AccordionContent",fte=C.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=TC(Ki,n),o=kA(dte,n),i=jA(n);return c.jsx(cje,{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}})});fte.displayName=dte;function hte(e){return e?"open":"closed"}var XJe=rte,QJe=ate,JJe=cte,mte=ute,pte=fte;const gte=XJe,EA=T.forwardRef(({className:e,...t},n)=>c.jsx(QJe,{ref:n,className:Z("border-b",e),...t}));EA.displayName="AccordionItem";const _A=T.forwardRef(({className:e,children:t,...n},r)=>c.jsx(JJe,{className:"flex",children:c.jsxs(mte,{ref:r,className:Z("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(hr,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));_A.displayName=mte.displayName;const DA=T.forwardRef(({className:e,children:t,...n},r)=>c.jsx(pte,{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:Z("pb-4 pt-0",e),children:t})}));DA.displayName=pte.displayName;function bte({context:e="editor",onFieldSelect:t,inlineFilters:n}={}){var A,L,F,H;const[r,s]=C.useState(""),[o,i]=C.useState("all");_e($=>$.isDevMode);const a=_e($=>$.card.dataSource),l=_e($=>$.card.config),u=_e($=>$.card),{autoJoinMetadata:d}=_a(u),{columns:f=[],columnGroups:h=[],isLoading:m,error:p}=pT(),g=(a==null?void 0:a.mode)==="semanticDomain"?a.semanticDomainId:void 0,{data:b}=SA(g),x=[...(l==null?void 0:l.groupByColumns)||[],...(l==null?void 0:l.metricColumns)||[]];(L=(A=l==null?void 0:l.joinPlan)==null?void 0:A.baseEntity)==null||L.name,(H=(F=d==null?void 0:d.resolvedJoinPlan)==null?void 0:F.baseEntity)==null||H.name,Jee();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"&&tte($)||$.role==="groupby"&&$.expression)return"calculated";if($.dataType==="number"||$.dataType==="integer"||$.dataType==="float"||$.dataType==="decimal"||$.dataType==="currency")return"metrics";const P=Tr($.dataType);return["date","string","boolean"].includes(P)?"dimensions":P==="number"?"metrics":"dimensions"},N=(o==="all"?y:y.filter($=>v($)===o)).reduce(($,P)=>{const Y=P.qualifiedEntityName||"Other Fields";return $[Y]||($[Y]={label:xD(P.entityName),fields:[]}),$[Y].fields.push(P),$},{}),j=Object.keys(N),E=y.filter($=>v($)==="dimensions").length,_=y.filter($=>v($)==="metrics").length,k=y.filter($=>v($)==="calculated").length,M=y.length>0&&e!=="inline-filter",D=e==="inline-filter"?"w-full":"w-[290px]";if(m)return c.jsx("div",{className:Z("flex h-full flex-col items-center justify-center py-8",D),children:c.jsx(Gc,{size:"md",color:"muted","aria-label":"Loading data"})});if(p)return c.jsxs("div",{className:Z("flex h-full flex-col items-center justify-center py-8",D),children:[c.jsx(Cl,{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:p.message||"Failed to load column data"})]});if(!a||!a.selectedEntities||a.selectedEntities.length===0)return c.jsxs("div",{className:Z("flex flex-col items-center justify-center py-8 text-center",D),children:[c.jsx(Cl,{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 R=e==="inline-filter"?"px-3 pb-3":"px-6 pb-6",I=e==="inline-filter"?"overflow-hidden":"";return c.jsxs("div",{className:Z("mt-2 flex h-full w-full grow flex-col gap-2",R,I),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(Ui,{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(yt,{className:"size-3.5"})})]}),M&&c.jsx(Bs,{defaultValue:"all",value:o,onValueChange:$=>i($),className:"mb-4",children:c.jsxs(vs,{className:"grid h-9 w-full grid-cols-4",children:[c.jsxs(Gt,{value:"all",className:"text-xs",children:["All",c.jsx("span",{className:"ml-2 text-xs font-semibold",children:y.length})]}),c.jsxs(Gt,{value:"dimensions",className:"text-xs",children:[c.jsx(D1,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:E})]}),c.jsxs(Gt,{value:"metrics",className:"text-xs",children:[c.jsx(im,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:_})]}),c.jsxs(Gt,{value:"calculated",className:"text-xs",children:[c.jsx(kD,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:k})]})]})})]}),c.jsxs(Bl,{className:"min-h-0 overflow-auto",children:[c.jsx(gte,{type:"multiple",defaultValue:j,className:"space-y-2",children:Object.entries(N).map(([$,P])=>{const Y=h.find(z=>z.entityName===$)||{entityName:$,label:P.label};return c.jsxs(EA,{value:$,className:"border-none",children:[c.jsx(_A,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{title:Y.label||Y.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:Y.label||Y.entityName}),c.jsx(Fe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:P.fields.length})]})}),c.jsx(DA,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:P.fields.map(z=>{const O=gT(z,{joinabilityMap:(b==null?void 0:b.joinabilityMap)||null,selectedFields:x,cardConfig:l,autoJoinMetadata:d});return c.jsx(FJe,{field:z,context:e,fieldState:O,onFieldSelect:t,inlineFilters:e==="inline-filter"?n:void 0},z.id)})})})]},$)})}),Object.keys(N).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(N).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(si,{orientation:"horizontal"}),c.jsx(si,{orientation:"vertical"})]})]})}function xte({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(bte,{context:e})," "]})}function yte(){const e=_e(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=Qn();C.useEffect(()=>{var m;if(!e)return;const{tableName:i,schemaName:a,databaseName:l,connectionId:u}=CA(e),d=(m=e.selectedEntities)==null?void 0:m[0],h=(d==null?void 0:d.type)==="model"&&"id"in d?d.id:"";t(u||""),n(l||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function eet(){yte();const e=X(l=>l.selectedSheetId),t=X(l=>l.selectedFrameId),n=X(l=>l.dashboard),r=X(l=>l.actions.getSelectedFrame),{setSelectedFrameId:s}=Ot(),{setCard:o}=Qn(),i=_e(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(m=>m.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),l=h)}if(l){const f=l.cards.find(h=>h.id===l.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function tet(){const e=X(o=>o.dashboard.filterLayout),{setFilterLayout:t}=Ot(),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(Xr,{children:[c.jsx(Qr,{asChild:!0,children:c.jsx(re,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0","aria-label":"Filter display settings",children:c.jsx(Nl,{className:"h-4 w-4"})})}),c.jsx(Jr,{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(jo,{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(In,{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(In,{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(Qt,{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(Qt,{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 net(){const e=X(n=>n.actions.setShowFilters),{hasEntities:t}=eet();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(tet,{}),c.jsx(re,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:c.jsx(eX,{})})]})]}),!t&&c.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[c.jsx(Cl,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),c.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&c.jsx("div",{className:"flex grow overflow-y-auto",children:c.jsx(ry,{collisionDetection:ey,children:c.jsx(sy,{items:[],strategy:RI,children:c.jsx(xte,{context:"filter"})})})})]})}function ret(){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:Z("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(jI,{filter:r}),c.jsx(rp,{filter:r})]},r.id))}):null}function set(){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:Z("",{"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(ret,{}),c.jsx(Yee,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:c.jsx(net,{})})]})}const oet=C.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-Bp5qe0eo.js"))),iet=C.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-C8JlV4-w.js"))),aet=C.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-Dx_6Ejec.js"))),cet=C.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-C-ijbO2j.js")).then(e=>({default:e.ResourceManagementPanel})));function uet({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(Ua,{FallbackComponent:eC,children:c.jsxs(jD,{dashboardProps:n,children:[c.jsx(hhe,{}),c.jsx(wA,{componentType:"surfboard",componentId:n.id}),c.jsx(vA,{children:c.jsxs(qee,{preferences:a,children:[o&&c.jsx(C.Suspense,{fallback:null,children:c.jsx(aet,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[e&&c.jsx(C.Suspense,{fallback:null,children:c.jsx(oet,{})}),c.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&c.jsx(C.Suspense,{fallback:null,children:c.jsx(cet,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),c.jsx("div",{className:"flex min-w-0 flex-1",children:c.jsxs(VT,{...n,type:"dashboard",children:[s&&c.jsx(C.Suspense,{fallback:null,children:c.jsx(iet,{})}),c.jsx(set,{})]})})]})]})]})})]})})}var det=Object.defineProperty,fet=(e,t,n)=>t in e?det(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Y0=(e,t,n)=>fet(e,typeof t!="symbol"?t+"":t,n);const het={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},met={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}},pet={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function get(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function vte(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const bet={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=vte(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},xet={stringify:e=>`${e}`,parse:e=>parseFloat(e)},yet={stringify:e=>e,parse:e=>e},I2={string:yet,number:xet,boolean:het,function:met,method:bet,json:pet},$p=Symbol.for("r2wc.render"),q0=Symbol.for("r2wc.connected"),Tu=Symbol.for("r2wc.context"),fo=Symbol.for("r2wc.props");function vet(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),l={},u={},d={},f={};for(const m of i){l[m]=Array.isArray(t.props)?"string":t.props[m];const p=get(m);d[m]=p,f[p]=m}for(const m of a)u[m]=Array.isArray(t.events)?{}:t.events[m];class h extends HTMLElement{constructor(){super(),Y0(this,o,!0),Y0(this,s),Y0(this,r,{}),Y0(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[fo].container=this.container;for(const p of i){const g=d[p],b=this.getAttribute(g),x=l[p],y=x?I2[x]:null;if(x==="method"){const v=vte(g);Object.defineProperty(this[fo].container,v,{enumerable:!0,configurable:!0,get(){return this[fo][v]},set(w){this[fo][v]=w,this[$p]()}}),this[fo][p]=y.parse(b,g,this)}y!=null&&y.parse&&b&&(this[fo][p]=y.parse(b,g,this))}for(const p of a)this[fo][p]=g=>{const b=p.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[p]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[q0]=!0,this[$p]()}disconnectedCallback(){this[q0]=!1,this[Tu]&&n.unmount(this[Tu]),delete this[Tu]}attributeChangedCallback(p,g,b){const x=f[p],y=l[x],v=y?I2[y]:null;x in l&&v!=null&&v.parse&&b&&(this[fo][x]=v.parse(b,p,this),this[$p]())}[(o=q0,s=Tu,r=fo,$p)](){this[q0]&&(this[Tu]?n.update(this[Tu],this[fo]):this[Tu]=n.mount(this.container,e,this[fo]))}}for(const m of i){const p=d[m],g=l[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[fo][m]},set(b){this[fo][m]=b;const x=g?I2[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,p,this);this.getAttribute(p)!==y&&this.setAttribute(p,y)}else this[$p]()}})}return h}function wet(e,t,n){const r=Bne.createRoot(e),s=C.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function Cet({root:e,ReactComponent:t},n){const r=C.createElement(t,n);e.render(r)}function Net({root:e}){e.unmount()}function jet(e,t={}){return vet(e,t,{mount:wet,update:Cet,unmount:Net})}const ket={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"},Eet=jet(Gee,{props:ket});function C6(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 _et(e){if(Array.isArray(e))return e}function Det(e,t,n){return(t=Oet(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Met(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 Tet(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1098
+ `)}})}});var TQe=NXe(()=>See(ai([Kn({type:Tt("text-start"),id:st(),providerMetadata:ur.optional()}),Kn({type:Tt("text-delta"),id:st(),delta:st(),providerMetadata:ur.optional()}),Kn({type:Tt("text-end"),id:st(),providerMetadata:ur.optional()}),Kn({type:Tt("error"),errorText:st()}),Kn({type:Tt("tool-input-start"),toolCallId:st(),toolName:st(),providerExecuted:Ys().optional(),dynamic:Ys().optional()}),Kn({type:Tt("tool-input-delta"),toolCallId:st(),inputTextDelta:st()}),Kn({type:Tt("tool-input-available"),toolCallId:st(),toolName:st(),input:sa(),providerExecuted:Ys().optional(),providerMetadata:ur.optional(),dynamic:Ys().optional()}),Kn({type:Tt("tool-input-error"),toolCallId:st(),toolName:st(),input:sa(),providerExecuted:Ys().optional(),providerMetadata:ur.optional(),dynamic:Ys().optional(),errorText:st()}),Kn({type:Tt("tool-output-available"),toolCallId:st(),output:sa(),providerExecuted:Ys().optional(),dynamic:Ys().optional(),preliminary:Ys().optional()}),Kn({type:Tt("tool-output-error"),toolCallId:st(),errorText:st(),providerExecuted:Ys().optional(),dynamic:Ys().optional()}),Kn({type:Tt("reasoning-start"),id:st(),providerMetadata:ur.optional()}),Kn({type:Tt("reasoning-delta"),id:st(),delta:st(),providerMetadata:ur.optional()}),Kn({type:Tt("reasoning-end"),id:st(),providerMetadata:ur.optional()}),Kn({type:Tt("source-url"),sourceId:st(),url:st(),title:st().optional(),providerMetadata:ur.optional()}),Kn({type:Tt("source-document"),sourceId:st(),mediaType:st(),title:st(),filename:st().optional(),providerMetadata:ur.optional()}),Kn({type:Tt("file"),url:st(),mediaType:st(),providerMetadata:ur.optional()}),Kn({type:bee(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:st().optional(),data:sa(),transient:Ys().optional()}),Kn({type:Tt("start-step")}),Kn({type:Tt("finish-step")}),Kn({type:Tt("start"),messageId:st().optional(),messageMetadata:sa().optional()}),Kn({type:Tt("finish"),finishReason:mee(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:sa().optional()}),Kn({type:Tt("abort")}),Kn({type:Tt("message-metadata"),messageMetadata:sa()})])));function RQe(e){return e.type.startsWith("data-")}function Mee(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]=Mee(o,s):n[r]=s}return n}function IQe(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 Tee(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await a1({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await a1({text:IQe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function yv(e){return e.type.startsWith("tool-")}function AQe(e){return e.type==="dynamic-tool"}function L_(e){return yv(e)||AQe(e)}function y6(e){return e.type.split("-").slice(1).join("-")}function PQe({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 OQe({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await r(async({state:u,write:d})=>{var f,h,m,p;function g(w){const S=u.message.parts.filter(yv).find(j=>j.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(j=>j.type==="dynamic-tool").find(j=>j.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 N;const S=u.message.parts.find(_=>yv(_)&&_.toolCallId===w.toolCallId),j=w,E=S;S!=null?(S.state=w.state,E.input=j.input,E.output=j.output,E.errorText=j.errorText,E.rawInput=j.rawInput,E.preliminary=j.preliminary,E.providerExecuted=(N=j.providerExecuted)!=null?N:S.providerExecuted,j.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.state,input:j.input,output:j.output,rawInput:j.rawInput,errorText:j.errorText,providerExecuted:j.providerExecuted,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}function y(w){var N,S;const j=u.message.parts.find(k=>k.type==="dynamic-tool"&&k.toolCallId===w.toolCallId),E=w,_=j;j!=null?(j.state=w.state,_.toolName=w.toolName,_.input=E.input,_.output=E.output,_.errorText=E.errorText,_.rawInput=(N=E.rawInput)!=null?N:_.rawInput,_.preliminary=E.preliminary,_.providerExecuted=(S=E.providerExecuted)!=null?S:j.providerExecuted,E.providerMetadata!=null&&j.state==="input-available"&&(j.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 N=u.message.metadata!=null?Mee(u.message.metadata,w):w;t!=null&&await m6({value:N,schema:t}),u.message.metadata=N}}switch(a.type){case"text-start":{const w={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=w,u.message.parts.push(w),d();break}case"text-delta":{const w=u.activeTextParts[a.id];w.text+=a.delta,w.providerMetadata=(f=a.providerMetadata)!=null?f:w.providerMetadata,d();break}case"text-end":{const w=u.activeTextParts[a.id];w.state="done",w.providerMetadata=(h=a.providerMetadata)!=null?h:w.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const w={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=w,u.message.parts.push(w),d();break}case"reasoning-delta":{const w=u.activeReasoningParts[a.id];w.text+=a.delta,w.providerMetadata=(m=a.providerMetadata)!=null?m:w.providerMetadata,d();break}case"reasoning-end":{const w=u.activeReasoningParts[a.id];w.providerMetadata=(p=a.providerMetadata)!=null?p:w.providerMetadata,w.state="done",delete u.activeReasoningParts[a.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),d();break}case"tool-input-start":{const w=u.message.parts.filter(yv);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:N}=await Tee(w.text);w.dynamic?y({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:N}):x({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:N}),d();break}case"tool-input-available":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d();break}case"tool-output-available":{if(a.dynamic){const 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:y6(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:y6(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(RQe(a)){(n==null?void 0:n[a.type])!=null&&await m6({value:a.data,schema:n[a.type]});const w=a;if(w.transient){i==null||i(w);break}const N=w.id!=null?u.message.parts.find(S=>w.type===S.type&&w.id===S.id):void 0;N!=null?N.data=w.data:u.message.parts.push(w),i==null||i(w),d()}}l.enqueue(a)})}}))}async function FQe({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()}}fy({prefix:"aitxt",size:24});fy({prefix:"aiobj",size:24});var $Qe=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()})}};fy({prefix:"aiobj",size:24});var LQe={};wQe(LQe,{object:()=>BQe,text:()=>zQe});var zQe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),BQe=({schema:e})=>{const t=yQe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await Tee(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 a1({text:n});if(!s.success)throw new b6({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 pA({value:s.value,schema:t});if(!o.success)throw new b6({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 VQe(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 HQe=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 If(this.body),l=await If(this.headers),u=await If(this.credentials),d={...$u(l),...$u(t.headers)},f=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:d,credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),h=(r=f==null?void 0:f.api)!=null?r:this.api,m=(f==null?void 0:f.headers)!==void 0?$u(f.headers):d,p=(f==null?void 0:f.body)!==void 0?f.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},g=(s=f==null?void 0:f.credentials)!=null?s:u,x=await((o=this.fetch)!=null?o:globalThis.fetch)(h,{method:"POST",headers:f6({"Content-Type":"application/json",...m},`ai-sdk/${x6}`,d6()),body:JSON.stringify(p),credentials:g,signal:e});if(!x.ok)throw new Error((i=await x.text())!=null?i:"Failed to fetch the chat response.");if(!x.body)throw new Error("The response body is empty.");return this.processResponseStream(x.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await If(this.body),a=await If(this.headers),l=await If(this.credentials),u={...$u(a),...$u(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?$u(d.headers):u,m=(r=d==null?void 0:d.credentials)!=null?r:l,g=await((s=this.fetch)!=null?s:globalThis.fetch)(f,{method:"GET",headers:f6(h,`ai-sdk/${x6}`,d6()),credentials:m});if(g.status===204)return null;if(!g.ok)throw new Error((o=await g.text())!=null?o:"Failed to fetch the chat response.");if(!g.body)throw new Error("The response body is empty.");return this.processResponseStream(g.body)}},bA=class extends HQe{constructor(e={}){super(e)}processResponseStream(e){return EXe({stream:e,schema:TQe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},UQe=class{constructor({generateId:e=bXe,id:t=e(),transport:n=new bA,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new $Qe,this.sendMessage=async(f,h)=>{var m,p,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(m=this.lastMessage)==null?void 0:m.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await VQe(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:x=f,f.messageId!=null){const y=this.state.messages.findIndex(v=>v.id===f.messageId);if(y===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[y].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,y+1),this.state.replaceMessage(y,{...x,id:f.messageId,role:(p=x.role)!=null?p:"user",metadata:f.metadata})}else this.state.pushMessage({...x,id:(g=x.id)!=null?g:this.generateId(),role:(b=x.role)!=null?b:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const m=f==null?this.state.messages.length-1:this.state.messages.findIndex(p=>p.id===f);if(m===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[m].role==="assistant"?m:m+1),await this.makeRequest({trigger:"regenerate-message",messageId:f,...h})},this.resumeStream=async(f={})=>{await this.makeRequest({trigger:"resume-stream",...f})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolOutput=async({state:f="output-available",tool:h,toolCallId:m,output:p,errorText:g})=>this.jobExecutor.run(async()=>{var b,x;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(w=>L_(w)&&w.toolCallId===m?{...w,state:f,output:p,errorText:g}:w)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(w=>L_(w)&&w.toolCallId===m?{...w,state:f,output:p,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 m={state:PQe({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};m.abortController.signal.addEventListener("abort",()=>{d=!0}),this.activeResponse=m;let p;if(e==="resume-stream"){const b=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(b==null){this.setStatus({status:"ready"});return}p=b}else p=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:m.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const g=b=>this.jobExecutor.run(()=>b({state:m.state,write:()=>{var x;this.setStatus({status:"streaming"}),m.state.message.id===((x=this.lastMessage)==null?void 0:x.id)?this.state.replaceMessage(this.state.messages.length-1,m.state.message):this.state.pushMessage(m.state.message)}}));await FQe({stream:OQe({stream:p,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:g,onError:b=>{throw b}}),onError:b=>{throw b}}),this.setStatus({status:"ready"})}catch(m){if(d||m.name==="AbortError")return d=!0,this.setStatus({status:"ready"}),null;h=!0,m instanceof TypeError&&(m.message.toLowerCase().includes("fetch")||m.message.toLowerCase().includes("network"))&&(f=!0),this.onError&&m instanceof Error&&this.onError(m),this.setStatus({status:"error",error:m})}finally{try{(i=this.onFinish)==null||i.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:d,isDisconnect:f,isError:h,finishReason:(o=this.activeResponse)==null?void 0:o.state.finishReason})}catch(m){console.error(m)}this.activeResponse=void 0}(a=this.sendAutomaticallyWhen)!=null&&a.call(this,{messages:this.state.messages})&&!h&&await this.makeRequest({trigger:"submit-message",messageId:(l=this.lastMessage)==null?void 0:l.id,metadata:t,headers:n,body:r})}};function WQe({messages:e}){const t=e[e.length-1];if(!t||t.role!=="assistant")return!1;const n=t.parts.reduce((s,o,i)=>o.type==="step-start"?i:s,-1),r=t.parts.slice(n+1).filter(L_).filter(s=>!s.providerExecuted);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function YQe(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 qQe=YQe;const GQe=Jc(qQe);var Ree=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Fn=(e,t,n)=>(Ree(e,t,"read from private field"),n?n.call(e):t.get(e)),Ji=(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)},tc=(e,t,n,r)=>(Ree(e,t,"write to private field"),t.set(e,n),n);function KQe(e,t){return t!=null?GQe(e,t):e}var Fo,vv,wv,lg,cg,ug,Lf,z_,B_,ZQe=class{constructor(e=[]){Ji(this,Fo,void 0),Ji(this,vv,"ready"),Ji(this,wv,void 0),Ji(this,lg,new Set),Ji(this,cg,new Set),Ji(this,ug,new Set),this.pushMessage=t=>{tc(this,Fo,Fn(this,Fo).concat(t)),Fn(this,Lf).call(this)},this.popMessage=()=>{tc(this,Fo,Fn(this,Fo).slice(0,-1)),Fn(this,Lf).call(this)},this.replaceMessage=(t,n)=>{tc(this,Fo,[...Fn(this,Fo).slice(0,t),this.snapshot(n),...Fn(this,Fo).slice(t+1)]),Fn(this,Lf).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?KQe(t,n):t;return Fn(this,lg).add(r),()=>{Fn(this,lg).delete(r)}},this["~registerStatusCallback"]=t=>(Fn(this,cg).add(t),()=>{Fn(this,cg).delete(t)}),this["~registerErrorCallback"]=t=>(Fn(this,ug).add(t),()=>{Fn(this,ug).delete(t)}),Ji(this,Lf,()=>{Fn(this,lg).forEach(t=>t())}),Ji(this,z_,()=>{Fn(this,cg).forEach(t=>t())}),Ji(this,B_,()=>{Fn(this,ug).forEach(t=>t())}),tc(this,Fo,e)}get status(){return Fn(this,vv)}set status(e){tc(this,vv,e),Fn(this,z_).call(this)}get error(){return Fn(this,wv)}set error(e){tc(this,wv,e),Fn(this,B_).call(this)}get messages(){return Fn(this,Fo)}set messages(e){tc(this,Fo,[...e]),Fn(this,Lf).call(this)}};Fo=new WeakMap;vv=new WeakMap;wv=new WeakMap;lg=new WeakMap;cg=new WeakMap;ug=new WeakMap;Lf=new WeakMap;z_=new WeakMap;B_=new WeakMap;var zf,v6=class extends UQe{constructor({messages:e,...t}){const n=new ZQe(e);super({...t,state:n}),Ji(this,zf,void 0),this["~registerMessagesCallback"]=(r,s)=>Fn(this,zf)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>Fn(this,zf)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>Fn(this,zf)["~registerErrorCallback"](r),tc(this,zf,n)}};zf=new WeakMap;function Iee({experimental_throttle:e,resume:t=!1,...n}={}){const r=C.useRef("chat"in n?n.chat:new v6(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new v6(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 XQe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function QQe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function JQe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function eJe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function Aee(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:eJe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function Pee(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 tJe(){var b;const{authToken:e,tokenProps:t}=Ge(),n=X(x=>x.dashboard.aiScopeTables),r=(b=C1().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=Iee({transport:new bA({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=Yi.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:IY(x)}})}),onToolCall:m,sendAutomaticallyWhen:WQe,onFinish({isAbort:x,isDisconnect:y,isError:v}){console.log(x?"[Dashboard Assistant] Stream aborted by user":y?"[Dashboard Assistant] Stream disconnected (network error)":v?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully")},onError(x){var y;if(x.name==="AbortError"||(y=x.message)!=null&&y.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)");return}console.error("[Dashboard Assistant] Stream error:",x)}});async function m({toolCall:x}){if(x.toolName==="getCurrentTableScope"&&u({tool:x.toolName,toolCallId:x.toolCallId,output:{tables:Aee(n||[])}}),x.toolName==="getDashboardContext"){const y=X.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const p=!["ready","error"].includes(l),g=Pee(d);return{sendMessage:s,regenerate:a,isLoading:p,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function Oee(){var u;const{authToken:e,tokenProps:t}=Ge(),n=(u=C1().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=hn({queryKey:["assistant-profile",n],queryFn:()=>Yn(`${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 Fee({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(p8,{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(re,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function l1(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(HD,{className:r});case"view":return c.jsx(Fc,{className:r});case"materialized view":return c.jsx(nle,{className:r});case"model":return c.jsx(D1,{className:r});case"file":return c.jsx(Fi,{className:r});case"dataset":return c.jsx(Cl,{className:r});case"upload":return c.jsx(qD,{className:r});case"url":return c.jsx(w8,{className:r});default:return c.jsx(E1,{className:r})}}const $ee=T.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(Ui,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(Ss.Input,{ref:n,className:Z("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})]}));$ee.displayName=Ss.Input.displayName;const U0=e=>e.label||(e==null?void 0:e.name),w6=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function nJe({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,m]=C.useState(""),[p,g]=C.useState(""),b=s.filter(S=>{if(!h)return!0;const j=U0(S).toLowerCase(),E=w6(S).toLowerCase(),_=h.toLowerCase();return j.includes(_)||E.includes(_)});C.useEffect(()=>{e||(m(""),g(""))},[e]),C.useEffect(()=>{b.length>0&&!p&&g(U0(b[0]))},[b,p]);const x=()=>{if(!p)return;const S=b.find(j=>U0(j)===p);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(j=>"id"in S&&"id"in j?S.id===j.id:S.name===j.name&&S.connectionId===j.connectionId),w=o.length===s.length,N=o.length>0;return c.jsx(c.Fragment,{children:c.jsxs(Lm,{shouldFilter:!1,value:p,onValueChange:g,onKeyDown:y,children:[s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[c.jsx($ee,{placeholder:"Search entities...",value:h,onValueChange:m,className:"flex-1 border-0",autoFocus:!0}),!f&&c.jsxs(re,{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(Sr,{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(re,{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"}),N&&c.jsxs(re,{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(yt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),c.jsxs(zm,{className:"min-h-60",children:[c.jsx(Bm,{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(re,{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(Sr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx(Vm,{children:b.map((S,j)=>{const E=v(S),_="id"in S?S.id:`${S.connectionId}-${S.name}`,k=U0(S);return c.jsxs(Hm,{value:k,onSelect:()=>{E?n==null||n(S):t(S)},onMouseDown:M=>{M.preventDefault(),M.stopPropagation()},className:Z("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:l1(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:w6(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 V_=e=>e.name||e.name,rJe=e=>{const t=V_(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 sJe({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(_n,{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(Zt,{children:[c.jsx(Xt,{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:[l1(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:V_(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(yt,{className:"h-3 w-3"})})]})}),c.jsx(en,{side:"top",className:"max-w-xs",children:rJe(d)})]},h)}),u&&c.jsxs(Zt,{open:s,onOpenChange:o,children:[c.jsx(Xt,{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(rle,{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(yt,{className:"h-3 w-3"})})]})}),c.jsx(en,{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:l1(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:V_(d)}),c.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),c.jsx(re,{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(yt,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function Lee(e){return e.type==="dataset"&&e.label||e.name}function oJe(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 iJe({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,"]"]}),Lee(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(yt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function aJe(e){const{tokenProps:t}=Ge(),n=X(l=>l.authToken)||e;_e(l=>l.selectedConnectionId),_e(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}=hn({queryKey:["semantic-domains"],queryFn:()=>Yn(`${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 lJe(e,t){const{tokenProps:n}=Ge(),r=X(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:l}=hn({queryKey:["datasets",e],queryFn:()=>Yn(`${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 cJe(e){var g,b;const{tokenProps:t}=Ge(),n=X(x=>x.authToken)||e,{connections:r}=$a(e),s=_e(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:m}=hn({queryKey:["databases",s],queryFn:()=>Yn(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),p=(b=d==null?void 0:d.databases)==null?void 0:b.map(x=>({id:x.database_name,name:x.database_name}));return{isPending:f,error:h,databases:p||[],refetch:m,label:l}}function uJe(e){var g;const{tokenProps:t}=Ge(),n=X(b=>b.authToken)||e,{connections:r}=$a(e),s=_e(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=_e(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:m}=hn({queryKey:["schemas",s,o],queryFn:()=>Yn(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),p=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:p||[],refetch:m,label:l}}function zee(e){const{tokenProps:t}=Ge(),n=X(h=>h.authToken)||e,{connections:r}=$a(e),s=_e(h=>{var m,p;return(p=(m=h==null?void 0:h.card)==null?void 0:m.dataSource)==null?void 0:p.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:l,error:u,refetch:d}=hn({queryKey:["dataModels",s],queryFn:()=>Yn(`${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 dJe(){var N,S,j;const e=_e(E=>E.card.dataSource);_e(E=>E.actions.updateDirectSource);const t=_e(E=>E.actions.updateDataSource),[n,r]=C.useState(""),{selectedConnection:s,error:o}=$a(),{databases:i,isPending:a,error:l,label:u}=cJe(),{schemas:d,isPending:f,error:h,label:m}=uJe(),{error:p}=zee(),g=s==null?void 0:s.capabilities.path.includes("schema"),b=s==null?void 0:s.capabilities.path.includes("database"),x=u==null?void 0:u.toLowerCase(),y=m==null?void 0:m.toLowerCase(),v=E=>{e&&t({...e,dbSelection:{database:E,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},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||p)&&c.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[c.jsx("div",{className:"flex items-center",children:c.jsxs("div",{className:"text-sm text-red-800",children:[c.jsx("strong",{children:"Error loading data:"}),c.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&c.jsxs("li",{children:["Connections: ",o]}),l&&c.jsxs("li",{children:[u,": ",l.message]}),h&&c.jsxs("li",{children:[m,": ",h.message]}),p&&c.jsxs("li",{children:["Data Models: ",p.message]})]})]})}),c.jsx(re,{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:((N=e==null?void 0:e.dbSelection)==null?void 0:N.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(ge,{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:m}),c.jsxs(nt,{value:((j=e==null?void 0:e.dbSelection)==null?void 0:j.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(ge,{className:"hover:bg-muted",value:E.id,children:E.name},E.id))})]})]})]})]})}function fJe(){const e=_e(l=>l.card.dataSource),t=_e(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(qD,{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(re,{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(Fi,{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(re,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(l.id),children:c.jsx(yt,{className:"h-3 w-3"})})]},l.id))})]})]})}function hJe(){const e=_e(f=>f.card.dataSource),t=_e(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(m=>m.id!==f);t({...e,selectedEntities:h})},d=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(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(re,{onClick:l,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[c.jsx(Sr,{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(E1,{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(re,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:c.jsx(yt,{className:"h-3 w-3"})})]},f.id))})]})]})}function mJe(e,t){var y,v;const{tokenProps:n}=Ge(),r=X(w=>w.authToken)||t,{connections:s}=$a(t),o=_e(w=>{var N,S;return(S=(N=w==null?void 0:w.card)==null?void 0:N.dataSource)==null?void 0:S.connectionId}),i=_e(w=>{var N,S,j;return(j=(S=(N=w==null?void 0:w.card)==null?void 0:N.dataSource)==null?void 0:S.dbSelection)==null?void 0:j.database}),a=_e(w=>{var N,S,j;return(j=(S=(N=w==null?void 0:w.card)==null?void 0:N.dataSource)==null?void 0:S.dbSelection)==null?void 0:j.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:m,isLoading:p,error:g,refetch:b}=hn({queryKey:[e,o,i,a],queryFn:()=>Yn(`${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 N;return{connectionId:l==null?void 0:l.id,connectionType:l==null?void 0:l.type,dialect:l==null?void 0:l.dialect,type:e,dbObjectType:(N=w==null?void 0:w.table_type)==null?void 0:N.toLowerCase(),id:w[`${e}_name`],database:i,schema:a,name:w[`${e}_name`]}});return{isPending:m,isLoading:p,error:g,entities:x||[],refetch:b,label:d}}function c1({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(Oc,{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 pJe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=$a(),[i,a]=C.useState(""),[l,u]=C.useState(""),[d,f]=C.useState("tables"),{updateDataSource:h,setSelectedConnectionId:m}=Qn(),{entities:p,isLoading:g,error:b}=mJe("table"),{dataModels:x,isPending:y,error:v}=zee(),w=k=>{const M=s.find(R=>R.id===k);if(!M)return;const D=M.type==="upload"?"upload":M.type==="url"?"url":"database";h({...e,connectionId:k,connectionType:M.type,mode:D,dbSelection:{database:"",schema:"",entityType:"table"}}),m(k)},N=k=>{var I,A;const M=n||[],D=M.some(L=>L.name===k.name&&L.type===k.type);let R;if(D)R=M.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:((I=e.dbSelection)==null?void 0:I.database)||"",schema:((A=e.dbSelection)==null?void 0:A.schema)||"",name:k.name,dialect:k.dialect};R=[...M,L]}t==null||t(R)},S=k=>{const M=n||[],D=M.some(I=>I.type==="model"&&I.name===k.name);let R;D?R=M.filter(I=>!(I.type==="model"&&I.name===k.name)):R=[...M,k],t==null||t(R)},j=p.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 M=[...k];if(d==="tables"){const R=j.filter(I=>!k.some(A=>A.name===I.name&&A.type==="table")).map(I=>{var A,L;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:I.dbObjectType,database:((A=e.dbSelection)==null?void 0:A.database)||"",schema:((L=e.dbSelection)==null?void 0:L.schema)||"",name:I.name,dialect:I.dialect}});M=[...k,...R]}else if(d==="datamodels"){const D=E.filter(R=>!k.some(I=>I.name===R.name&&I.type==="model"));M=[...k,...D]}t(M)},[d,j,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(ge,{className:"hover:bg-muted",value:k.id,children:c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(Cl,{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(fJe,{}),e.connectionType==="url"&&c.jsx(hJe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(dJe,{}),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(vs,{className:"grid w-full grid-cols-2",children:[c.jsxs(Gt,{value:"tables",children:["Tables & Views (",j.length,")"]}),c.jsxs(Gt,{value:"datamodels",children:["Data Models (",E.length,")"]})]}),c.jsxs(sr,{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(c1,{title:"Error loading tables",message:b.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):j.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):j.map(k=>{const M=n.some(D=>D.name===k.name&&D.type==="table");return c.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>N(k),children:[c.jsx(Qt,{id:`table-${k.name}`,checked:M,onCheckedChange:()=>N(k),onClick:D=>D.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(sr,{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(c1,{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 M=n.some(D=>D.name===k.name&&D.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(Qt,{id:`dataModel-${k.name}`,checked:M,onCheckedChange:()=>S(k),onClick:D=>D.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 gJe({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:s=[],isRestricted:o=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var N;const[l,u]=C.useState(""),d=C.useCallback(S=>{const j={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:S};t({...j})},[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:m}=aJe(),p=o?f.filter(S=>s.includes(S.id)):f,{datasets:g,isPending:b,error:x}=lJe(e==null?void 0:e.semanticDomainId),y=S=>{const j=r||[],E=j.some(k=>k.id===S.id&&k.type==="dataset");let _;if(E)_=j.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};_=[...j,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(M=>M.id===k.id&&M.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:((N=p.find(S=>S.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:N.label)||"Select semantic domain"})}),c.jsx(tt,{children:p.map(S=>c.jsx(ge,{className:"hover:bg-muted",value:S.id,children:c.jsxs("div",{className:"flex flex-col items-start",children:[c.jsx("span",{className:"font-medium",children:S.label}),c.jsx("span",{className:"text-xs",children:S.description})]})},S.id))})]}),m&&c.jsx(c1,{title:"Error loading semantic models",message:m.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(c1,{title:"Error loading datasets",message:x.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):v.length===0?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:l?"No datasets match your search":"No datasets available"}):v.map(S=>{const j=r.some(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(Qt,{id:`dataset-${S.id}`,checked:j,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 xA({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(M=>M.isVisualEditing),f=X(M=>M.dashboard.aiContext),{setAiContext:h}=Ot(),m=C.useRef(null),[p,g]=C.useState(!1),b=i&&i.length>0,x=!b,y=b&&i.length===1?i[0]:void 0,v=C.useCallback(M=>{const D=M;u({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:D,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...D!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,u]),w=C.useCallback(M=>{u({...n,...M})},[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||[]):(m.current=null,g(!1))},[e,n==null?void 0:n.selectedEntities,r,u,s,n]);const N=M=>{const D=a.filter(R=>!(R.name===M.name&&R.type===M.type));l(D)},S=()=>{l([])},j=C.useCallback(M=>{l(M)},[]),E=C.useCallback(()=>{m.current&&m.current()},[]),_=C.useCallback(M=>{m.current=M,g(!0)},[]);function k(){var M,D;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const R=(M=a==null?void 0:a[0])==null?void 0:M.connectionId,I=(D=a==null?void 0:a[0])==null?void 0:D.connectionType;u({...n,connectionId:R,connectionType:I,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return c.jsx(ns,{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(ys,{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(vs,{className:"grid w-full grid-cols-2",children:[c.jsx(Gt,{value:"database",children:"Direct Source"}),c.jsx(Gt,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&c.jsx(gJe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,allowedDomainIds:i||[],isRestricted:b,autoSelectedDomainId:y,onRegisterSelectAll:_}),(n==null?void 0:n.mode)==="database"&&x&&c.jsx(pJe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,onRegisterSelectAll:_})]})}),c.jsx(iJe,{selectedEntities:a,onDeselectEntity:N}),c.jsx(xs,{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(re,{variant:"outline",onClick:E,disabled:!p,children:"Select All"}),c.jsx(re,{variant:"outline",onClick:S,disabled:a.length===0,children:"Clear All"}),c.jsxs(re,{variant:"outline",onClick:()=>t(!1),children:[c.jsx(yt,{className:"mr-2 h-4 w-4"}),"Close"]}),c.jsxs(re,{onClick:k,children:[c.jsx(Mr,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function bJe({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=tl-n;if(l.length>u){Oe.error(`You can only attach ${tl} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=NJ(l);if(f.forEach(({file:h,error:m})=>{Oe.error(`${h.name}: ${m}`)}),d.length>0)try{const h=await Promise.all(d.map(m=>aA(m)));e(h)}catch(h){console.error("Failed to process files:",h),Oe.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>=tl}),c.jsx(re,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=tl,title:n>=tl?`Maximum ${tl} files allowed`:"Attach files",children:c.jsx($D,{className:"h-4 w-4 text-muted-foreground"})})]})}function xJe({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(),m=f.clientX,p=f.clientY;(m<h.left||m>=h.right||p<h.top||p>=h.bottom)&&i(!1)},[]),u=C.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=C.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const m=tl-r;if(h.length>m){Oe.error(`You can only attach ${tl} files per message. You have ${m} slot(s) remaining.`);return}const{valid:p,errors:g}=NJ(h);if(g.forEach(({file:b,error:x})=>{Oe.error(`${b.name}: ${x}`)}),p.length>0)try{const b=await Promise.all(p.map(x=>aA(x)));t(b),Oe.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),Oe.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:Z("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(qD,{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:[tl-r," slot(s) available"]})]})})]})}const yA=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,m]=C.useState(!1),[p,g]=C.useState(!1),b=C.useRef(null),x=Wm();b2e(),g2e();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:w,setShowReasoning:N}=_S(),{queueMessage:S}=Ym(),{addFileAttachment:j,removeFileAttachment:E,clearFileAttachments:_,getFileAttachments:k}=BT(),M=zT(l),D=_e(V=>V.card.dataSource),R=X(V=>V.dashboard.aiContext),I=X(V=>{var G;return(G=V.dashboard.aiContext)==null?void 0:G.selectedEntities});C.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const A=C.useCallback(()=>{const V=b.current;if(V){if(!e||e.length===0){V.style.height="10px";return}V.style.height="auto";const G=Math.min(Math.max(V.scrollHeight,10),200);V.style.height=`${G}px`}},[e]);C.useEffect(()=>{A()},[A]),C.useEffect(()=>{const V=setTimeout(()=>{A()},0);return()=>clearTimeout(V)},[A]);const L=()=>{const V=e.trim();!V&&M.length===0||(a!=="ready"?(S(l,V,M),t(""),_(l)):r({preventDefault:()=>{}}))},F=V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),L()),V.key==="@"&&(U(),f(!0))},H=C.useCallback(V=>{const G=VYe(V.nativeEvent);G.length>0&&(V.preventDefault(),G.forEach(async K=>{const ee=await aA(K);j(l,ee)}))},[j,l]),$=C.useCallback(V=>{V.forEach(G=>{j(l,G)})},[j,l]),P=C.useCallback(V=>{V.forEach(G=>{j(l,G)})},[j,l]),Y=C.useCallback(V=>{E(l,V)},[E,l]),z=V=>{if(x.selectedEntities.some(K=>K.id&&K.id===V.id||K.name===V.name)){const K=x.selectedEntities.filter(ee=>!(ee.id&&ee.id===V.id||ee.name===V.name));y({selectedEntities:K})}else{const K=[...x.selectedEntities,V];y({selectedEntities:K})}},O=V=>{z(V)},W=V=>{var ee;if(!x.selectedEntities.some(Q=>Q.id&&Q.id===V.id||Q.name===V.name)){const Q=[...x.selectedEntities,V];y({selectedEntities:Q})}const K="label"in V?V.label:V.name;t(e+`@${K} `),f(!1),(ee=b.current)==null||ee.focus()},B=V=>{const G=x.selectedEntities.filter(Q=>!(Q.id&&Q.id===V.id||Q.name===V.name));y({selectedEntities:G});const ee=`@${"label"in V?V.label:V.name}`;e.includes(ee)&&t(e.replace(ee,"").trim())},q=V=>{const G=new Set(V.map(Q=>Q.id||Q.name)),K=x.selectedEntities.filter(Q=>!G.has(Q.id||Q.name));y({selectedEntities:K});let ee=e;V.forEach(Q=>{const oe=`@${"label"in Q?Q.label:Q.name}`;ee=ee.replace(oe,"").trim()}),t(ee)},U=C.useCallback(()=>{x.selectedEntities.length===0&&y({selectedEntities:(R==null?void 0:R.selectedEntities)||[]})},[x.selectedEntities.length,R==null?void 0:R.selectedEntities,y]);return c.jsxs(xJe,{onFilesDropped:$,currentFileCount:M.length,disabled:s,className:"space-y-4",children:[c.jsx(sJe,{entities:x.selectedEntities,availableEntities:I||[],onRemoveEntity:B,onRemoveEntities:q}),M.length>0&&c.jsx(HYe,{files:M,onRemove:Y,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:H,onFocus:()=>{A(),i==null||i()},placeholder:"Ask a question...",className:"max-h-[200px] min-h-[40px] w-full resize-none overflow-y-auto border-0 bg-transparent px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),c.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[l==="dashboard"&&c.jsxs(Xr,{open:d,onOpenChange:V=>{V&&U(),f(V)},children:[c.jsx(Qr,{asChild:!0,children:c.jsx(re,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:c.jsx(Zae,{className:"h-4 w-4 text-muted-foreground"})})}),c.jsx(Jr,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:V=>V.preventDefault(),children:c.jsx(nJe,{isOpen:!0,onSelect:z,onDeselect:O,onClose:()=>{var V;f(!1),(V=b.current)==null||V.focus()},availableEntities:I||[],selectedEntities:x.selectedEntities,onTabComplete:W,onSelectAll:()=>{I&&y({selectedEntities:I})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),m(!0)}})})]}),c.jsx(bJe,{onFilesSelected:P,disabled:s,currentFileCount:M.length})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[s&&c.jsx(re,{className:"rounded-full",size:"sm",onClick:o,children:c.jsx(hle,{className:"size-3.5 bg-background"})}),!s&&c.jsx(re,{disabled:!e.trim()&&M.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:L,title:a!=="ready"?"Message will be queued":void 0,children:c.jsx(_8,{className:"size-4"})})]})]})]}),c.jsx(xA,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:m,dataSource:D||kC,dialogMode:"aiContext"})]})});yA.displayName="ChatInputWithContext";function Bee({assistantType:e,className:t}){const n=AY(e),{removeFromQueue:r}=Ym();return n.length===0?null:c.jsxs("div",{className:Z("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(Tl,{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(re,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:c.jsx(yt,{className:"h-3 w-3"})})]})},s.id))})]})}function Vee({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=AY(e),{dequeueMessage:o}=Ym();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 Hee(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),[m,p]=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}),N=C.useCallback(()=>{const _=i.current;return _?_.scrollHeight-_.scrollTop-_.clientHeight:0},[]),S=C.useCallback((_={})=>{if(!i.current)return;const{force:M=!1,instant:D=!1}=_;if(!M&&!y.current||!a&&!M)return;const R=D||r==="auto"||r==="instant"?"auto":r;v.current&&cancelAnimationFrame(v.current),b.current=!0,v.current=requestAnimationFrame(()=>{if(!M&&!y.current){b.current=!1,v.current=void 0;return}const I=i.current;if(!I){b.current=!1,v.current=void 0;return}const A=I.scrollHeight;R==="smooth"&&"scrollTo"in I?I.scrollTo({top:A,behavior:R}):I.scrollTop=A,g.current=I.scrollTop,d(!0),l(!0),y.current=!0,h(!1),p(0),b.current=!1,v.current=void 0})},[r,a]),j=C.useCallback(()=>{const _=i.current;if(!_)return;const k=g.current,M=_.scrollTop,D=M-k;if(g.current=M,D<-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 R=N()<=n;d(R),l(R),y.current=R,R&&(h(!1),p(0))},[N,n]),E=C.useCallback(()=>{p(0),h(!1)},[]);return C.useEffect(()=>{y.current=a},[a]),C.useEffect(()=>{const _=i.current;if(!_||!e||e.length===0){h(!1),p(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,M=e[e.length-1],D=(M==null?void 0:M.id)??(M==null?void 0:M.messageId)??(M==null?void 0:M.createdAt)??(M==null?void 0:M.timestamp)??e.length,R=Array.isArray(M==null?void 0:M.parts)?M.parts.reduce(($,P)=>P?typeof P=="string"?$+P.length:typeof P.text=="string"?$+P.text.length:typeof P.content=="string"?$+P.content.length:typeof P.value=="string"?$+P.value.length:$:$,0):typeof(M==null?void 0:M.content)=="string"?M.content.length:typeof(M==null?void 0:M.text)=="string"?M.text.length:0,I=e.length>k.count,A=D!==k.key,L=R>k.length,F=s&&(M==null?void 0:M.role)==="assistant"&&!I&&(A||L),H=o||F;if(w.current={key:D,count:e.length,length:R},a&&(I||A||L||H)){S({force:!1,instant:H});return}if(!a&&I){const $=e.length-k.count;$>0&&(h(!0),p(P=>P+$))}else!a&&L&&(h(!0),p($=>$>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 M=i.current;if(!M)return;const D=x.current,R=M.scrollHeight;x.current=R,!b.current&&y.current&&R>D&&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:m,scrollToBottom:S,handleScroll:j,resetNewMessageCount:E}}function Uee(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 Wee(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:jJ(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const yJe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function vJe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=C.useState(!1),[a,l]=C.useState(rD),[u,d]=C.useState(!1),[f,h]=C.useState(!1),[m,p]=C.useState(!1),g=n??m,{isLocalDev:b,isConsoleMode:x}=xm(),y=C.useRef(null);X(He=>He.dashboard.aiScopeTables),X(He=>He.isDashboardEditing);const v=X(He=>He.selectedSheetId),{setDataSource:w}=Qn(),{addFrame:N,setSelectedFrameId:S,setIsDashboardEditing:j}=Ot(),E=Wm(),{setCurrentAIContext:_,updateSelectedEntities:k,setReasoningEffort:M,setShowReasoning:D}=_S(),{clearQueue:R}=Ym(),{clearFileAttachments:I,getFileAttachments:A}=BT(),L=zT("dashboard"),F=X(He=>He.dashboard.aiContext),H=_e(He=>He.card.dataSource),{assistantProfile:$}=Oee(),P=X(He=>He.handleOpenAssistantProfile),{sendMessage:Y,isLoading:z,messages:O,setMessages:W,status:B,stop:q,errorMessage:U,clearError:V}=tJe(),G=C.useCallback(He=>{r==null||r(He),n===void 0&&p(He)},[n,r]),K=C.useCallback(()=>{G(!g)},[g,G]);C.useEffect(()=>{if(!g)return;function He(Jt){Jt.key==="Escape"&&G(!1)}return window.addEventListener("keydown",He),()=>{window.removeEventListener("keydown",He)}},[g,G]);const[ee,Q]=C.useState(""),J=He=>{Q(He.target.value)};function oe({sql:He,cardTitle:Jt,connectionId:Ke,cardType:Qe,python:Le,cardConfig:ye,dataSource:Be,customVisualPreferences:ve}){if(!v)return;const Ue={id:vr(),title:Jt||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Qe==="horizontalBar"?"y":"x"}},type:Qe,sql:He,python:Le,dataSource:Be,config:ye,connectionId:Ke,customCardPreferences:ve?{url:ve.url,componentName:ve.componentName,pluginChartType:ve.pluginChartType,settings:ve.settings,type:"component"}:void 0},at={id:vr(),cards:[Ue],activeCardId:Ue.id};j(!0),N(v,at,"end"),S(at.id)}const ue=He=>{He.preventDefault();const Jt=ee.trim();if(!Jt&&L.length===0)return;const Ke=[];Jt&&Ke.push({type:"text",text:Jt}),L.forEach(Qe=>{Qe.data&&Ke.push({type:"file",mediaType:Qe.type,filename:Qe.name,url:`data:${Qe.type};base64,${Qe.data}`})}),Y({role:"user",parts:Ke}),Q(""),I("dashboard"),ie({force:!0})};C.useEffect(()=>{var He;e&&((He=y.current)==null||He.focus())},[e]),Vee({assistantType:"dashboard",status:B,isLoading:z,sendMessage:Y});const{hasActiveTools:ae}=Wee(O),{visibleMessages:Ce,hasMoreMessages:me,totalMessageCount:se,loadMoreMessages:de,resetMessageWindow:Se}=Uee(O,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Re,isAtBottom:fe,hasNewMessages:Ie,newMessageCount:qe,scrollToBottom:ie,handleScroll:be,resetNewMessageCount:$e}=Hee(Ce,{threshold:50,behavior:"smooth",isStreaming:z});function he(He){Ae();const Jt={role:"user",parts:[{type:"text",text:He.title+" "+He.subtitle}]};Y(Jt)}function Ee(He){Ae(),Y({role:"user",parts:[{type:"text",text:He}]})}function Ve(He){Ae(),Y({role:"user",parts:[{type:"text",text:He}]}),ie({force:!0})}const We=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),Oe.success("Conversation copied")}catch(Jt){console.error("Failed to copy conversation",Jt),Oe.error("Unable to copy conversation")}},[O]);function Ae(){E.selectedEntities.length===0&&_({selectedEntities:(F==null?void 0:F.selectedEntities)||[]})}const xt=(ee==null?void 0:ee.length)===0&&(O==null?void 0:O.filter(He=>He.role==="user").length)===0;function Ne(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function mt(){return c.jsxs(gm,{children:[c.jsx(bm,{asChild:!0,children:c.jsx(kc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(lm,{className:"size-3.5"})})}),c.jsxs(rf,{align:"end",children:[c.jsx(sh,{children:"Options"}),c.jsx(Ad,{}),c.jsx(fg,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(fg,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(fg,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const _t=c.jsxs("div",{"data-role":"dashboard-assistant",className:Z("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:[Ne(),P&&c.jsx(re,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:P,children:($==null?void 0:$.name)||"Default Profile"}),c.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[x&&mt(),a&&c.jsx(re,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:We,children:"Copy Conversation"}),c.jsx(kc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:K,children:g?c.jsx(FD,{className:"size-4"}):c.jsx(M1,{className:"size-4"})}),c.jsx(kc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{W([]),R("dashboard"),V(),Se()},children:c.jsx(T1,{className:"size-4"})}),c.jsx(kc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(yt,{className:"size-4"})})]})]}),c.jsxs(Bl,{"data-role":"dashboard-assistant-scroll-area",ref:Re,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:be,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[me&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(re,{variant:"outline",size:"sm",onClick:de,className:"text-xs",children:["Load ",Math.min(5,se-Ce.length)," ","more messages (",se-Ce.length," ","hidden)"]})}),c.jsx(EJ,{showTools:a,showSystemMessage:u,messages:Ce,onAddToDashboard:oe,onQuickReply:Ve,disableQuickReplies:z}),!ae&&c.jsx(kJ,{status:B,errorMessage:U})]}),c.jsx(si,{orientation:"horizontal"})]}),e&&!fe&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(re,{onClick:()=>{ie({force:!0}),$e()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(hr,{className:"h-4 w-4"}),Ie&&qe>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:qe>9?"9+":qe})]})}),c.jsxs("div",{className:"space-y-3",children:[!$&&xt&&c.jsx(_J,{onClick:he,placeholders:yJe}),c.jsx("div",{children:xt&&$&&c.jsx(Fee,{seedQuestions:$.seedQuestions||[],handleSeedQuestionClick:Ee})}),c.jsx(Bee,{assistantType:"dashboard",className:"mb-3"}),c.jsx(yA,{ref:y,setInput:Q,stop:q,input:ee,handleInputChange:J,handleSubmit:He=>{Ae(),ue(He),ie({force:!0})},isLoading:z,status:B,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx(xA,{incomingSelectedEntities:(F==null?void 0:F.selectedEntities)||[],open:f,onOpenChange:h,dataSource:H||kC,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:_t})}),s):_t}function wJe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Ot(),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(m){const p=m.ctrlKey||m.metaKey;p&&m.key==="c"?(await f(),Oe.success("Card copied to clipboard"),m.preventDefault()):p&&m.key==="v"&&(await h(),m.preventDefault())}async function f(){try{const m=n();m&&await navigator.clipboard.writeText(JSON.stringify(m))}catch(m){console.error("Failed to copy text:",m)}}async function h(){if(!a)return null;try{const m=await navigator.clipboard.readText();try{const p=JSON.parse(m);if(p!=null&&p.id){const g=dI(p),b=g.cards.findIndex(x=>x.id===g.activeCardId);b!==-1&&(g.cards[b].title=`${g.cards[b].title} (Copy)`),r(a,g),s(g.id),Oe.success("Card pasted from clipboard")}}catch(p){console.error("Failed to parse clipboard contents: ",p)}return m}catch(m){return console.error("Failed to paste text:",m),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[r,n,s,a,l,u,t])}function SJe(e,t){switch(e.interactionMode){case"drillToDetail":CJe(e,t);break;case"drillThrough":NJe(e,t);break;case"drillToURL":jJe(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 CJe(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 NJe(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 jJe(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 kJe({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(ns,{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(ys,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(qZ,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(XZ,{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 EJe(){const e=It(w=>w.interactionStates),t=It(w=>w.setInteractionState),n=It(w=>w.clearLastInteractionEvent),r=It(w=>w.replaceCardWithInsight),s=It(w=>w.setPendingDrillThrough),o=It(w=>w.pendingDrillThrough),i=It(w=>w.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Ot(),{selectDashboard:u}=tx(),d=X(w=>w.dashboard),f=X(w=>w.filterValues),{data:h,isLoading:m}=H7((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[p,g]=C.useState({open:!1,insightId:""}),b=QZ(p.insightId,{enabled:p.open&&!!p.insightId}),x=C.useRef(new Set),y=C.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:w,filters:N,contextMode:S})=>{g({open:!0,insightId:w,filters:N,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:S})},replaceCardContent:({cardId:w,insightId:N,filters:S,contextMode:j})=>{r(w,N,S,j)},getCurrentFilters:()=>f||[],navigateWithDrill:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:w,contextMode:N,sourceDashboardId:S,sourceDashboardTitle:j,targetDashboardId:E})=>{const k={sourceCardId:ga,interactionMode:"clickFilter",filterGroups:[{filters:w}]},M={...Wo(),appliedClickFilters:[k],contextMode:N,sourceDashboardId:S,sourceDashboardTitle:j,targetDashboardId:E};t(ga,M)}}),[a,r,f,l,d,s,t]);C.useEffect(()=>{Object.entries(e).forEach(([w,N])=>{if(N!=null&&N.lastInteractionEvent){const S=N.lastInteractionEvent,j=`${w}-${S.interactionMode}-${S.sourceCardId}-${Date.now()}`;if(x.current.has(j))return;x.current.add(j);try{SJe(S,y)}catch(E){console.error("Error executing interaction event:",E)}finally{n(w),setTimeout(()=>{x.current.delete(j)},5e3)}}})},[e,n,y]),C.useEffect(()=>{if(!(!o||!h||m))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,m,u,l,i]);const v=()=>{g({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(kJe,{open:p.open,onOpenChange:v,insightId:p.insightId,filters:p.filters,filterDefinitions:p.filterDefinitions,contextMode:p.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&m&&c.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border bg-background p-6 shadow-lg",children:[c.jsx(an,{className:"h-8 w-8 animate-spin text-primary"}),c.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function _Je(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=DJe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function DJe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function MJe(e){return e?`Back to ${e}`:"Back"}function TJe(){var x,y,v,w,N;const e=It(S=>S.interactionStates[ga]),t=X(S=>S.actions.goBackFromDrill),n=X(S=>S.actions.clearDrillContext),{selectDashboard:r}=tx(),[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})},j=()=>{a(!1)};return document.addEventListener("mousemove",S),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",S),document.removeEventListener("mouseup",j)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((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||!((N=e.appliedClickFilters)!=null&&N.length))return null;const m=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(S){console.error("[DrillBack] Error during back navigation:",S)}},p=()=>{n()},g=S=>{S.target.closest("button")||(a(!0),l.current={x:S.clientX-s.x,y:S.clientY-s.y})};_Je(f);const b=MJe(d);return c.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:c.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:g,style:{cursor:i?"grabbing":"grab"},children:[c.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((S,j)=>{const E=S.field.label||S.field.name,_=String(S.value);return c.jsxs(Fe,{variant:"secondary",className:"pointer-events-none text-xs",children:[E," = ",_]},j)})})]}),c.jsx(re,{variant:"ghost",size:"sm",onClick:p,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(yt,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(re,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(l8,{className:"mr-2 h-4 w-4"}),b]})})]})})}function Yee(){var Q;const{showAssistant:e,tokenProps:t}=Ge(),{preferences:n,isConsoleMode:r}=xm(),s=((Q=n==null?void 0:n.cardDisplay)==null?void 0:Q.mode)==="print",o=C.useRef(null),i=C.useRef(null),[a,l]=C.useState(!1),u=vd(J=>J.setFullscreen),d=vd(J=>J.setPanelOpen),f=vd(J=>J.setContainer),h=MY("dashboard"),m=TY(),p=RY("dashboard"),g=h.isOpen,b=m==="dashboard",x=X(J=>J.isVisualEditing),y=X(J=>J.themeStyle),v=X(J=>{var oe;return(oe=J.dashboard)==null?void 0:oe.sheets}),w=X(J=>J.isDashboardEditing),N=X(J=>J.selectedSheetId),S=X(J=>{var oe;return(oe=J.dashboard)==null?void 0:oe.id}),j=X(J=>J.isDashboardPanelOpen),E=X(J=>J.actions.setIsDashboardPanelOpen),{getDefaultSheetId:_,setDefaultSheetId:k,clearDefaultSheetId:M}=r8(S),[D,R]=C.useState(null);W1(Pt.DASHBOARD);const{setSelectedSheetId:I,setSheetTitle:A,addSheet:L,setSheets:F}=Ot();wJe(i);const{setActiveAssistantType:H}=_S();C.useEffect(()=>{if(S){const J=_();R(J)}},[S,_]),C.useEffect(()=>{g?H("dashboard"):m==="dashboard"&&u(null)},[g,H,m,u]);function $(J){var oe,ue;J?((oe=o.current)==null||oe.resize(40),d("dashboard",!0),H("dashboard")):(d("dashboard",!1),u(null),(ue=o.current)==null||ue.resize(0),H(null))}function P(){const J={id:vr(),title:"New Sheet"};L(J),I(J.id)}function Y(J,oe){if(!S)return;D===J?(M(),R(null),Oe.success("Default sheet cleared")):(k(J),R(J),Oe.success(`"${oe}" set as default sheet`))}function z(J){J<1?(d("dashboard",!1),u(null),H(null)):(g||d("dashboard",!0),H("dashboard"))}function O(){return(y==null?void 0:y.canvasTheme)==="muted"||!(y!=null&&y.canvasTheme)?"hsl(var(--semaphor-muted))":(y==null?void 0:y.canvasTheme)==="clear"?"":y==null?void 0:y.canvasTheme}const W=(J,oe)=>{J.dataTransfer.setData("tabIndex",oe.toString())},B=J=>{J.preventDefault()},q=(J,oe)=>{const ue=J.dataTransfer.getData("tabIndex");if(ue===oe.toString())return;const ae=Array.from(v||[]),[Ce]=ae.splice(parseInt(ue),1);ae.splice(oe,0,Ce),F(ae)},U=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail;function V(){var J,oe;if(v&&v.length>1||w)return c.jsxs(vs,{role:"tab-list",className:"flex h-11 items-center justify-start gap-2 rounded-none border-b border-b-muted bg-transparent px-2.5 py-3",children:[r&&U&&c.jsx(re,{variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{E(!j)},className:"h-8 p-2",children:j?c.jsx(h8,{className:"h-4 w-4"}):c.jsx(m8,{className:"h-4 w-4"})}),v==null?void 0:v.map((ue,ae)=>{const Ce=N===ue.id,me=D===ue.id;return c.jsxs(Gt,{draggable:!0,onDragStart:se=>W(se,ae),onDragOver:B,onDrop:se=>q(se,ae),style:{borderRadius:y==null?void 0:y.controlInputRadius},onClick:()=>I(ue.id),className:"flex items-center gap-1 rounded-none border px-2 py-1",value:ue.id,children:[c.jsx(jb,{enabled:w&&Ce,text:ue.title,onSave:se=>A(ue.id,se),children:ue.title},ue.id),!w&&Ce&&c.jsx("div",{title:me?"Clear default sheet":"Set as default sheet",children:c.jsx(VD,{className:Z("ml-1 size-3 cursor-pointer transition-all",me?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:se=>{se.stopPropagation(),Y(ue.id,ue.title||"Sheet")}})}),w&&Ce&&v.length>1&&c.jsx(yt,{className:"ml-1 size-3",onClick:()=>l(!0)})]},ue.id)}),w&&c.jsx("div",{style:{borderRadius:(oe=(J=y==null?void 0:y.chart)==null?void 0:J.options)==null?void 0:oe.borderRadius},className:"flex h-7 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:P,children:c.jsx(Sr,{className:"size-3"})})]})}function G(){return c.jsx("div",{ref:i,style:{},className:"grow",children:v==null?void 0:v.map(J=>c.jsx(sr,{style:{backgroundColor:O()},className:Z("mt-0",{}),value:J.id,children:c.jsx(a8e,{sheet:J})},J.id))})}function K(){var J;return c.jsxs(Bs,{"data-role":"dashboard-tabs-container",className:Z("relative flex h-full flex-col",y==null?void 0:y.dashboardTabsContainer),onValueChange:oe=>{I(oe)},value:N||((J=v==null?void 0:v[0])==null?void 0:J.id),children:[V(),c.jsx(Bl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:G()}),c.jsx(F8e,{open:a,setOpen:l})]})}const ee=C.useCallback(J=>{f("dashboard",J)},[f]);return v?c.jsxs(c.Fragment,{children:[c.jsx(EJe,{}),c.jsx(TJe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(lQ,{className:Z("flex-1 basis-0 overflow-y-auto transition-opacity",b&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(x_,{children:K()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx(O8e,{open:g,onTabClick:$,withHandle:!0}),c.jsx(x_,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:z,defaultSize:g?40:0,ref:o,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(vJe,{open:g,setOpen:$,isFullscreen:b,onFullscreenChange:J=>u(J?"dashboard":null),fullscreenContainer:p})})})]})]}),c.jsx("div",{ref:ee,className:Z("absolute inset-0",!b&&"pointer-events-none")}),e===!0&&!s&&!g&&!x&&c.jsx("div",{className:"fixed bottom-6 right-6 z-50",children:c.jsx(re,{size:"sm",variant:"outline",className:"h-12 w-12 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>$(!0),title:"Open Assistant",children:c.jsx(BD,{className:"h-5 w-5"})})})]})]}):null}function vA({children:e}){return c.jsx(Fa,{style:{height:"100%",width:"100%"},children:c.jsx(uae,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(_n,{delayDuration:0,children:e})})})}function qee({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(v7.Provider,{value:r,children:c.jsx(wI,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function RJe(e=2e3,t=500){const n=Lae(),[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 wA({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=RJe(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 Gee(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(Ua,{FallbackComponent:eC,children:c.jsxs(jD,{dashboardProps:e,children:[c.jsx(wA,{componentType:"dashboard",componentId:e.id}),c.jsx(vA,{children:c.jsx(qee,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(VT,{...e,type:"dashboard",children:c.jsx(Yee,{})})})})})]})})}function SA(e){const{tokenProps:t,authToken:n}=Ge(),r=t==null?void 0:t.apiServiceUrl;return hn({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return Yn(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 Kee(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 Zee(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 Xee=e=>{var R;const t=(R=e==null?void 0:e.dataSource)==null?void 0:R.semanticDomainId,{data:n}=SA(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=Qn(),h=_e(I=>I.card.type),m=e==null?void 0:e.id,p=C.useCallback(I=>{if(!(e!=null&&e.config))return[];switch(I){case"groupBy":return(e.config.groupByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType,dateFormat:A.dateFormat,customFormat:A.customFormat,granularity:A.granularity}));case"metrics":return e.config.metricColumns||[];case"pivotBy":return(e.config.pivotByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map(A=>({id:A.id,name:A.name,dataType:A.dataType,label:A.label!==void 0?A.label:A.name,qualifiedEntityName:A.qualifiedEntityName,entityId:A.entityId,entityName:A.entityName,entityType:A.entityType,direction:A.direction}));case"source":return[];default:return[]}},[e]),g=C.useCallback((I,A)=>{if(m)switch(I){case"groupBy":{r(m,{groupByColumns:A});break}case"metrics":{r(m,{metricColumns:A});break}case"pivotBy":{r(m,{pivotByColumns:A});break}case"sortBy":{r(m,{sortByColumns:A});break}}},[m,r]),b=C.useCallback((I,A,L)=>{if(!m)return;const H=p(I)[A];if(H)switch(I){case"groupBy":s(m,H.id,{label:L});break;case"metrics":o(m,H.id,{label:L});break;case"pivotBy":i(m,H.id,{label:L});break;case"sortBy":a(m,H.id,{label:L});break}},[m,p,s,o,i,a]),x=C.useCallback((I,A)=>{if(!m)return;const F=p("metrics")[I];F&&o(m,F.id,{aggregate:A,label:OU(F.name,A)})},[m,p,o]),y=C.useCallback((I,A,L)=>{if(!m)return;const H=p("groupBy")[I];if(!H)return;const $={dateFormat:A};A==="custom"&&L?$.customFormat=L:$.customFormat=void 0,s(m,H.id,$)},[m,p,s]),v=C.useCallback((I,A)=>{if(!m)return;const F=p("groupBy")[I];F&&s(m,F.id,{granularity:A})},[m,p,s]),w=C.useCallback((I,A)=>{if(!m)return;const F=p("metrics")[I];F&&o(m,F.id,{aliasTemplate:A})},[m,p,o]),N=C.useCallback((I,A)=>{if(console.log("handleValueAliasesChange",I,A),!m)return;console.log("handleValueAliasesChange",I,A);const F=p("metrics")[I];F&&(console.log("handleValueAliasesChange",A),o(m,F.id,{valueAliases:A}))},[m,p,o]),S=C.useCallback(I=>{if(!m)return;if(p("metrics").length===0){Oe.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(m,{comparisonType:I})},[m,r,p]),j=C.useCallback(I=>{m&&r(m,{showTrendline:I})},[m,r]),E=C.useCallback(I=>{m&&r(m,{trendlineWindow:I})},[m,r]),_=C.useCallback(I=>{m&&r(m,{trendlineGranularity:I})},[m,r]),k=C.useCallback(I=>{m&&r(m,{targetValue:I})},[m,r]),M=C.useCallback(I=>{var Y;if(!m)return;const A=[...p("groupBy"),...p("pivotBy"),...p("metrics"),...p("sortBy")],L=rNe(I,A,{joinPlan:(Y=e==null?void 0:e.config)==null?void 0:Y.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!L.isValid){L.showError&&IU();return}const F=iNe(I,A,h);if(!F){Oe.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const H=Kee(I,F,h);if(!H.isValid){Oe.error("Invalid Field Type",{description:H.reason,position:"top-center",duration:3e3});return}const $=p(F);if(AU(I,$))return;const P=FU(I,F,$);if(P){const z=[...$,P];g(F,z),F==="metrics"&&Zee(h,e==null?void 0:e.config,r,m,z)}},[m,e==null?void 0:e.config,p,g,t,n,h,r]),D=C.useCallback((I,A)=>{if(!m)return;const F=p(I)[A];if(F){if(I!=="sortBy"){const H=p("sortBy"),$=H.filter(P=>!(P.name===F.name&&P.qualifiedEntityName===F.qualifiedEntityName));$.length!==H.length&&r(m,{sortByColumns:$})}switch(I){case"groupBy":l(m,F.id);break;case"metrics":u(m,F.id);break;case"pivotBy":d(m,F.id);break;case"sortBy":f(m,F.id);break}}},[m,p,l,u,d,f,r]);return{getFieldsForContainer:p,setFieldsForContainer:g,updateLabel:b,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:v,handleAliasTemplateChange:w,handleValueAliasesChange:N,removeField:D,handleFieldClick:M,handleKpiComparisonTypeChange:S,handleKpiShowTrendlineChange:j,handleKpiTrendlineWindowChange:E,handleKpiTrendlineGranularityChange:_,handleKpiTargetValueChange:k,cardType:h}};function hy(e,t){var Ee,Ve,We,Ae,xt;const{tokenProps:n}=Ge(),r=zs(),s=Ge().authToken||e,o=_e(Ne=>Ne.selectedConnectionId),i=_e(Ne=>Ne.card),{queryKey:a}=Epe(i),l=_e(Ne=>Ne.selectedDatamodelId),u=_e(Ne=>Ne.isDevMode),d=_e(Ne=>Ne.selectedDatabaseName),f=_e(Ne=>Ne.selectedSchemaName),h=_e(Ne=>Ne.selectedTableName),m=_e(Ne=>Ne.actions.setSelectedConnectionId),p=_e(Ne=>Ne.actions.setSelectedDatamodelId),g=_e(Ne=>Ne.actions.setSelectedDatabaseName),b=_e(Ne=>Ne.actions.setSelectedSchemaName),x=_e(Ne=>Ne.actions.setSelectedTableName);_e(Ne=>Ne.actions.setCardSql);const{setQueryConfig:y}=Qn();function v(Ne){var _t;return o&&Ne==="API"?!1:o&&Ne==="S3"?!0:!(!o||!d||d==="NA"||((_t=_==null?void 0:_.capabilities)==null?void 0:_t.path.includes("schema"))&&!f)}function w(Ne){return o&&Ne?!(Ne==="API"||Ne==="S3"):!1}const{refetchConnections:N,connectionsData:S,isConnectionsLoading:j,isConnectionsError:E,selectedConnection:_}=$a(e),{refetch:k,data:M,isLoading:D,isError:R}=hn({queryKey:["models",o],queryFn:()=>Yn(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),I=_==null?void 0:_.type,A=(_==null?void 0:_.type)==="API"||(_==null?void 0:_.type)==="S3",{data:L,isLoading:F,isFetching:H,isError:$,refetch:P}=hn({queryKey:["databases",o],queryFn:()=>Yn(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:w(I)}),{data:Y,isLoading:z,isFetching:O,isError:W,refetch:B}=hn({queryKey:["schemas",o,d],queryFn:()=>Yn(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&!A&&d!=="NA"}),{data:q,isLoading:U,isFetching:V,isError:G,refetch:K}=hn({queryKey:["tables",o,d,f],queryFn:()=>Yn(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(I)}),{columns:ee,isColumnsLoading:Q,isColumnsFetching:J,isColumnsError:oe,refetchColumns:ue}=$U(e);C.useEffect(()=>{(I==="S3"||I==="API")&&(g(""),b(""),p(""),I==="API"&&x("api"))},[I,x,g,b,p]);const ae=(_==null?void 0:_.type)==="API"?(Ee=_==null?void 0:_.type)==null?void 0:Ee.toLowerCase():h||"",Ce=A?"":f||"";function me(Ne){x(Ne),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function se(Ne){b(Ne),x("")}function de(Ne){g(Ne==="none"?"":Ne),b(""),x(""),Ne!=="none"&&Ne!==""&&p("")}function Se(Ne){m(Ne)}function Re(Ne){p(Ne==="none"?"":Ne),Ne!=="none"&&Ne!==""&&g("")}L&&((Ve=L==null?void 0:L.databases)==null?void 0:Ve.length)>0,Y&&((We=Y==null?void 0:Y.schemas)==null?void 0:We.length)>0;const fe=S==null?void 0:S.connections.map(Ne=>({id:Ne.id,name:Ne.name,type:Ne.type})),Ie=(Ae=M==null?void 0:M.datamodels)==null?void 0:Ae.map(Ne=>({id:Ne.id,name:Ne.name})),qe=L==null?void 0:L.databases.map(Ne=>({id:Ne.database_name,name:Ne.database_name})),ie=Y==null?void 0:Y.schemas.map(Ne=>({id:Ne.schema_name,name:Ne.schema_name})),be=q==null?void 0:q.tables.map(Ne=>({id:Ne.table_name,name:Ne.table_name})),$e=(xt=M==null?void 0:M.datamodels.find(Ne=>Ne.id===l))==null?void 0:xt.name,he=kv({schemaName:Ce,tableName:ae,modelName:$e,connectionType:I,databaseName:d||""});return{connectionItems:fe,selectedConnectionId:o,selectedConnection:_,isConnectionsLoading:j,isConnectionsError:E,modelItems:Ie,selectedDatamodelId:l,selectedDatamodelName:$e,isModelsLoading:D,isModelsError:R,selectedDatabaseName:d,databaseItems:qe,isDatabasesLoadingOrFetching:F||H,isDatabaseError:$,schemaItems:ie,selectedSchemaName:f,isSchemaLoadingOrFetching:z||O,isSchemaError:W,tableItems:be,selectedTableName:h,isTableLoadingOrFetching:U||V,isTableError:G,columns:ee,isColumnsLoadingOrFetching:Q||J,isColumnsError:oe,isNonDbConnection:A,connectionType:I,tableName:ae,formattedTableName:he,schemaName:Ce,refetchConnections:N,refetchModels:k,refetchDatabases:P,refetchSchemas:B,refetchTables:K,refetchColumns:ue,handleConnectionChange:Se,handleDatamodelChange:Re,handleDatabaseChange:de,handleSchemaChange:se,handleTableChange:me}}function W0(e){return`${e}-${vr()}`}function S6(e,t){const n=ni(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 IJe(e,t){const n=ni(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 CA(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 Qee(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Jee(){const e=_e(S=>S.sqlGen),t=_e(S=>S.isDevMode),n=_e(S=>S.card.dataSource),r=_e(S=>{var j,E;return(E=(j=S.card)==null?void 0:j.queryConfig)==null?void 0:E.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=CA(n),a=Qee(n),l=_e(S=>S.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:m,setIsShowingVisual:p}=Qn(),{connectionType:g,modelItems:b,selectedDatamodelName:x}=hy(),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 j=y(S);if(t&&a&&s){const _=cD(j,e);m(_);const k=(E=b==null?void 0:b.find(D=>D.id===l))==null?void 0:E.name,M=lD(_,Ci(o||""),Ci(s),k||"",g,i||"");M&&(f(M),h(!0))}else if(!t){if(Qb(j.data_type))if(r&&r.length>0){const _={...j,role:"groupby",id:W0(j.column_name),name:j.column_name,type:j.data_type};d(_)}else{const _={...j,role:"metric",id:W0(j.column_name),name:j.column_name,label:S6(j.column_name,"COUNT"),type:j.data_type,aggregate:"COUNT"};u(_)}if(Ii(j.data_type)){const _={...j,role:"groupby",id:W0(j.column_name),name:j.column_name,type:j.data_type,label:IJe(j.column_name,"month"),granularity:"month"};d(_)}if(Ri(j.data_type)){const _={...j,role:"metric",id:W0(j.column_name),name:j.column_name,label:S6(j.column_name,"SUM"),type:j.data_type,aggregate:"SUM"};u(_)}}},handleShowSample:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const S=kv({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});p(!1);const j=g==="MSSQL"?`SELECT top 10 * FROM ${S}`:`SELECT * FROM ${S} LIMIT 10`;f(j),h(!0)},handleShowCount:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const S=kv({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});f(`SELECT COUNT(*) as count FROM ${S}`),h(!0)},isNumberField:S=>Ri(S.dataType)}}function AJe({columnName:e,database:t,schemaName:n,tableName:r,connectionType:s,datamodelId:o,modelName:i,field:a}){const l=Ci(e),u=Ci(t||""),d=Ci(n||""),f=Ci(r);let h=x1({schemaName:d,tableName:f,connectionType:s,databaseName:u}),m=`${h}.${l}`;return o&&o!=="none"&&i&&(m=`${Vg}.${i}.${l}`,h=`${Vg}.${i}`),a!=null&&a.qualifiedFieldName&&(m=a.qualifiedFieldName,h=a.qualifiedFieldName.split(".").slice(0,-1).join(".")),{qualifiedColumnName:m,qualifiedTableName:h,formattedColumnName:l,formattedTableName:f,formattedDatabase:u,formattedSchemaName:d}}function ete(){const e=_e(p=>p.selectedConnectionId),t=_e(p=>p.selectedDatamodelId),n=_e(p=>p.selectedDatabaseName),r=_e(p=>p.selectedSchemaName),s=_e(p=>p.selectedTableName),o=X(p=>p.dashboard.filters)||[],i=X(p=>p.selectedSheetId),a=X(p=>p.actions.addFilter),l=X(p=>p.actions.removeFilter),{removeFilterValues:u}=Ot(),{modelItems:d,tableName:f,connectionType:h}=hy();function m(p,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:N,formattedDatabase:S}=AJe({columnName:p.column_name,database:n,schemaName:r,tableName:f,connectionType:h,datamodelId:t,modelName:x,field:b});let j;if(g==="sheet"&&i?j=i_e(o,y,N,n||"",S,i):j=o==null?void 0:o.find(_=>_.column===y&&_.table===N&&(_.database===S||_.database===n)),j)u(j.id),l(j.id);else{const _=vr(),k=g==="sheet"&&i?[i]:void 0;return f==="api"&&e?(a({location:g,id:_,column:y,title:p.label||p.column_name,dataType:p.data_type,table:"api",database:"",connectionId:e,operation:"in",applyToSheetIds:k,sql:KE(p.data_type,v,w)}),_):(a({id:_,location:g,column:y,title:p.label||p.column_name,dataType:p.data_type,table:s||"",database:n||"",connectionId:e||"",operation:"in",applyToSheetIds:k,sql:KE(p.data_type,v,(b==null?void 0:b.qualifiedFieldName)||w)}),_)}}return{assignFilter:m}}function PJe({column:e}){const[t,n]=C.useState(!1),r=_e(x=>x.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=CA(r),a=_e(x=>x.selectedDatamodelId),l=_e(x=>x.sqlGen),{modelItems:u,connectionType:d}=hy(),f=_e(x=>x.actions.setSqlGen),h=_e(x=>x.actions.setCardSql),m=_e(x=>x.actions.setRunSql),p=Qee(r);function g(x,y){var S;if(!p||!s){console.warn("Cannot generate SQL: missing table metadata");return}const v=cD(x,l,y),w=(S=u==null?void 0:u.find(j=>j.id===a))==null?void 0:S.name;f(v);const N=lD(v,Ci(o||""),Ci(s),w||"",d,i||"");N&&(h(N),m(!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 p?c.jsxs(km,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(Em,{asChild:!0,children:c.jsx(lm,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(of,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]}):null}function OJe({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 FJe({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s}){const o=_e(q=>q.isDevMode),i=t==="filter"||t==="inline-filter",a=o||i||(n==null?void 0:n.state)==="unreachable"&&!i,l=X(q=>q.dashboard.filters),u=X(q=>q.selectedSheetId),d=X(q=>q.actions.removeFilter),{removeFilterValues:f}=Ot(),{assignFilter:h}=ete(),m=t==="filter"?zl(l,u):l,p=t==="filter"?m==null?void 0:m.find(q=>{var U;return q.title===e.name||((U=q.column)==null?void 0:U.includes(e.name))}):void 0,g=!!p,b=t==="inline-filter"&&(s==null?void 0:s.some(q=>q.column===e.qualifiedFieldName||q.column===e.name)),x=g||b,y=p&&i?l==null?void 0:l.find(q=>q.id===p.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:p?{id:p.id,title:p.title,column:p.column,applyToSheetIds:p.applyToSheetIds,excludeSheetIds:p.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,N]=C.useState(!1),[S,j]=C.useState(null),{attributes:E,listeners:_,setNodeRef:k,transform:M,transition:D,isDragging:R}=oy({id:e.id,disabled:a}),[I,A]=C.useState(!1),L=_e(q=>q.card),{handleFieldClick:F}=Xee(L),{handleDevModeFieldClick:H,isNumberField:$}=Jee(),P=()=>{y&&(console.log("[SourceField] Removing multi-sheet filter:",y.id),f(y.id),d(y.id)),j(null),N(!1)},Y=()=>{if(t==="inline-filter"&&r){r(e);return}if(t==="filter"){const q={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description,qualifiedFieldName:e.qualifiedFieldName};x&&v?(j({column:q,field:e}),N(!0)):h(q,"sheet",e)}else o?H(e):F(e)},z={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},O={transform:ii.Transform.toString(M),transition:D},B=(()=>{if(!n||i)return{};const U={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",...U},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...U},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...U}}[n.state]||U})();return c.jsxs("div",{ref:k,style:O,...a?{}:E,...a?{}:_,className:Z("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",R&&"scale-95 opacity-50",!R&&"border",B.borderColor||"border-transparent",B.bgColor||"",B.hoverBorderColor,B.hoverBgColor||"hover:bg-muted",B.opacity,B.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:Y,children:[Eb(e.dataType),c.jsx(_n,{children:c.jsxs(Zt,{children:[c.jsx(Xt,{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 ${I?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),c.jsx(en,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:c.jsx(OJe,{field:e,fieldState:n})})]})}),o&&!i&&$(e)&&c.jsx("div",{onClick:q=>q.stopPropagation(),children:c.jsx(PJe,{column:z})})]}),I&&c.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:c.jsx(Do,{className:"",children:c.jsxs(Oi,{className:"space-y-2 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(M8,{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(xle,{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(px,{open:w,onOpenChange:N,children:c.jsxs(ym,{children:[c.jsxs(vm,{children:[c.jsx(Sm,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(Cm,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(wm,{children:[c.jsx(jm,{children:"Cancel"}),c.jsx(Nm,{onClick:P,children:"Remove Filter"})]})]})})]})}const $Je="SEMAPHOR_CALCULATED_FIELD",LJe=["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 tte(e){return!!e.expression}function zJe(e){return!!e.expression}function BJe(e){return!!e.expression}var nte=(e=>(e.SUBTOTAL="__SUBTOTAL__",e.TOTAL="__TOTAL__",e.ALL="__ALL__",e))(nte||{}),Ki="Accordion",VJe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[NA,HJe,UJe]=sx(Ki),[MC]=kr(Ki,[UJe,bW]),jA=bW(),rte=C.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(NA.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(GJe,{...o,ref:t}):c.jsx(qJe,{...s,ref:t})})});rte.displayName=Ki;var[ste,WJe]=MC(Ki),[ote,YJe]=MC(Ki,{collapsible:!1}),qJe=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:Ki});return c.jsx(ste,{scope:e.__scopeAccordion,value:C.useMemo(()=>a?[a]:[],[a]),onItemOpen:l,onItemClose:C.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(ote,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(ite,{...i,ref:t})})})}),GJe=C.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i,a]=Br({prop:n,defaultProp:r??[],onChange:s,caller:Ki}),l=C.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=C.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return c.jsx(ste,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(ote,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(ite,{...o,ref:t})})})}),[KJe,TC]=MC(Ki),ite=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=HJe(n),f=eu(s)==="ltr",h=ke(e.onKeyDown,m=>{var E;if(!VJe.includes(m.key))return;const p=m.target,g=u().filter(_=>{var k;return!((k=_.ref.current)!=null&&k.disabled)}),b=g.findIndex(_=>_.ref.current===p),x=g.length;if(b===-1)return;m.preventDefault();let y=b;const v=0,w=x-1,N=()=>{y=b+1,y>w&&(y=v)},S=()=>{y=b-1,y<v&&(y=w)};switch(m.key){case"Home":y=v;break;case"End":y=w;break;case"ArrowRight":o==="horizontal"&&(f?N():S());break;case"ArrowDown":o==="vertical"&&N();break;case"ArrowLeft":o==="horizontal"&&(f?S():N());break;case"ArrowUp":o==="vertical"&&S();break}const j=y%x;(E=g[j].ref.current)==null||E.focus()});return c.jsx(KJe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(NA.Slot,{scope:n,children:c.jsx(ze.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),u1="AccordionItem",[ZJe,kA]=MC(u1),ate=C.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=TC(u1,n),i=WJe(u1,n),a=jA(n),l=ar(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(ZJe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(vW,{"data-orientation":o.orientation,"data-state":hte(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});ate.displayName=u1;var lte="AccordionHeader",cte=C.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=TC(Ki,n),o=kA(lte,n);return c.jsx(ze.h3,{"data-orientation":s.orientation,"data-state":hte(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});cte.displayName=lte;var H_="AccordionTrigger",ute=C.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=TC(Ki,n),o=kA(H_,n),i=YJe(H_,n),a=jA(n);return c.jsx(NA.ItemSlot,{scope:n,children:c.jsx(lje,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});ute.displayName=H_;var dte="AccordionContent",fte=C.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=TC(Ki,n),o=kA(dte,n),i=jA(n);return c.jsx(cje,{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}})});fte.displayName=dte;function hte(e){return e?"open":"closed"}var XJe=rte,QJe=ate,JJe=cte,mte=ute,pte=fte;const gte=XJe,EA=T.forwardRef(({className:e,...t},n)=>c.jsx(QJe,{ref:n,className:Z("border-b",e),...t}));EA.displayName="AccordionItem";const _A=T.forwardRef(({className:e,children:t,...n},r)=>c.jsx(JJe,{className:"flex",children:c.jsxs(mte,{ref:r,className:Z("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(hr,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));_A.displayName=mte.displayName;const DA=T.forwardRef(({className:e,children:t,...n},r)=>c.jsx(pte,{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:Z("pb-4 pt-0",e),children:t})}));DA.displayName=pte.displayName;function bte({context:e="editor",onFieldSelect:t,inlineFilters:n}={}){var A,L,F,H;const[r,s]=C.useState(""),[o,i]=C.useState("all");_e($=>$.isDevMode);const a=_e($=>$.card.dataSource),l=_e($=>$.card.config),u=_e($=>$.card),{autoJoinMetadata:d}=_a(u),{columns:f=[],columnGroups:h=[],isLoading:m,error:p}=pT(),g=(a==null?void 0:a.mode)==="semanticDomain"?a.semanticDomainId:void 0,{data:b}=SA(g),x=[...(l==null?void 0:l.groupByColumns)||[],...(l==null?void 0:l.metricColumns)||[]];(L=(A=l==null?void 0:l.joinPlan)==null?void 0:A.baseEntity)==null||L.name,(H=(F=d==null?void 0:d.resolvedJoinPlan)==null?void 0:F.baseEntity)==null||H.name,Jee();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"&&tte($)||$.role==="groupby"&&$.expression)return"calculated";if($.dataType==="number"||$.dataType==="integer"||$.dataType==="float"||$.dataType==="decimal"||$.dataType==="currency")return"metrics";const P=Tr($.dataType);return["date","string","boolean"].includes(P)?"dimensions":P==="number"?"metrics":"dimensions"},N=(o==="all"?y:y.filter($=>v($)===o)).reduce(($,P)=>{const Y=P.qualifiedEntityName||"Other Fields";return $[Y]||($[Y]={label:xD(P.entityName),fields:[]}),$[Y].fields.push(P),$},{}),j=Object.keys(N),E=y.filter($=>v($)==="dimensions").length,_=y.filter($=>v($)==="metrics").length,k=y.filter($=>v($)==="calculated").length,M=y.length>0&&e!=="inline-filter",D=e==="inline-filter"?"w-full":"w-[290px]";if(m)return c.jsx("div",{className:Z("flex h-full flex-col items-center justify-center py-8",D),children:c.jsx(Gc,{size:"md",color:"muted","aria-label":"Loading data"})});if(p)return c.jsxs("div",{className:Z("flex h-full flex-col items-center justify-center py-8",D),children:[c.jsx(Cl,{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:p.message||"Failed to load column data"})]});if(!a||!a.selectedEntities||a.selectedEntities.length===0)return c.jsxs("div",{className:Z("flex flex-col items-center justify-center py-8 text-center",D),children:[c.jsx(Cl,{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 R=e==="inline-filter"?"px-3 pb-3":"px-6 pb-6",I=e==="inline-filter"?"overflow-hidden":"";return c.jsxs("div",{className:Z("mt-2 flex h-full w-full grow flex-col gap-2",R,I),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(Ui,{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(yt,{className:"size-3.5"})})]}),M&&c.jsx(Bs,{defaultValue:"all",value:o,onValueChange:$=>i($),className:"mb-4",children:c.jsxs(vs,{className:"grid h-9 w-full grid-cols-4",children:[c.jsxs(Gt,{value:"all",className:"text-xs",children:["All",c.jsx("span",{className:"ml-2 text-xs font-semibold",children:y.length})]}),c.jsxs(Gt,{value:"dimensions",className:"text-xs",children:[c.jsx(D1,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:E})]}),c.jsxs(Gt,{value:"metrics",className:"text-xs",children:[c.jsx(im,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:_})]}),c.jsxs(Gt,{value:"calculated",className:"text-xs",children:[c.jsx(kD,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:k})]})]})})]}),c.jsxs(Bl,{className:"min-h-0 overflow-auto",children:[c.jsx(gte,{type:"multiple",defaultValue:j,className:"space-y-2",children:Object.entries(N).map(([$,P])=>{const Y=h.find(z=>z.entityName===$)||{entityName:$,label:P.label};return c.jsxs(EA,{value:$,className:"border-none",children:[c.jsx(_A,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{title:Y.label||Y.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:Y.label||Y.entityName}),c.jsx(Fe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:P.fields.length})]})}),c.jsx(DA,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:P.fields.map(z=>{const O=gT(z,{joinabilityMap:(b==null?void 0:b.joinabilityMap)||null,selectedFields:x,cardConfig:l,autoJoinMetadata:d});return c.jsx(FJe,{field:z,context:e,fieldState:O,onFieldSelect:t,inlineFilters:e==="inline-filter"?n:void 0},z.id)})})})]},$)})}),Object.keys(N).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(N).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(si,{orientation:"horizontal"}),c.jsx(si,{orientation:"vertical"})]})]})}function xte({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(bte,{context:e})," "]})}function yte(){const e=_e(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=Qn();C.useEffect(()=>{var m;if(!e)return;const{tableName:i,schemaName:a,databaseName:l,connectionId:u}=CA(e),d=(m=e.selectedEntities)==null?void 0:m[0],h=(d==null?void 0:d.type)==="model"&&"id"in d?d.id:"";t(u||""),n(l||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function eet(){yte();const e=X(l=>l.selectedSheetId),t=X(l=>l.selectedFrameId),n=X(l=>l.dashboard),r=X(l=>l.actions.getSelectedFrame),{setSelectedFrameId:s}=Ot(),{setCard:o}=Qn(),i=_e(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(m=>m.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),l=h)}if(l){const f=l.cards.find(h=>h.id===l.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function tet(){const e=X(o=>o.dashboard.filterLayout),{setFilterLayout:t}=Ot(),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(Xr,{children:[c.jsx(Qr,{asChild:!0,children:c.jsx(re,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0","aria-label":"Filter display settings",children:c.jsx(Nl,{className:"h-4 w-4"})})}),c.jsx(Jr,{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(jo,{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(In,{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(In,{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(Qt,{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(Qt,{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 net(){const e=X(n=>n.actions.setShowFilters),{hasEntities:t}=eet();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(tet,{}),c.jsx(re,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:c.jsx(eX,{})})]})]}),!t&&c.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[c.jsx(Cl,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),c.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&c.jsx("div",{className:"flex grow overflow-y-auto",children:c.jsx(ry,{collisionDetection:ey,children:c.jsx(sy,{items:[],strategy:RI,children:c.jsx(xte,{context:"filter"})})})})]})}function ret(){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:Z("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(jI,{filter:r}),c.jsx(rp,{filter:r})]},r.id))}):null}function set(){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:Z("",{"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(ret,{}),c.jsx(Yee,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:c.jsx(net,{})})]})}const oet=C.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-BuFxkJ0D.js"))),iet=C.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-CTa1kTTW.js"))),aet=C.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-BDsvX0Uu.js"))),cet=C.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-f5hj1d5z.js")).then(e=>({default:e.ResourceManagementPanel})));function uet({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(Ua,{FallbackComponent:eC,children:c.jsxs(jD,{dashboardProps:n,children:[c.jsx(hhe,{}),c.jsx(wA,{componentType:"surfboard",componentId:n.id}),c.jsx(vA,{children:c.jsxs(qee,{preferences:a,children:[o&&c.jsx(C.Suspense,{fallback:null,children:c.jsx(aet,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[e&&c.jsx(C.Suspense,{fallback:null,children:c.jsx(oet,{})}),c.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&c.jsx(C.Suspense,{fallback:null,children:c.jsx(cet,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),c.jsx("div",{className:"flex min-w-0 flex-1",children:c.jsxs(VT,{...n,type:"dashboard",children:[s&&c.jsx(C.Suspense,{fallback:null,children:c.jsx(iet,{})}),c.jsx(set,{})]})})]})]})]})})]})})}var det=Object.defineProperty,fet=(e,t,n)=>t in e?det(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Y0=(e,t,n)=>fet(e,typeof t!="symbol"?t+"":t,n);const het={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},met={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}},pet={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function get(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function vte(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const bet={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=vte(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},xet={stringify:e=>`${e}`,parse:e=>parseFloat(e)},yet={stringify:e=>e,parse:e=>e},I2={string:yet,number:xet,boolean:het,function:met,method:bet,json:pet},$p=Symbol.for("r2wc.render"),q0=Symbol.for("r2wc.connected"),Tu=Symbol.for("r2wc.context"),fo=Symbol.for("r2wc.props");function vet(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),l={},u={},d={},f={};for(const m of i){l[m]=Array.isArray(t.props)?"string":t.props[m];const p=get(m);d[m]=p,f[p]=m}for(const m of a)u[m]=Array.isArray(t.events)?{}:t.events[m];class h extends HTMLElement{constructor(){super(),Y0(this,o,!0),Y0(this,s),Y0(this,r,{}),Y0(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[fo].container=this.container;for(const p of i){const g=d[p],b=this.getAttribute(g),x=l[p],y=x?I2[x]:null;if(x==="method"){const v=vte(g);Object.defineProperty(this[fo].container,v,{enumerable:!0,configurable:!0,get(){return this[fo][v]},set(w){this[fo][v]=w,this[$p]()}}),this[fo][p]=y.parse(b,g,this)}y!=null&&y.parse&&b&&(this[fo][p]=y.parse(b,g,this))}for(const p of a)this[fo][p]=g=>{const b=p.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[p]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[q0]=!0,this[$p]()}disconnectedCallback(){this[q0]=!1,this[Tu]&&n.unmount(this[Tu]),delete this[Tu]}attributeChangedCallback(p,g,b){const x=f[p],y=l[x],v=y?I2[y]:null;x in l&&v!=null&&v.parse&&b&&(this[fo][x]=v.parse(b,p,this),this[$p]())}[(o=q0,s=Tu,r=fo,$p)](){this[q0]&&(this[Tu]?n.update(this[Tu],this[fo]):this[Tu]=n.mount(this.container,e,this[fo]))}}for(const m of i){const p=d[m],g=l[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[fo][m]},set(b){this[fo][m]=b;const x=g?I2[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,p,this);this.getAttribute(p)!==y&&this.setAttribute(p,y)}else this[$p]()}})}return h}function wet(e,t,n){const r=Bne.createRoot(e),s=C.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function Cet({root:e,ReactComponent:t},n){const r=C.createElement(t,n);e.render(r)}function Net({root:e}){e.unmount()}function jet(e,t={}){return vet(e,t,{mount:wet,update:Cet,unmount:Net})}const ket={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"},Eet=jet(Gee,{props:ket});function C6(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 _et(e){if(Array.isArray(e))return e}function Det(e,t,n){return(t=Oet(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Met(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 Tet(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1099
1099
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function N6(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 j6(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?N6(Object(n),!0).forEach(function(r){Det(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):N6(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function Ret(e,t){if(e==null)return{};var n,r,s=Iet(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 Iet(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 Aet(e,t){return _et(e)||Met(e,t)||Fet(e,t)||Tet()}function Pet(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 Oet(e){var t=Pet(e,"string");return typeof t=="symbol"?t:t+""}function Fet(e,t){if(e){if(typeof e=="string")return C6(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)?C6(e,t):void 0}}function $et(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function k6(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 E6(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?k6(Object(n),!0).forEach(function(r){$et(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):k6(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function Let(){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 dg(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 d1(e){return{}.toString.call(e).includes("Object")}function zet(e){return!Object.keys(e).length}function zb(e){return typeof e=="function"}function Bet(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Vet(e,t){return d1(t)||Pc("changeType"),Object.keys(t).some(function(n){return!Bet(e,n)})&&Pc("changeField"),t}function Het(e){zb(e)||Pc("selectorType")}function Uet(e){zb(e)||d1(e)||Pc("handlerType"),d1(e)&&Object.values(e).some(function(t){return!zb(t)})&&Pc("handlersType")}function Wet(e){e||Pc("initialIsRequired"),d1(e)||Pc("initialType"),zet(e)&&Pc("initialContent")}function Yet(e,t){throw new Error(e[t]||e.default)}var qet={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"},Pc=dg(Yet)(qet),G0={changes:Vet,selector:Het,handler:Uet,initial:Wet};function Get(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};G0.initial(e),G0.handler(t);var n={current:e},r=dg(Xet)(n,t),s=dg(Zet)(n),o=dg(G0.changes)(e),i=dg(Ket)(n);function a(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(d){return d};return G0.selector(u),u(n.current)}function l(u){Let(r,s,o,i)(u)}return[a,l]}function Ket(e,t){return zb(t)?t(e.current):t}function Zet(e,t){return e.current=E6(E6({},e.current),t),t}function Xet(e,t,n){return zb(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 Qet={create:Get},Jet={paths:{vs:"https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs"}};function ett(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 ttt(e){return{}.toString.call(e).includes("Object")}function ntt(e){return e||_6("configIsRequired"),ttt(e)||_6("configType"),e.urls?(rtt(),{paths:{vs:e.urls.monacoBase}}):e}function rtt(){console.warn(wte.deprecation)}function stt(e,t){throw new Error(e[t]||e.default)}var wte={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!
1100
1100
  You are using deprecated way of configuration.
1101
1101