import{j as a}from"./jsx-runtime.D_zvdyIk.js";import{r as o}from"./index.2yJIXLcc.js";import{B as C}from"./index.D9qG4eP_.js";import{b as g}from"./cartStore.DQm8CpS2.js";import"./iconBase.Blz05Vck.js";import"./js.cookie.C0BS3qSL.js";function E({availableForSale:c,selectedVariantId:m,stylesClass:f,handle:u,pending:r,onClick:h}){const n=f,d="cursor-not-allowed flex",i=u===null?"button":"a";return c?m?a.jsx("button",{onClick:h,"aria-label":"Add to cart","aria-disabled":r?"true":"false",className:`${n}`,children:r?a.jsx(C,{className:"animate-spin w-[70px] md:w-[85px]",size:26}):"Add To Cart"}):a.jsx(i,{href:`/products/${u}`,"aria-label":"Please select an option","aria-disabled":!0,className:`${n} ${i==="button"?d:""}`,children:"Select Variant"}):a.jsx("button",{disabled:!0,"aria-disabled":!0,className:`${n} ${d}`,children:"Out Of Stock"})}function I({variants:c,availableForSale:m,stylesClass:f,handle:u,defaultVariantId:r}){const[h,n]=o.useState(null),[d,i]=o.useState(!1),[S,x]=o.useState(r),b=o.useRef(window.location.href),l=()=>{const e=new URLSearchParams(window.location.search),t=Array.from(e.entries()),s=c.find(p=>t.every(([v,j])=>p.selectedOptions.some(y=>y.name.toLowerCase()===v&&y.value===j)));x(s?.id||r)};o.useEffect(()=>{l();const e=()=>{l()},t=()=>{const p=window.location.href;p!==b.current&&(b.current=p,l())};window.addEventListener("popstate",e);const s=setInterval(t,100);return()=>{window.removeEventListener("popstate",e),clearInterval(s)}},[c,r]),o.useEffect(()=>{const e=history.pushState,t=history.replaceState;return history.pushState=function(...s){e.apply(this,s),l()},history.replaceState=function(...s){t.apply(this,s),l()},()=>{history.pushState=e,history.replaceState=t}},[]);const w=async e=>{if(e.preventDefault(),!!S){i(!0);try{const t=await g(S);n(t)}catch(t){n(t.message)}finally{i(!1)}}};return a.jsxs("form",{onSubmit:w,children:[a.jsx(E,{availableForSale:m,selectedVariantId:S,stylesClass:f,handle:u,pending:d,onClick:w}),a.jsx("p",{"aria-live":"polite",className:"sr-only",role:"status",children:h})]})}export{I as AddToCart};
