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.BYv_Qzcq.js";import{i}from"./UriUtil.FYzIdBsL.js";import{n as a,t as o}from"./styled-components.BjKbfR5p.js";import{t as s}from"./BaseButton.eTlHCX_j.js";import{t as c}from"./useTimeout.DgWF0Nme.js";import{t as l}from"./BaseButtonTooltip.B83DZSNb.js";import{i as u,t as d}from"./DynamicButtonLabel.BTjDBnmI.js";import{t as f}from"./useResolvedWrap.DnjqnyWR.js";import{t as p}from"./BackendOperationContext.BhY2-GLf.js";import{n as m}from"./styled-components.C8Nbdcp-.js";import{t as h}from"./createDownloadLinkElement.Dn1bNzvV.js";import{t as g}from"./iconPosition.DwITqWdC.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=f(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,{fromUi:!0},x),O?.length?B():h({filename:``,url:z,enforceDownloadInNewTab:I}).click())},[t,T,y,v,x,O,B,z,I]);u({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(l,{help:S,containerWidth:!0,children:r(s,{kind:R,size:a.SMALL,disabled:t||M,onClick:V,containerWidth:!0,children:r(d,{icon:M?`spinner`:w,iconPosition:g(v.iconPosition),label:C,shortcut:k,wrap:A,addTitleTooltip:j})})}),P&&r(m,{"data-testid":`stDownloadButtonError`,children:P})]})}var y=(0,_.memo)(v);export{y as default};