import{o as e}from"./rolldown-runtime.C0FnF6B9.js";import{r as t}from"./emotion-is-prop-valid.esm.CuYlOKOk.js";import{a as n,i as r}from"./emotion-styled.browser.esm.Dj5rZcu_.js";import{i}from"./UriUtil.Wq-or4O5.js";import{n as a,t as o}from"./styled-components.CMq9oZJa.js";import{t as s}from"./BaseButton.DiyA9nY7.js";import{t as c}from"./useTimeout.DgWF0Nme.js";import{E as l,G as u,J as d,K as f,k as p,q as m}from"./index.ByR4Z2EF.js";import{t as h}from"./createDownloadLinkElement.Bo1hqb4Q.js";import{t as g}from"./iconPosition.BjGBOrz5.js";var _=e(t(),1);function v(e){let{disabled:t,element:v,widgetMgr:y,endpoints:b,fragmentId:x}=e,{help:S,label:C,icon:w,ignoreRerun:T,type:E,url:D,deferredFileId:O}=v,k=v.shortcut?v.shortcut:void 0,A=u(v.wrap),j=!A&&!S,[M,N]=(0,_.useState)(!1),[P,F]=(0,_.useState)(null),{enforceDownloadInNewTab:I=!1}=(0,_.useContext)(i),{backendOperationClient:L}=(0,_.useContext)(p),R=o.SECONDARY;E===`primary`?R=o.PRIMARY:E===`tertiary`&&(R=o.TERTIARY);let z=(0,_.useMemo)(()=>b.buildDownloadUrl(D),[b,D]);(0,_.useEffect)(()=>{O?.length||b.checkSourceUrlResponse(z,`Download Button`)},[z,b,O]);let B=(0,_.useCallback)(async()=>{if(!L||!O){F(`Deferred download not properly configured`);return}N(!0),F(null);try{let e=await L.requestDeferredFile(O),t=b.buildDownloadUrl(e.url);b.checkSourceUrlResponse(t,`Download Button`),h({filename:``,url:t,enforceDownloadInNewTab:I}).click()}catch(e){let t=e instanceof Error?e.message:`Download failed`;F(t)}finally{N(!1)}},[L,O,b,I]),V=(0,_.useCallback)(()=>{t||(T||y.setTriggerValue(v.id,{formId:v.formId,fragmentId:x,fromUser:!0}),O?.length?B():h({filename:``,url:z,enforceDownloadInNewTab:I}).click())},[t,T,y,v,x,O,B,z,I]);m({shortcut:k,disabled:t,onActivate:V});let{clear:H,restart:U}=c(()=>{F(null)},5e3,{autoStart:!1});return(0,_.useEffect)(()=>{P?U():H()},[H,P,U]),n(`div`,{className:`stDownloadButton`,"data-testid":`stDownloadButton`,children:[r(d,{help:S,containerWidth:!0,children:r(s,{kind:R,size:a.SMALL,disabled:t||M,onClick:V,containerWidth:!0,children:r(f,{icon:M?`spinner`:w,iconPosition:g(v.iconPosition),label:C,shortcut:k,wrap:A,addTitleTooltip:j})})}),P&&r(l,{"data-testid":`stDownloadButtonError`,children:P})]})}var y=(0,_.memo)(v);export{y as default};