import{b as e,am as L,dl as U,ay as w,az as A,aV as P,j,c as u,b4 as z,ax as N,aB as Y,aA as F,dm as V}from"./index.BdH_oWMm.js";import{m as W}from"./iconPosition.BmsruyBM.js";import{c as R}from"./createDownloadLinkElement.CMYoaLbt.js";function q(M){const{disabled:l,element:n,widgetMgr:B,endpoints:t,fragmentId:g}=M,{help:T,label:v,icon:I,ignoreRerun:h,type:p,url:k,deferredFileId:r}=n,b=n.shortcut?n.shortcut:void 0,[E,f]=e.useState(!1),[i,s]=e.useState(null),{enforceDownloadInNewTab:d=!1}=e.useContext(L),{requestDeferredFile:m}=e.useContext(U);let D=w.SECONDARY;p==="primary"?D=w.PRIMARY:p==="tertiary"&&(D=w.TERTIARY);const c=e.useMemo(()=>t.buildDownloadUrl(k),[t,k]);e.useEffect(()=>{r?.length||t.checkSourceUrlResponse(c,"Download Button")},[c,t,r]);const y=e.useCallback(async()=>{if(!m||!r){s("Deferred download not properly configured");return}f(!0),s(null);try{const o=await m(r);if(o.errorMsg){s(o.errorMsg),f(!1);return}const a=t.buildDownloadUrl(o.url);t.checkSourceUrlResponse(a,"Download Button"),R({filename:"",url:a,enforceDownloadInNewTab:d}).click()}catch(o){const a=o instanceof Error?o.message:"Download failed";s(a)}finally{f(!1)}},[m,r,t,d]),C=e.useCallback(()=>{if(l)return;h||B.setTriggerValue(n,{fromUi:!0},g),!!r?.length?y():R({filename:"",url:c,enforceDownloadInNewTab:d}).click()},[l,h,B,n,g,r,y,c,d]);A({shortcut:b,disabled:l,onActivate:C});const{clear:S,restart:x}=P(()=>{s(null)},5e3,{autoStart:!1});return e.useEffect(()=>{i?x():S()},[S,i,x]),j("div",{className:"stDownloadButton","data-testid":"stDownloadButton",children:[u(F,{help:T,containerWidth:!0,children:u(z,{kind:D,size:N.SMALL,disabled:l||E,onClick:C,containerWidth:!0,children:u(Y,{icon:E?"spinner":I,iconPosition:W(n.iconPosition),label:v,shortcut:b})})}),i&&u(V,{"data-testid":"stDownloadButtonError",children:i})]})}const H=e.memo(q);export{H as default};
