1import{c as ui,b as r,j as e,ai as Rl,a0 as Ki,B as pe,X as Po,Y as ie,d as Fl,aB as Xi,aD as Zi,aF as El,b1 as Ul,aH as Fr,S as Je,aK as Xn,a7 as Ji,R as Ll,h as Ht,c4 as Qr,aM as Ca,aN as Io,ag as Ur,i as Sr,a as Dl,u as Ol,P as wa,m as bc,a1 as Er,F as Bl,cn as yc,aZ as vc,a2 as Oi,I as ci,b4 as Nc,b5 as jc,b6 as wc,b7 as kc,b8 as Cc,b9 as Mc,ba as Pc,bb as Ic,ah as Sc,aO as Ac,al as Tc,aQ as Rc,cC as Fc,cD as Ec,cE as Uc,cF as Lc,cG as Go,cH as Dc}from"./index-CmenFvy0.js";import{u as mi,a as Oc,s as Bc,w as Vo,p as Ko,b as Na,c as $c,d as zc,e as gn,f as _c,g as Gc,h as Vc,M as Yo,i as lo,j as Ho,k as Kc,l as Yc,m as ni,n as Hc,P as Wc,o as qc,q as Xc,r as Zc,t as Jc,v as Qc,x as ed,y as td,S as Gi,z as ka,A as rd,B as sd,D as nd,C as ad,E as Wo,F as co,G as id,H as od,I as ld,J as cd,W as dd,K as ud,L as md,N as pd,O as hd,U as xd,Q as $l,V as fd,R as gd,T as qo}from"./persisted-thumbnail-reconciliation-DUpOZ09E.js";import{D as Js,E as ri,F as Yi,i as Xo,H as bd,I as Zo,r as oi,e as Pr,f as Hr,l as qn,J as yd,c as vd,a as Nd,K as jd,b as wd,L as kd,d as Cd,s as Md,N as Jo,O as Qo,Q as zl,R as Hs,S as _l,j as Pd,n as Gl,k as Ks,B as Id,P as Sd,G as Ad,g as Td,T as yo,U as Rd,W as Vl,X as Fd,Y as Ed,Z as Ud,_ as Ld,A as Dd,$ as Od,a0 as Bd,a1 as $d,a2 as el,a3 as zd,q as _d,a4 as Gd,t as Vd,a5 as uo,a6 as Kd,a7 as Yd,a8 as Hd,M as Wd}from"./design-thumbnail-staging-BAJUzXCO.js";import{b as qd,c as Xd,D as Zd}from"./design-share-format-Old-uO3s.js";import{U as So,P as vo,C as Jd,a as Qd,c as eu,d as tu}from"./design-mutations-DSP-e9Ur.js";import{a as ru,S as su,b as nu,s as tl,G as au}from"./personalization-CLHajVIA.js";import{a as Kl}from"./index-CLUFmTw0.js";import{r as iu,s as ou,X as Yl,Y as lu,Z as cu,I as du,_ as ai,$ as rl,a0 as uu,a1 as mu,a2 as pu}from"./use-store-integration-CJ-kbEiG.js";import{a9 as hu,aa as xu,ab as fu,Y as gu}from"./store-integration-GAB4azby.js";import{u as No}from"./useLazyQuery-B-xE83tG.js";import{U as bu}from"./UnpublishConfirmDialog-BL6T_P1s.js";import{M as yu}from"./MarketSetupDialog-DSy2Seax.js";import{A as Ao}from"./arrow-left-CJS58dLz.js";import{C as yn}from"./circle-alert-BPOZbYR-.js";import{C as Nn}from"./circle-check-BccD9LVl.js";import{n as Hl,c as vu,g as sl,a as To,b as mo,d as nl,e as Nu}from"./selected-variants-igcVJzbJ.js";import{R as al}from"./rocket-Dq7s2ecz.js";import{C as Ma}from"./circle-x-Bz94nwn2.js";import{L as mr}from"./loader-circle-C1v0nX7W.js";import{C as ju}from"./clock-jJ557Ylz.js";import{P as wu}from"./plus-CqbSlzMj.js";import{R as Us}from"./refresh-cw-CxeHesb2.js";import{T as Wl}from"./trash-2-DPipxcVW.js";import{Z as ku}from"./zap-0Ml0vkDU.js";import{E as ql}from"./external-link-7j5vgFDd.js";import{S as Cu}from"./store-DOMsFHQX.js";import{u as qs}from"./useMutation-Bxnq73gW.js";import{k as il,d as Mu,A as Pu,l as Xl}from"./branding-pricing-queries-DsYoqOOw.js";import{B as Xs}from"./badge-CFa2-thk.js";import{R as Iu}from"./RenderProfileBMockupGenerator-CV85jg5P.js";import{R as Zl,a as Hi}from"./radio-group-C56Lvq6O.js";import{L as vn}from"./label-Ce_OevZG.js";import{C as Zs}from"./checkbox-FnMxYA9k.js";import{T as jn,a as wn,b as kn,c as Cn}from"./tooltip-BhYPy55S.js";import{m as Rr}from"./proxy-BxkDhY6T.js";import{I as Ir}from"./image-CIt07Au_.js";import{E as Zn}from"./eye-CHLkpTUO.js";import{A as Bi}from"./index-BFYhvvcC.js";import{C as Jl}from"./chevron-left-BSw0awP4.js";import{Z as Su,a as Au}from"./zoom-out-BHJJPWve.js";import{M as Tu}from"./minimize-2-Bsua92SY.js";import{S as Ro}from"./star-SvTrqYAq.js";import{L as Ql}from"./lock-keyhole-D7Zi6c4l.js";import{C as ec}from"./crown-d1Y--EeE.js";import{S as ol,a as ll,c as cl,d as dl,b as Ru}from"./select-Di1dB2kt.js";import{G as Fu}from"./branding-designs-OWaOQZWq.js";import{G as Eu}from"./gift-xiaTiCir.js";import{L as Uu}from"./layers-Cagmyy7y.js";import{B as Lu}from"./bookmark-D2kvJhug.js";import{T as tc}from"./tag-BLO2gzSo.js";import{F as rc}from"./file-text-C2-ciIn5.js";import{C as Du}from"./chevron-up-1rc3qM2k.js";import{C as Vi}from"./circle-help-DGyPagEx.js";import{p as jo}from"./purify.es-CqxHTgmJ.js";import{c as Ou,a as Bu,b as $u,d as zu,e as _u}from"./bleach-HaZ7tmGZ.js";import{B as Gu,I as Vu,U as Ku}from"./underline-C49wTiTh.js";import{L as Yu}from"./list-CgVKUk9u.js";import{L as Hu}from"./list-ordered-BbRi2M2E.js";import{L as Wu}from"./link-2-BXJah73q.js";import{P as ul,a as ml,b as pl}from"./popover-F-0RAChz.js";import{G as qu}from"./shipping-zone-queries-BMlL4LZD.js";import{G as Xu}from"./transaction-fee-queries-tY-GwImH.js";import{U as hl}from"./undo-2-CJAdD7R_.js";import{S as Pa}from"./save-BBO903t8.js";import{A as Zu,a as Ju,b as Qu}from"./alert-BxA0dR2G.js";import{L as em}from"./lock-BVJhZ9fS.js";import{C as tm}from"./clipboard-check-DybW_jrw.js";import{S as rm}from"./square-pen-7TaiHA9V.js";import{U as xl}from"./upload-c-whMN4H.js";import"./use-toast-Vrr_3tL9.js";import"./download-B655bWyJ.js";import"./customization-personal-static-copy-S5GQel6u.js";import"./use-reduced-motion-CFYih_3w.js";import"./use-file-upload-DZGT4TC9.js";import"./file-upload-mutations-Dt4FeAFe.js";import"./info-B_MIe1dQ.js";import"./index-EAZZWxuy.js";import"./csp-nonce-C9tyM8jG.js";import"./index-Dwsz3Eqa.js";import"./copy-DuxQAxk3.js";import"./ellipsis-DMW8YppW.js";import"./premium-upgrade-intent-1CbACDTR.js";import"./catalog-theme-FMWA3Ex-.js";import"./studio-sidebar-static-copy-Cmd7EQ2q.js";import"./product-queries-DFNvjKKq.js";import"./design-management-client-BdYnGVPN.js";import"./safe-random-uuid-C5emDdYB.js";import"./fingerprint-CVKMOPMY.js";
1import"./separator-Bzb6MnIq.js";import"./textarea-DaONNPjA.js";import"./arrow-up-CCA6qmHQ.js";import"./index.module-BLHglZRz.js";import"./circle-play-mfhHWfn5.js";import"./brush-CBi8GcPI.js";import"./pencil-line-BF6T2EuG.js";import"./minus-CduxLbnH.js";import"./customization-stores-static-copy-BJAdJWSh.js";import"./progress-t_YE0hwV.js";import"./posthog-NT2w5x0H.js";import"./customer-telemetry-sanitization-DJncNWuW.js";import"./useIsomorphicLayoutEffect-Cs7ln62M.js";/** 2 * @license lucide-react v0.468.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const fl=ui("CircleArrowUp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16 12-4-4-4 4",key:"177agl"}],["path",{d:"M12 16V8",key:"1sbj14"}]]);/** 7 * @license lucide-react v0.468.0 - ISC 8 * 9 * This source code is licensed under the ISC license. 10 * See the LICENSE file in the root directory of this source tree. 11 */const Wi=ui("CloudUpload",[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"m8 17 4-4 4 4",key:"1quai1"}]]);/** 12 * @license lucide-react v0.468.0 - ISC 13 * 14 * This source code is licensed under the ISC license. 15 * See the LICENSE file in the root directory of this source tree. 16 */const sm=ui("Link",[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]]);/** 17 * @license lucide-react v0.468.0 - ISC 18 * 19 * This source code is licensed under the ISC license. 20 * See the LICENSE file in the root directory of this source tree. 21 */const nm=ui("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]);/** 22 * @license lucide-react v0.468.0 - ISC 23 * 24 * This source code is licensed under the ISC license. 25 * See the LICENSE file in the root directory of this source tree. 26 */const am=ui("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]);function im(){const[t,{loading:s}]=No(hu,{fetchPolicy:"network-only"}),[n,a]=r.useState([]),[c,d]=r.useState(null),u=r.useCallback(async(P,B)=>{if(!P||B.length===0)return a([]),[];d(null);try{const{data:R}=await t({variables:{designId:P,storeConnectionIds:B}}),A=R==null?void 0:R.validatePublishBatch,D=new Set(B),_=new Set((A==null?void 0:A.map(O=>O.storeConnectionId))??[]);if(!A||A.length!==D.size||A.some(O=>!D.has(O.storeConnectionId))||[...D].some(O=>!_.has(O)))throw new Error("Store validation could not be completed. Please try again.");return a(A),A}catch(R){const A=R instanceof Error?R:new Error("Failed to validate publishing"),D=A.message;throw d(D),console.error("Publish validation error:",A),A}},[t]),y=n.some(P=>!P.canPublish),p=n.filter(P=>!P.canPublish),x=n.filter(P=>P.canPublish),b=x.map(P=>P.storeConnectionId),C=p.map(P=>P.storeConnectionId),L=r.useCallback(()=>{a([]),d(null)},[]),k=r.useCallback(P=>{switch(P){case"STORE_DISCONNECTED":return"This store is disconnected. Please reconnect it to publish.";case"PROVIDER_COUNTRY_MISSING":return"Provider country information is missing. Please select a provider with a valid location.";case"MARKET_PENDING":case"MARKET_SKIPPED":case"MARKET_FAILED":case"MARKET_NOT_CONFIGURED":return"Your store doesn't sell to your provider's country. Add the provider's country to your store's selling countries to publish this product.";case"COUNTRY_MISMATCH":return"Provider and store are in different countries. PrintaRex uses local fulfillment - providers can only ship within their own country.";default:return"Unable to publish to this store."}},[]),K=r.useCallback(P=>{switch(P){case"STORE_DISCONNECTED":return"Reconnect Store";case"PROVIDER_COUNTRY_MISSING":return"Select Provider";case"MARKET_PENDING":case"MARKET_SKIPPED":case"MARKET_FAILED":case"MARKET_NOT_CONFIGURED":return"Set Up Market";case"COUNTRY_MISMATCH":return"Choose Different Store";default:return null}},[]);return{validateStores:u,results:n,loading:s,error:c,hasErrors:y,errorResults:p,passedResults:x,publishableStoreIds:b,blockedStoreIds:C,reset:L,getErrorMessage:k,getErrorAction:K}}const om={EG:"ðªð¬",AE:"ð¦ðª",SA:"ð¸ð¦",US:"ðºð¸",GB:"ð¬ð§",DE:"ð©ðª",FR:"ð«ð·",IT:"ð®ð¹",ES:"ðªð¸",AU:"ð¦ðº",CA:"ð¨ð¦",JP:"ð¯ðµ",CN:"ð¨ð³",IN:"ð®ð³",BR:"ð§ð·",MX:"ð²ð½",KR:"ð°
26ð·",SG:"ð¸ð¬",NL:"ð³ð±",SE:"ð¸ðª"},lm={AE:"United Arab Emirates",SA:"Saudi Arabia",EG:"Egypt"},cm={AE:"AED",SA:"SAR",EG:"EGP"},ja=t=>t&&om[t.toUpperCase()]||"ð",dm=new Set(["AE","EG","SA"]),po=t=>t?dm.has(t.toUpperCase()):!1,ho=t=>t==="MARKET_PENDING"||t==="MARKET_SKIPPED"||t==="MARKET_FAILED"||t==="MARKET_NOT_CONFIGURED",um=t=>({STORE_DISCONNECTED:"Store disconnected",PROVIDER_COUNTRY_MISSING:"Provider not set",MARKET_PENDING:"Market setup required",MARKET_SKIPPED:"Market setup required",MARKET_FAILED:"Market setup required",MARKET_NOT_CONFIGURED:"Market setup required",COUNTRY_MISMATCH:"Country mismatch"})[t||""]||"Unavailable",mm=({open:t,onOpenChange:s,errorResults:n,passedResults:a,onProceedWithValid:c,onCancel:d,onRetryValidation:u,getErrorMessage:y,getErrorAction:p})=>{const[x,b]=r.useState(!1),[C,L]=r.useState(null),[k,K]=r.useState(""),[P,B]=r.useState("SHOPIFY"),[R,A]=r.useState(null),{createMarket:D,loading:_}=iu(),{skipMarket:O,loading:I}=ou();if(!t)return null;const ue=a.length>0,me=n.length>0&&a.length===0,Se=n.length+a.length,be=n.find(w=>ho(w.errorCode)),G=n.find(w=>w.errorCode==="COUNTRY_MISMATCH"&&po(w.storeCountry)),ye=n.find(w=>w.errorCode==="COUNTRY_MISMATCH"&&!po(w.storeCountry)),we=w=>{const M=w.providerCountry||w.storeCountry;if(!M){ie.error("Market setup country is unavailable. Please refresh the store validation and try again.");return}L(w.storeConnectionId),K(M.toUpperCase()),B(w.storePlatform==="WOOCOMMERCE"?"WOOCOMMERCE":"SHOPIFY"),A(null),b(!0)},re=async w=>{if(!C)return;A(null);const M=await D(C,w);(M==null?void 0:M.status)==="CONFIGURED"?(ie.success("Market created successfully",{description:"You can now publish your products."}),b(!1),u&&u()):A((M==null?void 0:M.errorMessage)||"Failed to create market. Please try again.")},X=async()=>{if(C){A(null);try{await O(C)?(ie.info("Market setup skipped",{description:"You can configure your market later from your store settings."}),b(!1)):A("Failed to skip market setup. Please try again.")}catch(w){A(w.message||"An unexpected error occurred. Please try again.")}}},Q=lm[k]||k,S=cm[k]??"";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"absolute inset-0 z-50 bg-white flex flex-col animate-in fade-in slide-in-from-right-4 duration-200",children:[e.jsxs("div",{className:"flex items-center gap-3 px-5 py-4 border-b border-slate-100",children:[e.jsx("button",{type:"button",onClick:d,className:"h-8 w-8 rounded-lg hover:bg-slate-100 flex items-center justify-center transition-colors",children:e.jsx(Ao,{className:"h-4 w-4 text-slate-600"})}),e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-red-100 flex items-center justify-center",children:e.jsx(yn,{className:"h-5 w-5 text-red-600"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-slate-900",children:me?"Cannot Publish":"Some Stores Blocked"}),e.jsxs("p",{className:"text-xs text-slate-500",children:[n.length," of ",Se," store",Se===1?"":"s"," unavailable"]})]})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-5 space-y-4",children:[be&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-xl p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rl,{className:"h-4 w-4 text-amber-600"}),e.jsx("p",{className:"text-sm font-medium text-amber-900",children:"Market setup required"})]}),e.jsxs("p",{className:"text-xs text-amber-800",children:["Your provider is based in ",e.jsx("strong",{children:be.providerCountryName||"your selected country"})," and PrintaRex fulfills orders locally â products are made and shipped within the provider's country. Your store doesn't currently sell to ",be.providerCountryName||"that country",". Add it to your selling countries to enable checkout."]}),e.jsx("p",{className:"text-xs text-slate-500",children:"Alternatively, you can go back to your design and select a provider from your store's country."})]}),ye&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-xl p-4 space-y-3",children:[e.jsxs("p",{className:"text-sm font-medium text-amber-900",children:["PrintaRex doesn't operate in ",ye.storeCountryName||"this country"," yet"]}),e.jsxs("div",{className:"flex items-center gap-3 justify-center py-2",children:[e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsx("span",{className:"text-2xl",children:ja(ye.providerCountry)}),e.jsx("span",{className:"text-xs font-medium text-slate-700",children:ye.providerCountryName||ye.providerCountry}),e.jsx("span",{className:"text-[10px] text-slate-500",children:"Provider"})]}),e.jsx(Ki,{className:"h-4 w-4 text-red-400 mx-2"}),e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsx("span",{className:"text-2xl",children:ja(ye.storeCountry)}),e.jsx("span",{className:"text-xs font-medium text-slate-700",children:ye.storeCountryName||ye.storeCountry}),e.jsx("span",{className:"text-[10px] text-slate-500",children:"Store"})]})]}),e.jsxs("p",{className:"text-xs text-amber-800",children:["PrintaRex currently operates in ",e.jsx("strong",{children:"UAE"}),", ",e.jsx("strong",{children:"Egypt"}),", and"," ",e.jsx("strong",{children:"Saudi Arabia"}),". Your store is based in"," ",ye.storeCountryName||"an unsupported country",", so orders cannot be fulfilled there. Connect a store from a supported country to publish."]})]}),G&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-xl p-4 space-y-3",children:[e.jsx("p",{className:"text-sm font-medium text-amber-900",children:"Your provider can only fulfill orders locally"}),e.jsxs("div",{className:"flex items-center gap-3 justify-center py-2",children:[e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsx("span",{className:"text-2xl",children:ja(G.providerCountry)}),e.jsx("span",{className:"text-xs font-medium text-slate-700",children:G.providerCountryName||G.providerCountry}),e.jsx("span",{className:"text-[10px] text-slate-500",children:"Provider"})]}),e.jsx(Ki,{className:"h-4 w-4 text-red-400 mx-2"}),e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsx("span",{className:"text-2xl",children:ja(G.storeCountry)}),e.jsx("span",{className:"text-xs font-medium text-slate-700",children:G.storeCountryName||G.storeCountry}),e.jsx("span",{className:"text-[10px] text-slate-500",children:"Store"})]})]}),e.jsxs("p",{className:"text-xs text-amber-800",children:[e.jsx("strong",{children:G.providerName})," is based in"," ",G.providerCountryName," and ships within"," ",G.providerCountryName," only. To publish to your"," ",G.storeCountryName," store, select a provider from"," ",G.storeCountryName," in the design editor."]})]}),!G&&!ye&&n.some(w=>w.errorCode==="PROVIDER_COUNTRY_MISSING")&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-xl p-4",children:[e.jsx("p",{className:"text-sm font-medium text-amber-900 mb
26-1",children:"Provider selection required"}),e.jsx("p",{className:"text-xs text-amber-800",children:"This design needs a provider assigned before publishing. Go back to the design editor and select a provider in the Prices step."})]}),e.jsx("div",{className:"space-y-2",children:n.map(w=>{const M=p(w.errorCode),E=ho(w.errorCode);return e.jsxs("div",{className:"p-3 rounded-xl bg-red-50/70 border border-red-100",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-xl",children:ja(w.storeCountry)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-slate-900 text-sm truncate",children:w.storeName||"Unknown Store"}),e.jsx("p",{className:"text-xs text-red-600",children:w.errorCode==="COUNTRY_MISMATCH"&&!po(w.storeCountry)?"Country not supported":um(w.errorCode)})]}),E&&M?e.jsx(pe,{variant:"outline",size:"sm",className:"shrink-0 text-xs h-8 border-primary/30 text-primary hover:bg-primary/5",onClick:()=>we(w),children:M}):e.jsx(Po,{className:"h-4 w-4 text-red-400 shrink-0"})]}),w.errorCode!=="COUNTRY_MISMATCH"&&!ho(w.errorCode)&&w.errorMessage&&e.jsx("p",{className:"text-xs text-slate-500 mt-2 ml-9",children:w.errorMessage})]},w.storeConnectionId)})}),ue&&e.jsxs("div",{className:"space-y-2 pt-3 border-t border-slate-100",children:[e.jsxs("p",{className:"text-xs font-medium text-slate-400 uppercase tracking-wide mb-2",children:["Ready to publish (",a.length,")"]}),a.map(w=>e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl bg-emerald-50/70 border border-emerald-100",children:[e.jsx("span",{className:"text-xl",children:ja(w.storeCountry)}),e.jsx("p",{className:"font-medium text-slate-900 text-sm truncate flex-1",children:w.storeName||"Store"}),e.jsx(Nn,{className:"h-4 w-4 text-emerald-500 shrink-0"})]},w.storeConnectionId))]})]}),e.jsxs("div",{className:"p-5 pt-4 border-t border-slate-100 flex gap-3 bg-slate-50/50",children:[e.jsx(pe,{variant:"outline",onClick:d,className:"flex-1 h-11 rounded-xl",children:me?"Close":"Go Back"}),ue&&c&&e.jsxs(pe,{onClick:c,className:"flex-1 h-11 rounded-xl bg-primary hover:bg-primary/90",children:["Publish ",a.length," Store",a.length===1?"":"s"]})]})]}),e.jsx(yu,{open:x,onOpenChange:b,countryCode:k,countryName:Q,currencyCode:S,onCreateMarket:re,onSkip:X,isCreating:_,isSkipping:I,error:R,platform:P})]})},$i={SHOPIFY:"/assets/sales-channels/shopify.svg",WOOCOMMERCE:"/assets/sales-channels/woocommerce.svg",AMAZON:"/assets/sales-channels/amazon.svg",NOON:"/assets/sales-channels/noon.svg",TIKTOK:"/assets/sales-channels/tiktok.svg",WIX:"/assets/sales-channels/wix.svg"},pm={SHOPIFY:"from-[#96bf48]/10 to-[#96bf48]/5",WOOCOMMERCE:"from-[#9b5c8f]/10 to-[#9b5c8f]/5",AMAZON:"from-[#ff9900]/10 to-[#ff9900]/5",TIKTOK:"from-[#010101]/8 to-[#010101]/4",WIX:"from-[#0C6EFC]/10 to-[#0C6EFC]/5"};function gl({storeId:t,value:s,selectedVariantCount:n,locked:a,onChange:c}){const d=`amazon-listing-mode-${t}`;let u=null;return a==="closed"?u="This product is closed on Amazon. Publishing again relists it with its saved listing type. Delete it from this store first to change the type.":a==="listed"?u="The listing type of a listed Amazon product cannot be changed here. Delete it from this store first, then publish again with the new type.":s==="AUTOMATIC"?u=n===0?"Automatic needs at least one selected variant. Keep at least one color/size combination selected before publishing.":n===1?"Automatic: your 1 selected color/size combination will publish as a standalone single-variant listing.":`Automatic: your ${n} selected color/size combinations will publish as a parent multi-variant listing with ${n} child listings.`:s==="STANDALONE"&&n!==1&&(u="Standalone publishes exactly one selected variant. Keep exactly one color/size combination selected, or choose Automatic / Parent listing."),e.jsxs("div",{className:"mt-1.5 flex flex-col gap-0.5",children:[e.jsx("label",{htmlFor:d,className:"text-[10px] font-semibold text-slate-500 uppercase tracking-[0.06em]",children:"Amazon listing type"}),e.jsxs("select",{id:d,value:s,disabled:a!==void 0,onChange:y=>c(y.target.value),className:"h-8 w-full max-w-[280px] rounded-[14px] border border-slate-200 bg-white px-2 text-[11px] text-slate-700 focus:outline-none focus:ring-2 focus:ring-[#15B6
267F]/20 disabled:cursor-not-allowed disabled:opacity-60",children:[e.jsx("option",{value:"AUTOMATIC",children:"Automatic (recommended)"}),e.jsx("option",{value:"STANDALONE",children:'Standalone "Single-variant listing" â one buyable listing'}),e.jsx("option",{value:"PARENT_CHILD",children:'Parent Listing "Multi-variant listing" â one child listing per variant'})]}),u&&e.jsx("p",{className:`text-[10px] leading-snug ${s==="STANDALONE"&&n!==1?"text-amber-600":"text-slate-400"}`,children:u})]})}function hm({open:t,onOpenChange:s,designId:n,designRevision:a,sourceDesignId:c,productTitle:d,productDescription:u,productType:y,tags:p,variantPrices:x,providerId:b,providerConfigId:C,providerName:L,printingTechnology:k,brandingItems:K,selectedColors:P,selectedSizes:B,initialSelectedStoreIds:R,initialSelectionKey:A,onSuccess:D}){const _=Fl(),{stores:O,loading:I,refetch:ue}=Yl(n,{skip:!t}),{hasPaymentMethod:me,loading:Se}=lu({skip:!t}),{publishAsync:be,retryPublishingJobs:G,isPublishing:ye,error:we,progress:re,failedPublishingJobs:X,resetPublishing:Q}=cu(t?n:null,a??null),{unpublishFromStore:S,loading:w}=du(),M=r.useMemo(()=>Hl(P,B),[P,B]),E=r.useMemo(()=>vu(x,M.selectedColors,M.selectedSizes),[x,M.selectedColors,M.selectedSizes]),{validateStores:Me,loading:Y,errorResults:Ee,passedResults:Be,publishableStoreIds:Ae,reset:Ze,getErrorMessage:Ye,getErrorAction:kt}=im(),[he,ne]=r.useState(!1),[ee,nt]=r.useState(new Set),[Ue,Le]=r.useState(new Set),[Te,$e]=r.useState({}),[Ke,pt]=r.useState(null),[ot,at]=r.useState(null),[He,De]=r.useState(!1),[Gt,es]=r.useState(new Set),ke=r.useRef(null),lt=mu(ot,we),[Wt,Qe]=r.useState({open:!1,publishedProductId:null,storeName:""}),ht=r.useMemo(()=>new Set(X.map(N=>N.storeConnectionId)),[X]),rr=r.useRef(O);r.useEffect(()=>{rr.current=O},[O]);const Oe=r.useCallback(N=>N.closedAmazonListingMode??Te[N.id]??N.amazonDefaultListingMode??"AUTOMATIC",[Te]),St=r.useCallback((N,U)=>{$e(ae=>({...ae,[N]:U}))},[]),ze=r.useMemo(()=>O.filter(N=>!N.isPublished&&N.status==="CONNECTED"&&!ht.has(N.id)),[ht,O]),it=r.useMemo(()=>O.filter(N=>N.isPublished&&!ht.has(N.id)),[ht,O]);r.useEffect(()=>{if(!t){pt(null);return}if(I||!(R!=null&&R.length))return;const N=A||R.join("|");if(Ke===N)return;const U=new Set(R);nt(new Set(ze.filter(ae=>U.has(ae.id)).map(ae=>ae.id))),Le(new Set(it.filter(ae=>U.has(ae.id)).map(ae=>ae.id))),pt(N)},[Ke,ze,R,A,I,t,it]);const Lt=r.useCallback((N,U)=>{nt(ae=>{const le=new Set(ae);return U?le.add(N):le.delete(N),le})},[]),xt=r.useCallback((N,U)=>{Le(ae=>{const le=new Set(ae);return U?le.add(N):le.delete(N),le})},[]),et=r.useCallback(()=>{nt(new Set(ze.map(N=>N.id)))},[ze]),Lr=r.useCallback(()=>{nt(new Set)},[]),Dr=r.useCallback(async N=>{es(U=>new Set(U).add(N.id));try{await G([N.id])}catch(U){const ae=U instanceof Error?U.message:"Could not retry this store.";ie.error(ae)}finally{es(U=>{const ae=new Set(U);return ae.delete(N.id),ae})}},[G]),Dt=r.useCallback((N,U,ae)=>{N&&Qe({open:!0,publishedProductId:N,storeName:U,platform:ae})},[]),qt=r.useCallback(async()=>{if(!Wt.publishedProductId)return;await S(Wt.publishedProductId,Wt.storeName)&&(Qe({open:!1,publishedProductId:null,storeName:""}),ue())},[Wt,S,ue]),lr=r.useCallback(N=>{var ae;const U={};for(const le of rr.current){if(le.platform!=="AMAZON"||!N.includes(le.id))continue;const ct=le.isPublished?((ae=le.publishedProduct)==null?void 0:ae.amazonListingMode)??"PARENT_CHILD":null;U[le.id]=ct??Oe(le)}return U},[Oe]),Ct=r.useCallback(N=>{if(ke.current)return ke.current;const U=be({designId:n,designRevision:a,sourceDesignId:c,storeConnectionIds:N,title:d,descriptionHtml:u,productType:y,tags:p,variantPrices:x,providerId:b,providerConfigId:C,providerName:L,printingTechnology:k,brandingItems:K,selectedColors:M.selectedColors,selectedSizes:M.selectedSizes,amazonListingModes:lr(N)}).finally(()=>{ke.current=null});return ke.current=U,U},[lr,K,n,a,M.selectedColors,M.selectedSizes,k,u,d,y,C,b,L,be,c,p,x]),yr=r.useCallback(async N=>{try{return await Me(n,N)}catch{return ie.error("Publishing checks are unavailable. Please try again."),null}},[n,Me]),Mt=async()=>{const N=new Set([...ee,...Ue]);if(N.size===0)return;if(!b||!C){ie.error("Provider information is missing. Cannot publish without provider data.");return}const U=rr.current.find(le=>N.has(le.id)&&!le.isPublished&&!le.closedAmazonListingMode&&le.platform==="AMAZON"&&Oe(le)==="STANDALONE"&&E!==1);if(U){ie.error(`A standalone Amazon listing publishes exactly one selected variant, but ${E} are selected for ${U.shopName||U.shopDomain}. Keep exactly one color/size combination selected, or choose Automatic / Parent listing.`);return}const ae=await yr(Array.from(N));if(ae){if(ae.some(le=>!le.canPublish)){ne(!0);return}await Ct(Array.from(N))}},At=r.useCallback(async()=>{ne(!1),Ae.length>0&&await Ct(Ae)},[Ct,Ae]),Tt=r.useCallback(()=>{Q(),Ze(),nt(new Set),Le(new Set),$e({}),es(new Set),ne(!1),at(null)},[Q,Ze]),Vt=()=>{Y||(s(!1),Tt())},Kt=()=>{s(!1),Tt(),_("/dashboard/catalog/my-products",{state:{refreshDesigns:!0,trackedDesignId:n,trackedPublishingJobs:(re==null?void 0:re.jobs)??[]}})},Xt=r.useCallback(async()=>
26{if(!He){De(!0),at(null);try{try{await ue()}catch(N){console.warn("[StoreSelectionModal] Failed to refresh stores after publish",N)}await(D==null?void 0:D()),s(!1),Tt()}catch(N){const U=N instanceof Error?N.message:"Publishing finished, but My Products could not be opened automatically.";at(U),ie.error(U)}finally{De(!1)}}},[He,s,D,ue,Tt]),Nt=I||Se,Ve=x&&x.length>0&&x.every(N=>N.price>0);return e.jsxs(Xi,{open:t,onOpenChange:N=>{N||Vt()},children:[e.jsxs(Zi,{className:"sm:max-w-[500px] max-h-[85vh] p-0 overflow-hidden bg-white rounded-2xl border border-slate-200/60 shadow-[0_25px_50px_-12px_rgba(0,0,0,0.15),0_0_0_1px_rgba(0,0,0,0.03)] relative flex flex-col",onPointerDownOutside:N=>N.preventDefault(),onInteractOutside:N=>N.preventDefault(),children:[e.jsxs(Kl,{children:[e.jsx(El,{children:"Publish to Stores"}),e.jsxs(Ul,{children:["Select stores to publish ",d]})]}),e.jsxs("div",{className:"relative flex-shrink-0 overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-primary/[0.06] via-emerald-50/80 to-teal-50/40"}),e.jsx("div",{className:"absolute top-0 right-0 w-32 h-32 bg-gradient-to-bl from-primary/10 to-transparent rounded-full -translate-y-1/2 translate-x-1/4 blur-2xl"}),e.jsx("div",{className:"absolute bottom-0 left-0 w-24 h-24 bg-gradient-to-tr from-teal-400/8 to-transparent rounded-full translate-y-1/2 -translate-x-1/4 blur-xl"}),e.jsx("div",{className:"relative px-5 pt-4 pb-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-9 w-9 rounded-xl bg-gradient-to-br from-primary to-emerald-600 flex items-center justify-center shadow-[0_2px_8px_rgba(21,182,127,0.35)]",children:e.jsx(al,{className:"h-4 w-4 text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h2",{className:"text-[15px] font-semibold text-slate-900 tracking-[-0.01em]",children:"Publish to Stores"}),e.jsx("p",{className:"text-[12px] text-slate-500 mt-0.5 truncate font-medium",children:d})]})]})}),e.jsx("div",{className:"h-px bg-gradient-to-r from-transparent via-primary/15 to-transparent"})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3",children:[e.jsxs("div",{className:"space-y-1.5 mb-3",children:[!Nt&&!Ve&&e.jsxs("div",{className:"flex items-center gap-2.5 px-3 py-2.5 rounded-xl bg-red-50/80 border border-red-100/80",children:[e.jsx("div",{className:"h-6 w-6 rounded-lg bg-red-100 flex items-center justify-center flex-shrink-0",children:e.jsx(Ma,{className:"h-3.5 w-3.5 text-red-500"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[12px] font-semibold text-red-800 leading-tight",children:"Pricing required"}),e.jsx("p",{className:"text-[11px] text-red-600/70 leading-snug",children:"Set prices before publishing"})]})]}),!Nt&&Ve&&!me&&e.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2.5 rounded-xl bg-amber-50/80 border border-amber-100/80",children:[e.jsx("div",{className:"h-6 w-6 rounded-lg bg-amber-100 flex items-center justify-center flex-shrink-0 mt-px",children:e.jsx(Fr,{className:"h-3.5 w-3.5 text-amber-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[12px] font-semibold text-amber-800 leading-tight",children:"No payment method"}),e.jsxs("p",{className:"text-[11px] text-amber-600/80 mt-0.5 leading-snug",children:["Add a payment method to avoid delays when orders arrive."," ",e.jsxs("a",{href:"/dashboard/billing",className:"inline-flex items-center gap-0.5 ml-1 font-semibold text-amber-700 hover:text-amber-900 underline underline-offset-2 transition-colors",children:["Add now",e.jsx(Ki,{className:"h-2.5 w-2.5"})]})]})]})]}),lt.map(N=>e.jsxs("div",{className:N.kind==="navigation"?"flex items-start gap-2.5 px-3 py-2.5 rounded-xl bg-amber-50/80 border border-amber-100/80":"flex items-start gap-2.5 px-3 py-2.5 rounded-xl bg-red-50/80 border border-red-100/80",children:[e.jsx(Fr,{className:N.kind==="navigation"?"h-4 w-4 text-amber-600 flex-shrink-0 mt-px":"h-4 w-4 text-red-600 flex-shrink-0 mt-px"}),e.jsxs("div",{children:[e.jsx("p",{className:N.kind==="navigation"?"text-[12px] font-semibold text-amber-800":"text-[12px] font-semibold text-red-800",children:N.title}),e.jsx("p",{className:N.kind==="navigation"?"text-[11px] text-amber-700/80 mt-0.5":"text-[11px] text-red-700/80 mt-0.5",children:N.message})]})]},N.kind))]}),re&&(()=>{const N=re.isComplete,U=re.completed,ae=re.failed,le=re.jobs.filter($=>ai($)==="retry-reconciliation").length,ct=re.jobs.filter($=>ai($)==="reconciliation-blocked").length,Pt=N&&ae===0&&U>0,Yt=N&&U===0&&ae>0&&le===0&&ct===0,Rt=U+ae;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-center pt-1",children:[e.jsx("div",{className:`inline-flex items-center justify-center h-16 w-16 rounded-2xl mx-auto mb-3 transition-all duration-500 ${N?Pt?"bg-gradient-to-br from-emerald-100 to-emerald-50 shadow-[0_0_0_4px_rgba(16,185,129,0.1)]":Yt?"bg-gradient-to-br from-red-100 to-red-50 shadow-[0_0_0_4px_rgba(239,68,68,0.08)]":"bg-gradient-to-br from-amber-100 to-amber-50 shadow-[0_0_0_4px_rgba(245,158,11,0.08)]":"bg-gradient-to-br from-primary/10 to-emerald-50 shadow-[0_0_0_4px_rgba(21,182,127,0.08)]"}`,children:N?Pt?e.jsx(Nn,{className:"h-7 w-7 text-emerald-600"}):Yt?e.jsx(Ma,{className:"h-7 w-7 text-red-500"}):e.jsx(Fr,{className:"h-7 w-7 text-amber-500"}):e.jsx(mr,{className:"h-7 w-7 text-primary animate-spin"})}),e.jsx("h3",{className:"text-[15px] font-semibold text-slate-900 tracking-[-0.01em]",children:N?ct>0?"Published â Manual Recovery Needed":le>0?"Published â Finalizing Tracking":Pt?"Published Successfully!":Yt?"Publishing Failed":"Partially Published":re.currentStep||"Publishing..."}),e.jsx("p",{className:"text-[12px] text-slate-500 mt-1 font-medium",children:N?ct>
260?"The store accepted your product, but automated recovery is blocked. Contact support before publishing again.":le>0?"The store accepted your product. Local tracking recovery is in progress.":Pt?`${U} store${U===1?"":"s"} published`:Yt?`Failed to publish to ${ae} store${ae===1?"":"s"}`:`${U} succeeded, ${ae} failed`:re.currentStepMessage||`${Rt} of ${re.total} store${re.total===1?"":"s"}`}),!N&&e.jsx("div",{className:"mt-3 mx-auto max-w-[320px] rounded-xl border border-primary/15 bg-primary/[0.06] px-3 py-2 text-left",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ju,{className:"mt-0.5 h-3.5 w-3.5 flex-shrink-0 text-primary"}),e.jsxs("p",{className:"text-[11px] leading-relaxed text-slate-700",children:[e.jsx("span",{className:"font-semibold text-slate-900",children:"Publishing started."})," ","You can close this window and track progress from My Products."]})]})})]}),e.jsxs("div",{className:"px-1",children:[e.jsx("div",{className:"flex gap-1",children:Array.from({length:re.total}).map(($,de)=>{const ce=re.jobs[de],xe=(ce==null?void 0:ce.status)==="COMPLETED",f=(ce==null?void 0:ce.status)==="FAILED",j=!xe&&!f&&de<Rt+1&&!N;return e.jsx("div",{className:`h-1.5 flex-1 rounded-full transition-all duration-700 ease-out ${xe?"bg-emerald-400":f?"bg-red-400":j?"bg-primary/40 animate-pulse":"bg-slate-100"}`},`step-${de}`)})}),e.jsxs("p",{className:"text-[11px] text-slate-400 text-right mt-1.5 font-medium tabular-nums",children:[Rt,"/",re.total]})]}),re.jobs.length>0&&e.jsx("div",{className:"space-y-1.5 max-h-48 overflow-y-auto",children:re.jobs.map($=>e.jsx(xm,{job:$},$.id))})]})})(),!re&&(Nt?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(N=>e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl border border-slate-100 bg-slate-50/50",children:[e.jsx(Je,{className:"h-4 w-4 rounded"}),e.jsx(Je,{className:"h-9 w-9 rounded-lg"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx(Je,{className:"h-3.5 w-28 rounded"}),e.jsx(Je,{className:"h-2.5 w-20 rounded"})]}),e.jsx(Je,{className:"h-5 w-12 rounded-full"})]},`step-${N}`))}):O.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"inline-flex items-center justify-center h-14 w-14 rounded-2xl bg-gradient-to-br from-slate-50 to-slate-100 ring-1 ring-slate-200/80 mx-auto mb-3 shadow-soft",children:e.jsx(Rl,{className:"h-6 w-6 text-slate-400"})}),e.jsx("h3",{className:"font-semibold text-slate-900 text-[14px] tracking-[-0.01em]",children:"No stores connected"}),e.jsx("p",{className:"text-[12px] text-slate-500 mt-1 mb-4 max-w-[240px] mx-auto leading-relaxed",children:"Connect your first e-commerce store to start selling your designs"}),e.jsxs(pe,{onClick:()=>{s(!1),globalThis.location.href="/dashboard/stores"},className:"bg-primary hover:bg-primary/90 text-white gap-2 h-9 rounded-lg px-5 text-[12px] font-semibold shadow-primary",children:[e.jsx(wu,{className:"h-3.5 w-3.5"}),"Connect Store"]})]}):e.jsxs(e.Fragment,{children:[X.length>0&&e.jsxs("div",{className:"mb-3",children:[e.jsxs("div",{className:"mb-1.5 flex items-center gap-2",children:[e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-red-400"}),e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-slate-500",children:"Needs attention"}),e.jsx("span",{className:"rounded bg-red-50 px-1.5 py-px text-[10px] font-semibold tabular-nums text-red-600",children:X.length})]}),e.jsx("div",{className:"space-y-1",children:X.map(N=>{var Yt,Rt,$;const U=O.find(de=>de.id===N.storeConnectionId),ae=(U==null?void 0:U.shopName)||(U==null?void 0:U.shopDomain)||((Yt=N.storeConnection)==null?void 0:Yt.shopName)||((Rt=N.storeConnection)==null?void 0:Rt.shopDomain)||"Store",le=(U==null?void 0:U.platform)||(($=N.storeConnection)==null?void 0:$.platform),ct=Gt.has(N.id),Pt=rl([N]).length>0;return e.jsxs("div",{className:"flex items-center gap-2.5 rounded-xl border border-red-100 bg-red-50/50 p-2",children:[e.jsx("div",{className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg bg-white shadow-sm ring-1 ring-red-100",children:le&&$i[le]?e.jsx("img",{src:$i[le],alt:le,className:"h-4 w-4 object-contain"}):e.jsx(Fr,{className:"h-4 w-4 text-red-500"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-[12px] font-medium leading-tight text-slate-800",children:ae}),e.jsx("p",{className:"mt-px line-clamp-2 text-[10px] leading-4 text-red-600",children:N.errorMessage||N.stepMessage||"Publishing failed for this store."})]}),Pt?e.jsxs(pe,{type:"button",size:"sm",onClick:()=>void Dr(N),disabled:ye||ct,"aria-busy":ct,"aria-label":`Retry publishing to ${ae}`,className:"h-8 flex-shrink-0 gap-1.5 rounded-lg bg-slate-900 px-3 text-[11px] font-semibold text-white hover:bg-slate-800",children:[ct?e.jsx(mr,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Us,{className:"h-3.5 w-3.5"}),ct?"Retrying":"Retry"]}):e.jsx("span",{className:"flex-shrink-0 text-[10px] font-semibold text-red-600",children:"Contact support"})]},N.id)})})]}),it.length>0&&e.jsxs("div",{className:"mb-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-emerald-400"}),e.jsx("span",{className:"text-[11px] font-semibold text-slate-500 uppercase tracking-[0.08em]",children:"Live"}),e.jsx("span",{className:"text-[10px] text-slate-400 font-semibold bg-slate-100 rounded px-1.5 py-px tabular-nums",children:it.length})]}),e.jsx("span",{className:"text-[10px] text-slate-400 font-medium",children:"Select to re-sync"})]}),e.jsx("div",{className:"space-y-1",children:it.map(N=>{var ae;
26const U=Ue.has(N.id);return e.jsxs("div",{className:`group flex flex-col p-2 rounded-xl transition-all duration-200 ${U?"bg-amber-50/70 border border-amber-200/80":"bg-emerald-50/30 border border-emerald-100/60 hover:border-emerald-200/80 hover:bg-emerald-50/50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>xt(N.id,!U),onKeyDown:le=>{(le.key==="Enter"||le.key===" ")&&(le.preventDefault(),xt(N.id,!U))},className:"flex flex-1 min-w-0 items-center gap-2.5 cursor-pointer",children:[e.jsx("div",{className:`h-4 w-4 rounded-md border-[1.5px] flex items-center justify-center transition-all flex-shrink-0 ${U?"border-amber-500 bg-amber-500 shadow-[0_0_0_2px_rgba(245,158,11,0.12)]":"border-slate-300/80 group-hover:border-slate-400"}`,children:U&&e.jsx(Us,{className:"h-2 w-2 text-white"})}),e.jsx("div",{className:"h-8 w-8 rounded-lg bg-white ring-1 ring-slate-200/60 flex items-center justify-center flex-shrink-0 shadow-sm",children:e.jsx("img",{src:$i[N.platform],alt:N.platform,className:"h-4 w-4 object-contain"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-slate-800 text-[12px] truncate leading-tight",children:N.shopName||N.shopDomain}),e.jsx("p",{className:"text-[10px] text-slate-400 truncate mt-px",children:N.shopDomain})]}),e.jsx("span",{className:`text-[10px] font-semibold px-2 py-0.5 rounded-md transition-all ${U?"bg-amber-100 text-amber-700":"bg-emerald-100/80 text-emerald-700"}`,children:U?"Sync":"Live"})]}),e.jsx("button",{type:"button",onClick:()=>{var le;return Dt((le=N.publishedProduct)==null?void 0:le.id,N.shopName||N.shopDomain,N.platform)},disabled:w,className:"h-6 w-6 rounded-md flex-shrink-0 flex items-center justify-center text-slate-300 hover:text-red-500 hover:bg-red-50 transition-all opacity-0 group-hover:opacity-100",children:e.jsx(Wl,{className:"h-3 w-3"})})]}),N.platform==="AMAZON"&&U&&e.jsx(gl,{storeId:N.id,value:((ae=N.publishedProduct)==null?void 0:ae.amazonListingMode)??"PARENT_CHILD",selectedVariantCount:E,locked:"listed",onChange:()=>{}})]},N.id)})})]}),ze.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"}),e.jsx("span",{className:"text-[11px] font-semibold text-slate-500 uppercase tracking-[0.08em]",children:"New"}),e.jsx("span",{className:"text-[10px] text-slate-400 font-semibold bg-slate-100 rounded px-1.5 py-px tabular-nums",children:ze.length})]}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx("button",{type:"button",onClick:et,className:"text-[10px] font-semibold text-primary hover:text-primary/80 px-1.5 py-0.5 rounded-md hover:bg-primary/5 transition-all",children:"All"}),e.jsx("span",{className:"text-slate-200 text-[10px]",children:"/"}),e.jsx("button",{type:"button",onClick:Lr,className:"text-[10px] font-semibold text-slate-400 hover:text-slate-600 px-1.5 py-0.5 rounded-md hover:bg-slate-50 transition-all",children:"None"})]})]}),e.jsx("div",{className:"space-y-1 max-h-[220px] overflow-y-auto",children:ze.map(N=>{const U=ee.has(N.id);return e.jsxs("div",{className:`group flex flex-col p-2 rounded-xl transition-all duration-200 ${U?"bg-primary/[0.04] border border-primary/20":"border border-transparent hover:bg-slate-50/80 hover:border-slate-200/80"}`,children:[e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>Lt(N.id,!U),onKeyDown:ae=>{(ae.key==="Enter"||ae.key===" ")&&(ae.preventDefault(),Lt(N.id,!U))},className:"flex items-center gap-2.5 cursor-pointer",children:[e.jsx("div",{className:`h-4 w-4 rounded-md border-[1.5px] flex items-center justify-center transition-all flex-shrink-0 ${U?"border-primary bg-primary shadow-[0_0_0_2px_rgba(21,182,127,0.12)]":"border-slate-300/80 group-hover:border-slate-400"}`,children:U&&e.jsx(Xn,{className:"h-2.5 w-2.5 text-white"})}),e.jsx("div",{className:`h-9 w-9 rounded-lg flex items-center justify-center flex-shrink-0 transition-all ${U?`bg-gradient-to-br ${pm[N.platform]||"from-slate-50 to-slate-100"} ring-1 ring-primary/10 shadow-sm`:"bg-slate-50 ring-1 ring-slate-200/60 group-hover:bg-white group-hover:shadow-sm group-hover:ring-slate-200"}`,children:e.jsx("img",{src:$i[N.platform],alt:N.platform,className:"h-4.5 w-4.5 object-contain"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`font-medium text-[12px] truncate leading-tight transition-colors ${U?"text-slate-900":"text-slate-700 group-hover:text-slate-900"}`,children:N.shopName||N.shopDomain}),e.jsx("p",{className:"text-[10px] text-slate-400 truncate mt-px",children:N.shopDomain})]}),e.jsxs("span",{className:`text-[10px] font-medium px-2 py-0.5 rounded-md transition-all tabular-nums ${U?"bg-primary/8 text-primary font-semibold":"bg-slate-100/80 text-slate-400"}`,children:[N.productsSynced," items"]})]}),N.platform==="AMAZON"&&U&&e.jsx(gl,{storeId:N.id,value:Oe(N),selectedVariantCount:E,locked:N.closedAmazonListingMode?"closed":void 0,onChange:ae=>St(N.id,ae)})]},N.id)})})]}),ze.length===0&&it.length>0&&X.length===0&&e.jsxs("div",{className:"text-center py-6 rounded-xl bg-gradient-to-br from-primary/[0.03] to-emerald-50/30 ring-1 ring-primary/10",children:[e.jsx(Nn,{className:"h-7 w-7 text-primary mx-auto mb-2"}),e.jsx("p",{className:"text-[13px] text-slate-800 font-semibold tracking-[-0.01em]",children:"All stores covered"}),e.jsx("p",{className:"text-[11px] text-slate-500 mt-0.5",children:"Published to every connected store"})]})]}))]}),e.jsx("div",{className:"flex-shrink-0 px-4 py-3 border-t border-slate-100",children:re?(()=>{const N=re.isComplete,U=re.completed,ae=re.failed,le=N&&ae===0&&U>0,ct=re.jobs.filter(j=>ai(j)==="retry-reconciliation").length,Pt=re.jobs.filter(j=>ai(j)==="reconciliation-blocked").length,Yt=uu(re.jobs),Rt=rl(re.jobs),$=re.jobs.filter(j=>j.status==="FAILED"&&j.id.startsWith("failed-")).map(j=>j.storeConnectionId),de=Rt.length+$.length,ce=de>0;let xe=`Retry (${de})`;ce?ct>0&&(xe=`Resume tracking (${ct})`):xe="Manual recovery needed";const f=async()=>{Q();try{$.length>0&&await Ct($),Rt.length>0&&await G(Rt)}catch(j){const Z=j instanceof Error?j.message:"Could not resume publishing.";ie.error(Z)}};return N?le?e.jsxs(pe,{onClick:()=>void Xt(),disabled:He,className:"w-full h-10 text-[12px] font-semibold bg-gradient-to-r from-primary to-emerald-600 hover:from-primary/90 hover:to-emerald-600/90 text-white rounded-lg shadow-primary transition-all",children:[He?e.jsx(mr,{className:"h-3.5 w-3.5 mr-2 animate-spin"}):e.jsx(Nn,{className:"h-3.5 w-3.5 mr-2"}),He?"Opening My Products...":"Done"]}):e.jsxs("div",{className:"space-y-2",children:[Pt>0&&e.jsxs("div",{className:"text-[11px] leading-4 text-amber-700",children:[e.jsxs("p",{children:[Pt," published product ",Pt===1?"needs":"need"," manual recovery. Contact support before publishing again."]}),e.jsx("button",{type:"button",onClick:()=>_("/dashboard/support/create?category=TECHNICAL_ISSUE"),className:"mt-1 font-semibold underline underline-offset-2 hover:text-amber-900",children:"Open a supp
26ort ticket"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{variant:"outline",onClick:()=>Vt(),className:"flex-1 h-10 border-slate-200 text-slate-700 hover:text-slate-900 hover:border-slate-400 bg-transparent rounded-lg text-[12px] font-semibold transition-colors",children:"Close"}),e.jsxs(pe,{onClick:()=>void f(),disabled:ye||!ce,className:"flex-1 h-10 bg-slate-900 hover:bg-slate-800 text-white rounded-lg text-[12px] font-semibold shadow-soft",children:[e.jsx(Us,{className:"h-3.5 w-3.5 mr-2"}),xe]})]})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{variant:"outline",onClick:Vt,className:"flex-1 h-10 border-slate-200 text-slate-700 hover:text-slate-900 hover:border-slate-400 bg-transparent rounded-lg text-[12px] font-semibold transition-colors",children:"Close"}),e.jsxs(pe,{onClick:Kt,disabled:!Yt,className:"flex-1 h-10 bg-gradient-to-r from-primary to-emerald-600 hover:from-primary/90 hover:to-emerald-600/90 text-white rounded-lg text-[12px] font-semibold shadow-primary transition-all",children:[Yt?e.jsx(Ki,{className:"h-3.5 w-3.5 mr-2"}):e.jsx(mr,{className:"h-3.5 w-3.5 mr-2 animate-spin"}),Yt?"Track in My Products":"Starting publishing..."]})]})})():e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{variant:"outline",onClick:()=>Vt(),className:"flex-1 h-10 border-slate-200 text-slate-700 hover:text-slate-900 hover:border-slate-400 bg-transparent rounded-lg text-[12px] font-semibold transition-colors",children:"Cancel"}),e.jsx(pe,{onClick:Mt,disabled:ee.size===0&&Ue.size===0||ye||Y||!Ve,className:"flex-1 h-10 bg-gradient-to-r from-primary to-emerald-600 hover:from-primary/90 hover:to-emerald-600/90 text-white disabled:from-slate-100 disabled:to-slate-100 disabled:text-slate-400 rounded-lg text-[12px] font-semibold shadow-primary disabled:shadow-none transition-all",title:Ve?void 0:"Please configure pricing before publishing",children:Y?e.jsxs(e.Fragment,{children:[e.jsx(mr,{className:"h-3.5 w-3.5 mr-2 animate-spin"}),"Validating..."]}):ye?e.jsxs(e.Fragment,{children:[e.jsx(mr,{className:"h-3.5 w-3.5 mr-2 animate-spin"}),Ue.size>0?"Updating...":"Publishing..."]}):Ue.size>0&&ee.size===0?e.jsxs(e.Fragment,{children:[e.jsx(Us,{className:"h-3.5 w-3.5 mr-2"}),"Update ",Ue.size," Store",Ue.size===1?"":"s"]}):Ue.size>0&&ee.size>0?e.jsxs(e.Fragment,{children:[e.jsx(ku,{className:"h-3.5 w-3.5 mr-2"}),"Publish & Update (",ee.size+Ue.size,")"]}):e.jsxs(e.Fragment,{children:[e.jsx(al,{className:"h-3.5 w-3.5 mr-2"}),"Publish",ee.size>0&&` to ${ee.size} Store${ee.size===1?"":"s"}`]})})]})}),e.jsx(mm,{open:he,onOpenChange:N=>{N||(ne(!1),Ze())},errorResults:Ee,passedResults:Be,onProceedWithValid:Be.length>0?At:void 0,onCancel:()=>{ne(!1),Ze()},getErrorMessage:Ye,getErrorAction:kt,onRetryValidation:async()=>{const N=new Set([...ee,...Ue]);if(N.size===0)return;const U=await yr(Array.from(N));U!=null&&U.length&&U.every(ae=>ae.canPublish)&&(ne(!1),await Ct(Array.from(N)))}})]}),e.jsx(bu,{open:Wt.open,onOpenChange:N=>{N||Qe({open:!1,publishedProductId:null,storeName:""})},onConfirm:qt,storeName:Wt.storeName,platform:Wt.platform,loading:w})]})}function xm({job:t}){var b,C,L;const s=t.status==="COMPLETED",n=t.status==="FAILED",a=ai(t),c=a==="retry-reconciliation",d=a==="reconciliation-blocked",u=c||d;let y="bg-slate-200/80",p="text-slate-700",x="text-slate-500";return s?(y="bg-emerald-100",p="text-emerald-800",x="text-emerald-600"):u?(y="bg-amber-100",p="text-amber-800",x="text-amber-600"):n&&(y="bg-red-100",p="text-red-800",x="text-red-500"),e.jsxs("div",{className:`flex items-center gap-2.5 p-2 rounded-lg transition-all ${s?"bg-emerald-50/70 ring-1 ring-emerald-100/80":u?"bg-amber-50/70 ring-1 ring-amber-100/80":n?"bg-red-50/70 ring-1 ring-red-100/80":"bg-slate-50/70 ring-1 ring-slate-100/80"}`,children:[e.jsx("div",{className:`h-6 w-6 rounded-md flex items-center justify-center flex-shrink-0 ${y}`,children:s?e.jsx(Nn,{className:"h-3 w-3 text-emerald-600"}):c?e.jsx(Us,{className:"h-3 w-3 text-amber-600"}):d?e.jsx(Fr,{className:"h-3 w-3 text-amber-600"}):n?e.jsx(Ma,{className:"h-3 w-3 text-red-500"}):e.jsx(mr,{className:"h-3 w-3 text-slate-500 animate-spin"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`font-medium text-[12px] truncate leading-tight ${p}`,children:((b=t.storeConnection)==null?void 0:b.shopName)||((C=t.storeConnection)==null?void 0:C.shop
26Domain)||"Store"}),e.jsx("p",{className:`text-[10px] truncate mt-px ${x}`,children:s?"Published successfully":c?"Published; restoring local tracking...":d?"Published; contact support for tracking recovery":n?t.errorMessage||"Publishing failed":t.stepMessage||t.stepLabel||"Processing..."})]}),(s||u)&&t.externalProductHandle&&((L=t.storeConnection)==null?void 0:L.shopDomain)&&e.jsx("a",{href:`https://${t.storeConnection.shopDomain}/products/${t.externalProductHandle}`,target:"_blank",rel:"noopener noreferrer",className:"h-6 w-6 rounded-md bg-white ring-1 ring-emerald-200 flex items-center justify-center text-emerald-600 hover:text-emerald-700 hover:ring-emerald-300 hover:shadow-sm transition-all",children:e.jsx(ql,{className:"h-3 w-3"})})]})}const fm={SHOPIFY:"/assets/sales-channels/shopify.svg",WOOCOMMERCE:"/assets/sales-channels/woocommerce.svg",AMAZON:"/assets/sales-channels/amazon.svg",NOON:"/assets/sales-channels/noon.svg",TIKTOK:"/assets/sales-channels/tiktok.svg",WIX:"/assets/sales-channels/wix.svg"};function gm({open:t,onOpenChange:s,designId:n,productTitle:a,productDescription:c,tags:d,variantPrices:u,brandingItems:y,selectedColors:p,selectedSizes:x,onSuccess:b}){const{stores:C,loading:L}=Yl(n,{skip:!t}),[k]=qs(xu),K=r.useMemo(()=>Hl(p,x),[p,x]),[P,B]=r.useState(new Set),[R,A]=r.useState(!1),[D,_]=r.useState(null),O=r.useRef(null),I=r.useMemo(()=>C.filter(X=>{var Q;return X.isPublished&&((Q=X.publishedProduct)==null?void 0:Q.id)}),[C]),ue=r.useMemo(()=>I.map(X=>X.id),[I]);Ji.useEffect(()=>{if(!t){O.current=null;return}L||O.current===n||(O.current=n,B(new Set(ue)))},[n,L,t,ue]);const me=r.useCallback((X,Q)=>{B(S=>{const w=new Set(S);return Q?w.add(X):w.delete(X),w})},[]),Se=r.useCallback(()=>{B(new Set(I.map(X=>X.id)))},[I]),be=r.useCallback(()=>{B(new Set)},[]),G=r.useCallback(()=>{_(null)},[]),ye=async()=>{var w,M,E,Me,Y;if(P.size===0)return;A(!0),_({total:P.size,completed:0,results:[]});const X=[];for(const Ee of P){const Be=I.find(Ae=>Ae.id===Ee);if((w=Be==null?void 0:Be.publishedProduct)!=null&&w.id){try{const Ae=await k({variables:{input:{publishedProductId:Be.publishedProduct.id,title:a,descriptionHtml:c||void 0,tags:d,variantPrices:u,brandingItems:y,selectedColors:K.selectedColors,selectedSizes:K.selectedSizes}}});(E=(M=Ae.data)==null?void 0:M.updatePublishedProduct)!=null&&E.success?X.push({storeConnectionId:Ee,storeName:Be.shopName||Be.shopDomain,success:!0}):X.push({storeConnectionId:Ee,storeName:Be.shopName||Be.shopDomain,success:!1,error:((Y=(Me=Ae.data)==null?void 0:Me.updatePublishedProduct)==null?void 0:Y.error)||"Unknown error"})}catch(Ae){X.push({storeConnectionId:Ee,storeName:Be.shopName||Be.shopDomain,success:!1,error:Ae instanceof Error?Ae.message:"Failed to update"})}_(Ae=>Ae?{...Ae,completed:Ae.completed+1,results:[...X]}:null)}}A(!1);const Q=X.filter(Ee=>Ee.success).length,S=X.filter(Ee=>!Ee.success).length;Q>0&&S===0&&(b==null||b())},we=()=>{R||(s(!1),G(),B(new Set))},re=(u==null?void 0:u.length)>0&&u.every(X=>X.price>0);return e.jsx(Xi,{open:t,onOpenChange:we,children:e.jsxs(Zi,{className:"sm:max-w-[500px] max-h-[85vh] p-0 overflow-hidden bg-white rounded-2xl border border-slate-200/60 shadow-[0_25px_50px_-12px_rgba(0,0,0,0.15),0_0_0_1px_rgba(0,0,0,0.03)] relative flex flex-col",children:[e.jsxs(Kl,{children:[e.jsx(El,{children:"Update Published Stores"}),e.jsxs(Ul,{children:["Select stores to update ",a]})]}),e.jsxs("div",{className:"relative flex-shrink-0 overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-blue-500/[0.06] via-indigo-50/80 to-sky-50/40"}),e.jsx("div",{className:"absolute top-0 right-0 w-32 h-32 bg-gradient-to-bl from-blue-500/10 to-transparent rounded-full -translate-y-1/2 translate-x-1/4 blur-2xl"}),e.jsx("div",{className:"absolute bottom-0 left-0 w-24 h-24 bg-gradient-to-tr from-indigo-400/8 to-transparent rounded-full translate-y-1/2 -translate-x-1/4 blur-xl"}),e.jsx("div",{className:"relative px-5 pt-4 pb-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-9 w-9 rounded-xl bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center shadow-[0_2px_8px_rgba(59,130,246,0.35)]",children:e.jsx(fl,{className:"h-4 w-4 text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h2",{className:"text-[15px] font-semibold text-slate-900 tracking-[-0.01em]",children:"Update in Stores"}),e.jsx("p",{className:"text-[12px] text-slate-500 mt-0.5 truncate font-medium",children:a})]})]})}),e.jsx("div",{className:"h-px bg-gradient-to-r from-transparent via-blue-500/15 to-transparent"})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3",children:[!L&&!re&&e.jsxs("div",{className:"mb-3 flex items-center gap-2.5 px-3 py-2.5 rounded-xl bg-red-50/80 border border-red-100/80",children:[e.jsx("div",{className:"h-6 w-6 rounded-lg bg-red-100 flex items-center justify-center flex-shrink-0",children:e.jsx(Ma,{className:"h-3.5 w-3.5 text-red-500"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[12px] font-semibold text-red-800 leading-tight",children:"Pricing required"}),e.jsx("p",{className:"text-[11px] text-red-600/70 leading-snug",children:"Set prices before updating"})]})]}),D&&(()=>{const X=D.completed===D.total,Q=D.results.filter(E=>E.success).length,S=D.results.filter(E=>!E.success).length,w=X&&S===0&&Q>0,M=X&&Q===0&&S>0;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-center pt-1",children:[e.jsx("div",{className:`inline-flex items-center justify-center h-16 w-16 rounded-2xl mx-auto mb-3 transition-all duration-500 ${X?w?"bg-gradient-to-br from-emerald-100 to-emerald-50 shadow-[0_0_0_4px_rgba(16,185,129,0.1)]":M?"bg-gradient-to-br from-red-100 to-red-50 shadow-[0_0_0_4px_rgba(239,68,68,0.08)]":"bg-gradient-to-br from-amber-100 to-amber-50 shadow-[0_0_0_4px_rgba(245,158,11,0.08)]":"bg-gradient-to-br from-blue-100 to-indigo-50 shadow-[0_0_0_4px_rgba(59,130,246,0.08)]"}`,children:X?w?e.jsx(Nn,{className:"h-7 w-7 text-emerald-600"}):M?e.jsx(Ma,{className:"h-7 w-7 text-red-500"}):e.jsx(Fr,{className:"h-7 w-7 text-amber-500"}):e.jsx(mr,{className:"h-7 w-7 text-blue-500 animate-spin"})}),e.jsx("h3",{className:"text-[15px] font-semibold text-slate-900 tracking-[-0.01em]",children:X?w?"Updated Successfully!":M?"Update Failed":"Partially Updated":"Updating..."}),e.jsx("p",{className:"text-[12px] text-slate-500 mt-1 font-medium",children:X?w?`${Q} store${Q===1?"":"s"} updated`:M?`Failed to update ${S} store${S===1?"":"s"}`:`${Q} succeeded, ${S} failed`:`${D.completed} of ${D.total} store${D.total===1?"":"s"}`})]}),e.jsxs("div",{className:"px-1",children:[e.jsx("div",{className:"flex gap-1",children:Array.from({length:D.total}).map((E,Me)=>{const Y=D.results[Me],Ee=(Y==null?void 0:Y.success)===!0,Be=(Y==null?void 0:Y.success)===!1,Ae=!Y&&Me<=D.completed&&!X;return e.jsx("div",{className:`h-1.5 flex-1 rounded-full transition-all duration-700 ease-out ${Ee?"bg-emerald-400":Be?"bg-red-400":Ae?"bg-blue-400/40 animate-pulse":"bg-slate-100"}`},`step-${Me}`)})}),e.jsxs("p",{className:"text-[11px] text-slate-400 text-right mt-1.5 font-medium tabular-nums",children:[D.completed,"/",D.total]})]}),D.results.length>0&&e.jsx("div",{className:"space-y-1.5 max-h-48 overflow-y-auto",children:D.results.map(E=>e.jsxs("div",{className:`flex items-center gap-2.5 p-2 rounded-lg transition-all ${E.success?"bg-emerald-50/70 ring-1 ring-emerald-100/80":"bg-red-50/70 ring-1 ring-red-100/80"}`,children:[e.jsx("div",{className:`h-6 w-6 rounded-md flex items-center justify-center flex-shrink-0 ${E.success?"bg-emerald-100":"bg-red-100"}`,children:E.success?e.jsx(Nn,{className:"h-3 w-3 text-emerald-600"}):e.jsx(Ma,{className:"h-3 w-3 text-red-500"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`font-medium text-[12px] truncate leading-tight ${E.success?"text-emerald-800":"text-red-800"}`,children:E.storeName}),E.error&&e.jsx("p",{className:"text-[10px] text-red-500 truncate mt-px",children:E.error})]})]},E.storeConnectionId))})]})})(),!D&&e.jsx(e.Fragment,{children:L?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(X=>e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl border border-slate-100 bg-slate-50/50",children:[e.jsx(Je,{className:"h-4 w-4 roun
26ded"}),e.jsx(Je,{className:"h-9 w-9 rounded-lg"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx(Je,{className:"h-3.5 w-28 rounded"}),e.jsx(Je,{className:"h-2.5 w-20 rounded"})]}),e.jsx(Je,{className:"h-5 w-10 rounded-full"})]},`step-${X}`))}):I.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"inline-flex items-center justify-center h-14 w-14 rounded-2xl bg-gradient-to-br from-slate-50 to-slate-100 ring-1 ring-slate-200/80 mx-auto mb-3 shadow-soft",children:e.jsx(Cu,{className:"h-6 w-6 text-slate-400"})}),e.jsx("h3",{className:"font-semibold text-slate-900 text-[14px] tracking-[-0.01em]",children:"Not published yet"}),e.jsx("p",{className:"text-[12px] text-slate-500 mt-1 max-w-[240px] mx-auto leading-relaxed",children:"This design hasn't been published to any store yet"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-blue-500"}),e.jsx("span",{className:"text-[11px] font-semibold text-slate-500 uppercase tracking-[0.08em]",children:"Published Stores"}),e.jsx("span",{className:"text-[10px] text-slate-400 font-semibold bg-slate-100 rounded px-1.5 py-px tabular-nums",children:I.length})]}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx("button",{type:"button",onClick:Se,className:"text-[10px] font-semibold text-blue-600 hover:text-blue-500 px-1.5 py-0.5 rounded-md hover:bg-blue-50 transition-all",children:"All"}),e.jsx("span",{className:"text-slate-200 text-[10px]",children:"/"}),e.jsx("button",{type:"button",onClick:be,className:"text-[10px] font-semibold text-slate-400 hover:text-slate-600 px-1.5 py-0.5 rounded-md hover:bg-slate-50 transition-all",children:"None"})]})]}),e.jsx("div",{className:"space-y-1 max-h-[280px] overflow-y-auto",children:I.map(X=>{const Q=P.has(X.id);return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>me(X.id,!Q),onKeyDown:S=>{(S.key==="Enter"||S.key===" ")&&me(X.id,!Q)},className:`group flex items-center gap-2.5 p-2 rounded-xl cursor-pointer transition-all duration-200 ${Q?"bg-blue-500/[0.04] border border-blue-500/20":"border border-transparent hover:bg-slate-50/80 hover:border-slate-200/80"}`,children:[e.jsx("div",{className:`h-4 w-4 rounded-md border-[1.5px] flex items-center justify-center transition-all flex-shrink-0 ${Q?"border-blue-500 bg-blue-500 shadow-[0_0_0_2px_rgba(59,130,246,0.12)]":"border-slate-300/80 group-hover:border-slate-400"}`,children:Q&&e.jsx(Xn,{className:"h-2.5 w-2.5 text-white"})}),e.jsx("div",{className:`h-9 w-9 rounded-lg flex items-center justify-center flex-shrink-0 transition-all ${Q?"bg-white ring-1 ring-blue-500/10 shadow-sm":"bg-slate-50 ring-1 ring-slate-200/60 group-hover:bg-white group-hover:shadow-sm group-hover:ring-slate-200"}`,children:e.jsx("img",{src:fm[X.platform],alt:X.platform,className:"h-4.5 w-4.5 object-contain"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`font-medium text-[12px] truncate leading-tight transition-colors ${Q?"text-slate-900":"text-slate-700 group-hover:text-slate-900"}`,children:X.shopName||X.shopDomain}),e.jsx("p",{className:"text-[10px] text-slate-400 truncate mt-px",children:X.shopDomain})]}),e.jsx("span",{className:`text-[10px] font-semibold px-2 py-0.5 rounded-md transition-all ${Q?"bg-blue-100/80 text-blue-700":"bg-emerald-100/60 text-emerald-600"}`,children:Q?"Update":"Live"})]},X.id)})})]})})]}),e.jsx("div",{className:"flex-shrink-0 px-4 py-3 border-t border-slate-100",children:D?(()=>{const X=D.completed===D.total,Q=D.results.filter(Me=>Me.success).length,S=D.results.filter(Me=>!Me.success).length,w=X&&S===0&&Q>0;if(!X)return e.jsxs(pe,{disabled:!0,className:"w-full h-10 text-[12px] font-semibold bg-slate-100 text-slate-400 rounded-lg border border-slate-200/60",children:[e.jsx(mr,{className:"h-3.5 w-3.5 mr-2 animate-spin"}),"Updating..."]});if(w)return e.jsxs(pe,{onClick:we,className:"w-full h-10 text-[12px] font-semibold bg-gradient-to-r from-blue-500 to-indigo-600 hover:from-blue-600 hover:to-indigo-700 text-white rounded-lg shadow-[0_2px_8px_rgba(59,130,246,0.3)] transition-all",children:[e.jsx(Nn,{className:"h-3.5 w-3.5 mr-2"}),"Done"]});const M=D.results.filter(Me=>!Me.success).map(Me=>Me.storeConnectionId),E=async()=>{G(),B(new Set(M)),setTimeout(()=>{ye()},100)};return e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{variant:"outline",onClick:we,className:"flex-1 h-10 border-slate-200 text-slate-700 hover:text-slate-900 hover:border-slate-400 bg-transparent roun
26ded-lg text-[12px] font-semibold transition-colors",children:"Close"}),e.jsxs(pe,{onClick:E,className:"flex-1 h-10 bg-slate-900 hover:bg-slate-800 text-white rounded-lg text-[12px] font-semibold shadow-soft",children:[e.jsx(Us,{className:"h-3.5 w-3.5 mr-2"}),"Retry (",S,")"]})]})})():e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{variant:"outline",onClick:we,className:"flex-1 h-10 border-slate-200 text-slate-700 hover:text-slate-900 hover:border-slate-400 bg-transparent rounded-lg text-[12px] font-semibold transition-colors",children:"Cancel"}),e.jsx(pe,{onClick:ye,disabled:P.size===0||R||!re,className:"flex-1 h-10 bg-gradient-to-r from-blue-500 to-indigo-600 hover:from-blue-600 hover:to-indigo-700 text-white disabled:from-slate-100 disabled:to-slate-100 disabled:text-slate-400 rounded-lg text-[12px] font-semibold shadow-[0_2px_8px_rgba(59,130,246,0.25)] disabled:shadow-none transition-all",title:re?void 0:"Please configure pricing before updating",children:R?e.jsxs(e.Fragment,{children:[e.jsx(mr,{className:"h-3.5 w-3.5 mr-2 animate-spin"}),"Updating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(fl,{className:"h-3.5 w-3.5 mr-2"}),"Update",P.size>0&&` ${P.size} Store${P.size===1?"":"s"}`]})})]})})]})})}const bm=Ur` 27 query GetAvailableMockupsByProductId($productId: ID!) { 28 getAvailableMockupsByProductId(productId: $productId) { 29 id 30 mockupKey 31 printAreaId 32 viewType 33 name 34 isPremium 35 canUse 36 isDefault 37 isPrimary 38 thumbnailUrl 39 psdUrl 40 # V30 Enhancement: Layer configuration for mockup generation 41 colorLayerPaths 42 designLayers { 43 layerPath 44 printAreaId 45 layerName 46 layerType 47 } 48 # V39: Dual renderer support 49 publicRenderProfile 50 designCoverage 51 coverageWidth 52 coverageHeight 53 # Renderer-specific mockup lookup code 54 mockupCode 55 # RENDER_PROFILE_A extracted layer fields 56 extractedShadowUrl 57 extractedHighlightUrl 58 extractedForegroundUrl 59 extractedMaskUrl 60 extractedBackgroundUrl 61 designPlacementX 62 designPlacementY 63 designPlacementWidth 64 designPlacementHeight 65 designPlacementRotation 66 psdWidth 67 psdHeight 68 psdLastModified 69 extractionJobId 70 displayOrder 71 } 72 } 73`,ym=Ur` 74 mutation UploadCustomerMockup($designId: ID!, $colorName: String!, $imageData: String, $templateName: String, $printAreaId: String, $originalFileName: String) { 75 uploadCustomerMockup(designId: $designId, colorName: $colorName, imageData: $imageData, templateName: $templateName, printAreaId: $printAreaId, originalFileName: $originalFileName) { 76 id 77 designId 78 mockupTemplateId 79 mockupKey 80 source 81 customMockupId 82 printAreaId 83 fileId 84 originalFileName 85 contentType 86 mockupVersion 87 uploadedAt 88 fingerprint 89 templateName 90 colorName 91 mockupUrl 92 generatedAt 93 designLastModified 94 } 95 } 96`,vm=Ur` 97 mutation ReplaceCustomerMockup($designId: ID!, $mockupKey: ID!, $imageData: String, $templateName: String, $originalFileName: String) { 98 replaceCustomerMockup(designId: $designId, mockupKey: $mockupKey, imageData: $imageData, templateName: $templateName, originalFileName: $originalFileName) { 99 id 100 designId 101 mockupTemplateId 102 mockupKey 103 source 104 customMockupId 105 printAreaId 106 fileId 107 originalFileName 108 contentType 109 mockupVersion 110 uploadedAt 111 fingerprint 112 templateName 113 colorName 114 mockupUrl 115 generatedAt 116 designLastModified 117 } 118 } 119`,Nm=Ur` 120 mutation DeleteCustomerMockup($designId: ID!, $mockupKey: ID!) { 121 deleteCustomerMockup(designId: $designId, mockupKey: $mockupKey) 122 } 123`,jm=Ur` 124 query GetProductTemplateId($productId: ID!) { 125 getProductById(productId: $productId) { 126 mockupTemplateId 127 } 128 } 129`,wm=Ur` 130 ${Ad} 131 query GetSavedMockups($designId: ID!) { 132 getSavedMockups(designId: $designId) { 133 id 134 designId 135 mockupTemplateId 136 mockupKey 137 source 138 customMockupId 139 printAreaId 140 fileId 141 originalFileName 142 contentType 143 mockupVersion 144 uploadedAt 145 fingerprint 146 templateName 147 colorName 148 mockupUrl 149 generatedAt 150 designLastModified 151 generationOperationId 152 canvasGenerationToken 153 canvasBaseRevision 154 committedRevision 155 replay 156 renderSignature 157 publicRenderProfile 158 } 159 getDesign(id: $designId) { 160 revision 161 printAreas { 162 printAreaId
163 variantCanvases { 164 ...GeneratedMockupCanvasReferenceFields 165 designImageUrl 166 } 167 } 168 } 169 } 170`,km=t=>t.taskId,Cm=20*1024*1024,Mm=4,bl=4,ws=10,Pm=Object.freeze({token:"empty-print-area",baseRevision:0,lastModified:null}),xo=t=>t.slice().sort((s,n)=>(s.displayOrder||0)-(n.displayOrder||0)),fo=t=>{const s=t.filter(c=>c.isPrimary===!0),n=t.filter(c=>c.isPrimary!==!0);return(s.length>0?[...s,...n]:t.slice(0,Mm)).slice(0,ws)},Im=(t,s,n,a,c)=>t.map(d=>{const u=Ws(n,d);return{color:d,mockups:s.filter(y=>(Hr(y.publicRenderProfile)||a)&&Ks(y.publicRenderProfile,y.psdUrl)&&Hs(y.publicRenderProfile,y.printAreaId,u)&&!c.has(`${y.id}-${d}`))}}),sc=(t,s,n,a)=>{var c,d;return{taskId:`${t.id}-${s}`,mockupId:t.id,colorName:s,colorHex:n,psdTemplateUrl:t.psdUrl||"",printAreaId:t.printAreaId,colorLayerPaths:t.colorLayerPaths,designLayerPath:(d=(c=t.designLayers)==null?void 0:c.find(u=>u.printAreaId===t.printAreaId))==null?void 0:d.layerPath,publicRenderProfile:t.publicRenderProfile,mockupCode:t.mockupCode,designCoverage:t.designCoverage,coverageWidth:t.coverageWidth,coverageHeight:t.coverageHeight,designLayers:t.designLayers,designLastModified:a}},yl=async(t,s,n,a)=>(await Promise.all(t.map(async d=>Hr(d.publicRenderProfile)?{task:d,designUrl:""}:{task:d,designUrl:await n(s,d.colorName,d.printAreaId)}))).filter(({designUrl:d})=>d!==null).map(({task:d,designUrl:u})=>({...d,designImageUrl:ni(u||"",d.designLastModified??a)})),Sm=(t,s,n,a,c,d)=>t.flatMap(u=>Pr(u)?Ks(u.publicRenderProfile,u.psdUrl)?s.flatMap(y=>{var b;if(n.has(`${u.id}-${y}`))return[];const p=Ws(a,y);if(!Hs(u.publicRenderProfile,u.printAreaId,p))return[];const x=(b=c.find(C=>C.colorName===y))==null?void 0:b.colorHex;return[sc(u,y,x,d(y,u.printAreaId))]}):[]:[]),Am=(t,s)=>s||(!t||t.startsWith("blob:")||t.startsWith("data:")?t||"":`data:image/jpeg;base64,${t}`),Fo=t=>typeof t=="string"&&t.startsWith("custom:"),Tm=t=>Vl(t),Rm=(t,s)=>Fo(t)?null:Tm(t)??s??null,wo=(t,s,n)=>!Fo(s)||n==null?t:t.filter(a=>a!==n),Fm=(t,s,n,a,c,d)=>{if(t!==void 0){const u=n?yo(n,d):c,y=t.filter(p=>p.startsWith("template:")).map(p=>yo(p,d)).filter(p=>p!=null);return{templateIds:bn(wo(y,n,a),u),customKeys:t.filter(p=>p.startsWith("custom:"))}}return((s==null?void 0:s.length)??0)===0?null:{templateIds:bn(wo(s??[],n,a),c),customKeys:null}},Em=(t,s,n,a,c)=>n?{customKey:s,templateId:null}:t&&zl(t)?{customKey:null,templateId:yo(t,c)}:{customKey:null,templateId:a},bn=(t,s,n=ws)=>{if(n<=0)return[];const a=Array.from(new Set(t)),c=a.slice(0,n);return s==null||c.includes(s)||!a.includes(s)?c:[...c.slice(0,n-1),s]},or=t=>t.mockupKey?t.mockupKey:t.customMockupId?`custom:${t.customMockupId}`:t.mockupTemplateId?Rd(t.mockupTemplateId):null,nc=t=>{var s;return t.source==="CUSTOMER_UPLOADED"||!!t.customMockupId||!!((s=t.mockupKey)!=null&&s.startsWith("custom:"))},Um=t=>{const s=[],n=new Map;return t.forEach(a=>{if(!nc(a))return;const c=or(a);if(!c||!a.colorName||!a.mockupUrl)return;const d=gn(a);n.set(`${c}-${a.colorName}`,d),s.push(d)}),{uploadedMockups:s,uploadedMockupMap:n}},Lm=(t,s)=>new Promise((n,a)=>{const c=new FileReader;c.onload=()=>n(String(c.result||"")),c.onerror=()=>a(new Error(s)),c.readAsDataURL(t)}),Dm=t=>t.replace(/\.[^.]+$/,"").trim(),Om=(t,s)=>t.type.startsWith("image/")?t.type==="image/svg+xml"||t.name.toLowerCase().endsWith(".svg")?s("SVG files are not supported for store mockups."):t.size>Cm?s("Mockup image must be 20 MB or smaller."):null:s("Upload a PNG, JPEG, or WebP image."),ac=({isPrimary:t,disabled:s,primaryLabel:n,makePrimaryLabel:a,onMakePrimary:c})=>e.jsx(jn,{delayDuration:250,children:e.jsxs(wn,{children:[e.jsx(kn,{asChild:!0,children:e.jsx("button",{type:"button","aria-pressed":t,"aria-label":t?n:a,title:t?n:a,disabled:s,onClick:d=>{d.stopPropagation(),t||c(d)},className:Sr("inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full border shadow-sm transition focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#15B67F] focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t?"border-[#15B67F] bg-[#15B67F] text-white shadow-[0_8px_18px_rgba(21,182,127,0.24)]":"border-slate-200 bg-white text-slate-400 hover:border-[#15B67F]/40 hover:bg-[#15B67F]/10 hover:text-[#0f8f65]"),children:e.jsx(Ro,{className:Sr("h-3.5 w-3.5",t?"fill-current":"fill-transparent")})})}),e.jsx(Cn,{side:"left",className:"text-xs",children:t?n:a})]})}),Eo=(t,s)=>`${t}::${s}`,vl=(t,s)=>{if(!t||!s)return!1;const n=Date.parse(t),a=Date.parse(s);return Number.isFinite(n)&&Number.isFinite(a)?n===a:t===s},Bm=t=>{const s=new Map,n=new Map;if(!t)return{byColorArea:s,maxByColor:n};
170for(const a of t)for(const c of a.variantCanvases||[]){if(!c.colorName||!c.lastModified)continue;s.set(Eo(c.colorName,a.printAreaId),c.lastModified);const d=n.get(c.colorName);(!d||Date.parse(c.lastModified)>Date.parse(d))&&n.set(c.colorName,c.lastModified)}return{byColorArea:s,maxByColor:n}},$m=(t,s)=>{var a;const n=new Map;return(a=t==null?void 0:t.printAreas)==null||a.forEach(c=>{var d;(d=c.variantCanvases)==null||d.forEach(u=>{const y=Td(u,t.revision??s);y&&n.set(`${u.colorName}::${c.printAreaId}`,y)})}),n},zm=(t,s,n,a,c,d)=>{const u=new Map;n.forEach(p=>{p.id!==void 0&&p.printAreaId&&u.set(p.id,p.printAreaId)});const y=new Map(s);return t.forEach(p=>{if(nc(p)||d||!p.mockupTemplateId)return;const x=u.get(p.mockupTemplateId);if(!x)return;const b=a.get(Eo(p.colorName,x));if(!b)return;(vl(p.designLastModified,b)||vl(p.designLastModified,c.get(p.colorName)))&&y.set(`${p.mockupTemplateId}-${p.colorName}`,gn(p))}),y},_m=(t,s)=>{const n=Gm(t);for(const[a,c]of s.entries()){if(!Yi(c))continue;const d=a.lastIndexOf("-");if(d===-1)continue;const u=a.substring(0,d),y=a.substring(d+1),p=n.get(u)??new Set;p.add(y),n.set(u,p)}return n},Gm=t=>{const s=new Map;if(!t)return s;for(const n of t)if(n.variantCanvases){for(const a of n.variantCanvases)if(a.designImageUrl&&a.designImageUrl.trim()!==""){const d=s.get(a.colorName)||new Set;d.add(n.printAreaId),s.set(a.colorName,d)}}return s},Ws=(t,s)=>t.get(s)||new Set,Vm=()=>e.jsx("div",{className:"grid grid-cols-5 gap-4",children:Array.from({length:10}).map((t,s)=>e.jsx(Rr.div,{initial:{opacity:0}
170,animate:{opacity:1},transition:{delay:s*.03},className:"aspect-[4/5] animate-pulse bg-gradient-to-br from-slate-100 to-slate-200 rounded-xl"},`skeleton-${s}`))}),Km=({designedPrintAreasList:t,mockupPrintAreasList:s,mockupsCopy:n})=>e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-gradient-to-br from-slate-100 to-slate-200 flex items-center justify-center mb-4",children:e.jsx(Ir,{className:"h-8 w-8 text-slate-400"})}),e.jsxs("p",{className:"text-sm text-slate-500 max-w-md",children:[n("Mockup templates for the")," ",e.jsx("span",{className:"font-medium text-slate-700",children:t.join(", ")})," ",n(t.length===1?"print area":"print areas")," ",n("are not yet available for this product.")]}),e.jsxs("p",{className:"text-xs text-slate-400 mt-2",children:[n("You can continue to publish your product or go back to add a design on the")," ",s.join(", ")," ",n("area.")]})]}),Ym=({previewCustomMockupKey:t,previewMockupId:s,displayedMockups:n,displayColor:a,canUseTemplate:c,generatedMockupsMap:d})=>{var C;const u=t?null:s??((C=n[0])==null?void 0:C.id)??null,y=n.find(L=>L.id===u),p=y?!c(y):!1,x=u?`${u}-${a}`:"",b=x&&!p?d.get(x):void 0;return{activePreviewId:u,activePreviewMockup:y,activePreviewLocked:p,activePreviewKey:x,activePreviewGenerated:b}},Hm=(t,s,n,a)=>{const c=t.find(y=>or(y)===n);if(c)return c;const d=t.find(y=>or(y)===a);return d||(t.find(y=>{const p=or(y);return p!==null&&s.includes(p)})??t[0])},ic=(t,s)=>t?"border-[#15B67F]/25 bg-[#15B67F]/5 shadow-[0_8px_18px_rgba(21,182,127,0.08)]":s?"border-slate-200 bg-slate-50":"border-transparent hover:border-slate-100 hover:bg-slate-50",Wm=({mockupSourceMode:t,mockupControlsLocked:s,setMockupSourceMode:n,setPreviewCustomMockupKey:a,setPreviewMockupId:c,activeUploadPreviewKey:d,mockupsCopy:u})=>e.jsxs("div",{className:"grid grid-cols-2 rounded-[14px] bg-slate-100 p-1",children:[e.jsx("button",{type:"button",disabled:s,onClick:()=>{n("generated"),a(null)},className:Sr("h-8 rounded-[10px] text-xs font-semibold transition-colors",t==="generated"?"bg-white text-slate-900 shadow-sm":"text-slate-500 hover:text-slate-700",s&&"cursor-not-allowed opacity-55"),children:u("Generated")}),e.jsx("button",{type:"button",disabled:s,onClick:()=>{n("upload"),c(null),a(d)},className:Sr("h-8 rounded-[10px] text-xs font-semibold transition-colors",t==="upload"?"bg-white text-slate-900 shadow-sm":"text-slate-500 hover:text-slate-700",s&&"cursor-not-allowed opacity-55"),children:u("Upload")})]}),qm=({isViewOnly:t,uploadInputRef:s,replaceInputRef:n,replaceCustomMockupKeyRef:a,handleCustomMockupFile:c})=>e.jsx(e.Fragment,{children:!t&&e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:s,type:"file",accept:"image/png,image/jpeg,image/webp",className:"hidden",onChange:d=>{var y;const u=(y=d.target.files)==null?void 0:y[0];u&&c(u)}}),e.jsx("input",{ref:n,type:"file",accept:"image/png,image/jpeg,image/webp",className:"hidden",onChange:d=>{var p;const u=(p=d.target.files)==null?void 0:p[0],y=a.current;u&&y&&c(u,y)}})]})}),Xm=({activePreviewGenerating:t,activePreviewUrl:s,activePreviewName:n,activePreviewMockup:a,activePreviewLocked:c,mockupSourceMode:d,displayColor:u,isViewOnly:y,isUploadingCustomMockup:p,openCustomMockupUploadPicker:x,setLockedPremiumMockupName:b,handleZoom:C,mockupsCopy:L})=>{let k;return t?k=e.jsxs("div",{className:"flex flex-col items-center gap-3 text-slate-400",children:[e.jsx("span",{className:"h-8 w-8 animate-spin rounded-full border-3 border-[#15B67F] border-t-transparent"}),e.jsx("p",{className:"text-sm font-medium",children:L("Generating mockup...")})]}):s?k=e.jsx("button",{type:"button",className:"flex min-h-[400px] w-full cursor-pointer items-center justify-center border-0 bg-transparent p-0 hover:bg-slate-50","aria-label":c?`${L("Unlock")} ${n}`:n,onClick:()=>{a&&c?b(a.name):a&&C(a,s)},children:e.jsx("img",{src:s,alt:n,className:"max-w-full max-h-[75vh] object-contain"})}):d==="upload"?k=e.jsxs("div",{className:"flex flex-col items-center gap-4 px-6 py-20 text-center",children:[e.jsx("div",{className:"flex h-16 w-16 items-center justify-center rounded-[20px] bg-[#15B67F]/10 text-[#15B6
1707F]",children:e.jsx(Wi,{className:"h-7 w-7"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-semibold text-slate-800",children:[L("Upload your mockup for")," ",u]}),e.jsx("p",{className:"mt-1 max-w-sm text-xs text-slate-500",children:L("This color does not have an uploaded mockup yet. Add one here to use it in your store listing.")})]}),!y&&e.jsxs(pe,{type:"button",variant:"outline",onClick:x,disabled:p,className:"h-10 rounded-[14px] border-[#15B67F]/40 bg-white px-5 text-[#0f8f65] hover:bg-[#15B67F]/10",children:[p?e.jsx(mr,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Wi,{className:"mr-2 h-4 w-4"}),L("Upload mockup")]})]}):k=e.jsxs("div",{className:"flex flex-col items-center gap-3 text-slate-400 py-20",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-slate-100 flex items-center justify-center",children:e.jsx(Ir,{className:"h-8 w-8 text-slate-300"})}),e.jsx("p",{className:"text-sm font-medium",children:L(a?"Click a thumbnail to preview":"No mockups available")})]}),e.jsx("div",{className:"w-full lg:w-[70%]",children:e.jsx("div",{className:"bg-slate-50/50 rounded-2xl overflow-hidden flex items-center justify-center transition-colors min-h-[400px]",children:k})})},Zm=({displayColor:t,selectedColorsCount:s,uploadScope:n,setUploadScope:a,openCustomMockupUploadPicker:c,isUploadingCustomMockup:d,customMockupBusyKey:u,customMockupError:y,mockupsCopy:p})=>e.jsxs("div",{className:"space-y-3 rounded-[14px] border border-dashed border-[#15B67F]/35 bg-[#15B67F]/5 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-wider text-slate-400",children:p("Upload color mode")}),e.jsx("span",{className:"text-[10px] font-medium text-[#15B67F]",children:t})]}),s>1?e.jsxs(Zl,{value:n,onValueChange:x=>a(x),className:"grid grid-cols-2 gap-2",children:[e.jsxs(vn,{className:"flex items-center gap-2 rounded-[10px] bg-white px-2.5 py-2 text-xs text-slate-600 shadow-sm",children:[e.jsx(Hi,{value:"current",className:"h-3.5 w-3.5"}),p("Current color")]}),e.jsxs(vn,{className:"flex items-center gap-2 rounded-[10px] bg-white px-2.5 py-2 text-xs text-slate-600 shadow-sm",children:[e.jsx(Hi,{value:"all",className:"h-3.5 w-3.5"}),p("All colors")]})]}):e.jsxs("div",{className:"rounded-[10px] bg-white px-3 py-2 text-xs font-medium text-slate-600 shadow-sm",children:[p("Uploads apply to")," ",t]}),e.jsxs(pe,{type:"button",variant:"outline",onClick:c,disabled:d,className:"h-10 w-full rounded-[14px] border-[#15B67F]/40 bg-white text-[#0f8f65] hover:bg-[#15B67F]/10",children:[d&&u==="upload"?e.jsx(mr,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Wi,{className:"mr-2 h-4 w-4"}),p("Upload mockup")]}),y&&e.jsx("p",{className:"rounded-[10px] bg-red-50 px-3 py-2 text-xs text-red-700",children:y})]}),Jm=({uploadedMockupsForDisplayColor:t,selectedCustomMockupKeys:s,primaryCustomMockupKey:n,activeUploadPreviewKey:a,displayColor:c,handleUploadedMockupPrimaryClick:d,handleSelectCustomMockup:u,openCustomMockupUploadPicker:y,isViewOnly:p,isUploadingCustomMockup:x,mockupsCopy:b})=>e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2.5 flex items-center justify-between",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-wider text-slate-400",children:b("Views")}),e.jsxs("span",{className:"text-[10px] font-medium text-slate-400",children:[t.length," ",b("uploaded")]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:t.length===0?e.jsxs("button",{type:"button",onClick:y,disabled:p||x,className:"col-span-3 flex h-24 flex-col items-center justify-center gap-2 rounded-[14px] border border-dashed border-[#15B67F]/35 bg-[#15B67F]/5 text-xs font-medium text-[#0f8f65] hover:bg-[#15B67F]/10",children:[e.jsx(Wi,{className:"h-4 w-4"}),b("Upload mockup for")," ",c]}):t.map((C,L)=>{const k=or(C);if(!k)return null;const K=s.includes(k),P=n===k,B=a===k;return e.jsxs(Rr.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},transition:{delay:L*.02,duration:.3},className:Sr("relative h-20 w-20 cursor-pointer overflow-hidden rounded-xl transition-all duration-200",B?"ring-2 ring-[#15B6
1707F] ring-offset-1 shadow-md":"opacity-75 ring-1 ring-slate-200/60 hover:opacity-100 hover:ring-slate-300 hover:shadow-sm"),onClick:()=>d(k),title:b("Set as primary uploaded mockup"),children:[e.jsx("img",{src:C.mockupUrl,alt:C.templateName||b("Uploaded mockup"),className:"h-full w-full object-cover"}),e.jsx("div",{className:"absolute top-1 left-1",children:e.jsx(Zs,{checked:K,onCheckedChange:()=>u(k),onClick:R=>R.stopPropagation(),className:"h-3.5 w-3.5 rounded border-white/80 bg-white/70 backdrop-blur-sm data-[state=checked]:bg-[#15B67F] data-[state=checked]:border-[#15B67F]"})}),P&&e.jsx("div",{className:"absolute bottom-0.5 right-0.5",children:e.jsx(Xs,{className:"border-0 bg-[#15B67F] px-1 py-0 text-[8px] leading-tight text-white",children:b("Primary")})})]},`${k}-${C.colorName}`)})})]}),Qm=({selectedColors:t,colorVariants:s,displayCustomerUploadedMockups:n,primaryVariant:a,onColorChoice:c,mockupsCopy:d})=>e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-wider text-slate-400 mb-2.5",children:d("Colors")}),e.jsx("div",{className:"flex flex-wrap gap-2",children:t.map(u=>{var x;const y=(x=s.find(b=>b.colorName===u))==null?void 0:x.colorHex,p=n.filter(b=>b.colorName===u).length;return e.jsx(jn,{children:e.jsxs(wn,{children:[e.jsx(kn,{asChild:!0,children:e.jsx("button",{type:"button",onClick:()=>void c(u),className:Sr("h-7 w-7 rounded-full shadow-sm transition-all duration-200",a===u?"scale-110 ring-2 ring-[#15B67F] ring-offset-2":"ring-1 ring-slate-200 hover:scale-105 hover:ring-slate-400"),style:{backgroundColor:y||"#e2e8f0"}})}),e.jsxs(Cn,{side:"bottom",className:"text-center",children:[e.jsx("p",{className:"font-medium text-xs",children:u}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:p>0?`${p} ${d("uploaded")}`:d("No upload yet")})]})]})},u)})})]}),ep=({uploadedMockupsForDisplayColor:t,selectedCustomMockupKeys:s,primaryCustomMockupKey:n,activeUploadPreviewKey:a,displayColor:c,customMockupBusyKey:d,isViewOnly:u,markMockupSelectionDirty:y,setSelectedCustomMockupKeys:p,setPrimaryCustomMockupKey:x,setPreviewCustomMockupKey:b,setPreviewMockupId:C,handleSelectCustomMockup:L,handleSetPrimaryCustomMockup:k,openCustomMockupReplacePicker:K,handleDeleteCustomMockup:P,mockupsCopy:B})=>e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2.5 flex items-center justify-between",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-wider text-slate-400",children:B("Mockups")}),e.jsx("span",{className:"text-[10px] font-medium text-slate-400",children:c})]}),t.length===0?e.jsxs("div",{className:"rounded-[14px] border border-dashed border-slate-200 bg-slate-50 px-3 py-4 text-center",children:[e.jsxs("p",{className:"text-xs font-semibold text-slate-700",children:[B("No uploaded mockups for")," ",c]}),e.jsx("p",{className:"mt-1 text-[11px] text-slate-500",children:B("Upload one to select it for publishing.")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 py-1.5 border-b border-slate-100 mb-1",children:[e.jsx(Zs,{checked:t.every(R=>{const A=or(R);return A?s.includes(A):!1}),onCheckedChange:R=>{y();const A=t.map(or).filter(D=>!!D);if(R)p(D=>[...new Set([...D,...A])]);else{const D=new Set(A);p(_=>_.filter(O=>!D.has(O))),n&&D.has(n)&&x(null)}},className:"h-3.5 w-3.5 rounded data-[state=checked]:bg-[#15B67F] data-[state=checked]:border-[#15B67F]"}),e.jsx("span",{className:"text-xs font-medium text-slate-600",children:B("Select all uploaded for this color")})]}),e.jsx("div",{className:"max-h-64 space-y-1 overflow-y-auto pr-1",children:t.map(R=>{const A=or(R);if(!A)return null;const D=s.includes(A),_=n===A,O=d===A;return e.jsxs("div",{className:Sr("flex items-center gap-2 rounded-[12px] border px-2 py-2 transition-colors",ic(_,a===A)),children:[e.jsx(Zs,{checked:D,onCheckedChange:()=>L(A),className:"h-3.5 w-3.5 rounded data-[state=checked]:bg-[#15B67F] data-[state=checked]:border-[#15B67F]"}),e.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 cursor-pointer items-center gap-2 text-left","aria-label":B("Select uploaded mockup"),onClick:()=>{b(A),C(null)},children:[e.jsx("span",{className:"h-10 w-10 flex-shrink-0 overflow-hidden rounded-[10px] bg-slate-100",children:e.jsx("img",{src:R.mockupUrl,alt:R.templateName||B("Uploaded mockup"),className:"h-full w-full object-cover"})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-xs font-semibold text-slate-700",children:R.templateName||R.originalFileName||B("Uploaded mockup")}),e.jsxs("span",{className:"mt-0.5 flex min-w-0 items-center gap-1.5",children:[e.jsx("span",{className:"truncate text-[11px] text-slate-400",children:R.colorName}),_&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-1 w-1 shrink-0 rounded-full bg-[#15B67F]"}),e.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1 text-[11px] font-semibold text-[#0f8f65]",children:[e.jsx(Ro,{className:"h-3 w-3 fill-[#15B6
1707F]"}),B("Primary mockup")]})]})]})]})]}),e.jsx(ac,{isPrimary:_,disabled:u||O,primaryLabel:B("Uploaded mockup is primary"),makePrimaryLabel:B("Make uploaded mockup primary"),onMakePrimary:()=>k(A)}),!u&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{type:"button",className:"flex h-7 w-7 items-center justify-center rounded-lg text-slate-400 hover:bg-slate-100 hover:text-slate-700",disabled:O,onClick:I=>{I.stopPropagation(),K(A)},title:B("Replace mockup"),children:O?e.jsx(mr,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Us,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button",className:"flex h-7 w-7 items-center justify-center rounded-lg text-slate-400 hover:bg-red-50 hover:text-red-600",disabled:O,onClick:I=>{I.stopPropagation(),P(A)},title:B("Delete mockup"),children:e.jsx(Wl,{className:"h-3.5 w-3.5"})})]})]},`${A}-${R.colorName}-row`)})})]})]}),tp=({isGenerating:t,isWaitingForGeneratedMockup:s,hasFailed:n,thumbUrl:a,mockup:c,renderLoadingLabel:d,renderGeneratedThumbnailLoading:u})=>t||s?u(d):n?e.jsx("div",{className:"flex h-full w-full items-center justify-center bg-red-50",children:e.jsx(Fr,{className:"h-4 w-4 text-red-400"})}):a?e.jsx("img",{src:a,alt:c.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full bg-slate-100 flex items-center justify-center",children:e.jsx(Ir,{className:"h-4 w-4 text-slate-300"})}),rp=({stockViews:t,stockViewIndex:s,stockCount:n,displayedMockups:a,filteredMockups:c,displayColor:d,generatedMockups:u,generatingMockups:y,savingMockupTaskKey:p,failedMockups:x,activePreviewId:b,designedPrintAreasPerColorRef:C,selectedMockups:L,isViewOnl
170y:k,mockupControlsLocked:K,primaryMockup:P,setLockedPremiumMockupName:B,handleGeneratedMockupPrimaryClick:R,handleRetry:A,handleSelectMockup:D,renderGeneratedThumbnailLoading:_,mockupsCopy:O})=>e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-wider text-slate-400",children:O("Views")}),e.jsxs("span",{className:"text-[11px] font-medium text-slate-400",children:[a.length+n,"/",c.length+n]})]}),e.jsxs("div",{className:"grid max-h-56 grid-cols-[repeat(auto-fill,80px)] justify-start gap-2 overflow-y-auto p-1",children:[a.map((I,ue)=>{const me=!Pr(I),Se=`${I.id}-${d}`,be=me?void 0:u.get(Se),G=!me&&y.includes(Se),ye=!me&&p===Se,we=!me&&x.has(Se),re=I.id===b,X=Ws(C.current,d),Q=Hs(I.publicRenderProfile,I.printAreaId,X),S=L.includes(I.id),w=!(be!=null&&be.mockupUrl)&&!we&&Q&&S,M=me?I.thumbnailUrl:be==null?void 0:be.mockupUrl;return e.jsxs(Ji.Fragment,{children:[ue===s&&t,e.jsxs(Rr.div,{"data-source":"template","data-print-area":I.printAreaId,initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},transition:{delay:ue*.02,duration:.3},className:Sr("relative flex-shrink-0 w-20 h-20 rounded-xl overflow-hidden transition-all duration-200",re?"ring-2 ring-[#15B67F] ring-offset-1 shadow-md":"ring-1 ring-slate-200/60 hover:ring-slate-300 hover:shadow-sm opacity-75 hover:opacity-100"),children:[e.jsx("button",{type:"button",className:"absolute inset-0 h-full w-full cursor-pointer overflow-hidden rounded-xl border-0 bg-transparent p-0","aria-label":me?`${O("Unlock")} ${I.name}`:O("Select mockup"),onClick:()=>{me?B(I.name):R(I.id)},title:O(me?"Premium mockup â upgrade to unlock":"Set as primary generated mockup"),children:e.jsx(tp,{isGenerating:G,isWaitingForGeneratedMockup:w,hasFailed:we,thumbUrl:M,mockup:I,renderLoadingLabel:O(G?"Generating":"Queued"),renderGeneratedThumbnailLoading:_})}),we&&e.jsx("button",{type:"button",title:O("Retry mockup generation"),onClick:()=>void A(I.id,d),className:"absolute bottom-1 right-1 z-10 flex h-6 w-6 items-center justify-center rounded-lg bg-white/90 text-red-500 shadow-sm hover:bg-white",children:e.jsx(Us,{className:"h-3 w-3"})}),e.jsx("div",{className:"absolute top-1 left-1",children:me?e.jsx("button",{type:"button",className:"flex h-6 w-6 items-center justify-center rounded-md bg-white/95 text-amber-700 shadow-sm","aria-label":`${O("Unlock")} ${I.name}`,onClick:E=>{E.stopPropagation(),B(I.name)},children:e.jsx(Ql,{className:"h-3.5 w-3.5","aria-hidden":"true"})}):e.jsx(Zs,{checked:L.includes(I.id),disabled:k||K,onCheckedChange:()=>D(I.id),onClick:E=>E.stopPropagation(),"aria-label":O(L.includes(I.id)?"Deselect mockup":"Select mockup"),className:"h-3.5 w-3.5 rounded border-white/80 bg-white/70 backdrop-blur-sm data-[state=checked]:bg-[#15B67F] data-[state=checked]:border-[#15B67F]"})}),I.isPremium&&e.jsxs(Xs,{className:"pointer-events-none absolute right-1 top-1 gap-1 border-0 bg-amber-50 px-1.5 py-0.5 text-[8px] text-amber-800",children:[e.jsx(ec,{className:"h-2.5 w-2.5","aria-hidden":"true"}),O("Premium")]}),P===I.id&&e.jsx("div",{className:"absolute bottom-0.5 right-0.5",children:e.jsx(Xs,{className:"text-[8px] px-1 py-0 leading-tight bg-[#15B67F] text-white border-0",children:O("Primary")})}),ye&&M&&e.jsx(td,{label:O("Saving...")})]},I.id)]},I.id)}),s>=a.length&&t]})]}),sp=({hasSecondaryMockups:t,isLoadingSecondary:s,isParallelGenerating:n,mockupControlsLocked:a,handleLoadMoreMockups:c,nextSecondaryBatchCount:d,remainingSecondaryCount:u,mockupsCopy:y})=>t?e.jsxs(pe,{type:"button",variant:"ghost",size:"sm",disabled:s||n||a,onClick:()=>void c(),className:"mt-2 h-9 w-full rounded-[12px] text-xs font-medium text-[#0f8f65] hover:bg-[#15B67F]/10 hover:text-[#0f8f65]",children:[s?e.jsx(mr,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"}):e.jsx(Us,{className:"mr-1.5 h-3.5 w-3.5"}),y("Load")," ",d," ",y("more"),u>d?` (${u} ${y("left")})`:""]}):null,np=({visible:t,mockupColorMode:s,mockupControlsLocked:n,requestMockupColorMode:a,mockupsCopy:c})=>t?e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-2.5",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-wider text-slate-400",children:c("Mockup color mode")}),e.jsx("a",{href:"/support/kb/how-to-create-realistic-mockups-for-your-designs-1775293261065",target:"_blank",rel:"noopener noreferrer",className:"text-[10px] text-[#15B6
1707F] hover:text-[#12a070] hover:underline",children:c("Learn more")})]}),e.jsxs(Zl,{value:s,disabled:n,onValueChange:d=>a(d),className:"flex gap-3",children:[e.jsx(jn,{delayDuration:300,children:e.jsxs(wn,{children:[e.jsx(kn,{asChild:!0,children:e.jsxs(vn,{htmlFor:"cmyk-mode",className:Sr("flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs cursor-pointer transition-all",n&&"cursor-not-allowed opacity-55",s==="cmyk"?"bg-[#15B67F]/10 text-[#15B67F] font-medium":"bg-slate-50 text-slate-500 hover:bg-slate-100"),"aria-disabled":n,children:[e.jsx(Hi,{value:"cmyk",id:"cmyk-mode",className:"h-3 w-3"}),e.jsx("span",{className:"text-xs",children:c("Realistic (CMYK)")})]})}),e.jsx(Cn,{side:"bottom",className:"max-w-[220px] text-xs",children:c("CMYK mode makes mockups look more accurate and true to the final print.")})]})}),e.jsx(jn,{delayDuration:300,children:e.jsxs(wn,{children:[e.jsx(kn,{asChild:!0,children:e.jsxs(vn,{htmlFor:"rgb-mode",className:Sr("flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs cursor-pointer transition-all",n&&"cursor-not-allowed opacity-55",s==="rgb"?"bg-[#15B67F]/10 text-[#15B67F] font-medium":"bg-slate-50 text-slate-500 hover:bg-slate-100"),"aria-disabled":n,children:[e.jsx(Hi,{value:"rgb",id:"rgb-mode",className:"h-3 w-3"}),e.jsx("span",{className:"text-xs",children:c("Bright/colourful (RGB)")})]})}),e.jsx(Cn,{side:"bottom",className:"max-w-[220px] text-xs",children:c("RGB mode makes mockups look more vibrant, but they may not match the printed result.")})]})})]})]}):null,ap=({selectedColors:t,colorVariants:s,primaryVariant:n,onColorChoice:a,mockupsCopy:c})=>e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-wider text-slate-400 mb-2.5",children:c("Colors")}),e.jsx("div",{className:"flex flex-wrap gap-2",children:t.map(d=>{var y;const u=(y=s.find(p=>p.colorName===d))==null?void 0:y.colorHex;return e.jsx(jn,{children:e.jsxs(wn,{children:[e.jsx(kn,{asChild:!0,children:e.jsx("button",{type:"button",onClick:()=>void a(d),className:Sr("w-7 h-7 rounded-full cursor-pointer transition-all duration-200 shadow-sm",n===d?"ring-2 ring-[#15B67F] ring-offset-2 scale-110":"ring-1 ring-slate-200 hover:ring-slate-400 hover:scale-105"),style:{backgroundColor:u||"#e2e8f0"}})}),e.jsxs(Cn,{side:"bottom",className:"text-center",children:[e.jsx("p",{className:"font-medium text-xs",children:d}),u&&e.jsx("p",{className:"text-[10px] text-muted-foreground",children:u}),n===d&&e.jsx("p",{className:"text-[10px] text-[#15B67F] font-semibold",children:c("Main color")})]})]})},d)})})]}),ip=({displayedMockups:t,selectedMockups:s,primaryMockup:n,activePreviewId:a,isViewOnly:c,mockupControlsLocked:d,markMockupSelectionDirty:u,setSelectedMockups:y,setLockedPremiumMockupName:p,setPreviewMockupId:x,setPreviewCustomMockupKey:b,handleSelectMockup:C,handleSetPrimary:L,mockupsCopy:k})=>e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-wider text-slate-400 mb-2.5",children:k("Mockups")}),e.jsxs("div",{className:"flex items-center gap-2 py-1.5 border-b border-slate-100 mb-1",children:[e.jsx(Zs,{checked:t.some(Pr)&&t.filter(Pr).every(K=>s.includes(K.id)),disabled:c||d,onCheckedChange:K=>{if(u(),K){const P=t.filter(Pr).map(B=>B.id);y(B=>{const R=[...new Set([...B,...P])];return R.length>ws&&ie.error(`${k("Select up to")} ${ws} ${k("generated mockups per color")}`),bn(R,n)})}else{const P=new Set(t.map(B=>B.id));y(B=>B.filter(R=>!P.has(R)))}},className:"h-3.5 w-3.5 rounded data-[state=checked]:bg-[#15B67F] data-[state=checked]:border-[#15B67F]"}),e.jsx("span",{className:"text-xs font-medium text-slate-600",children:k("Select all")})]}),e.jsx("div",{className:"max-h-64 space-y-1 overflow-y-auto",children:t.map(K=>{const P=!Pr(K),B=n===K.id;return e.jsxs("div",{className:Sr("flex items-center gap-2 rounded-[12px] border px-2 py-2 transition-colors",ic(B,K.id===a)),children:[e.jsx("div",{children:P?e.jsx("button",{type:"button",className:"flex h-7 w-7 items-center justify-center rounded-lg bg-amber-50 text-amber-700","aria-label":`${k("Unlock")} ${K.name}`,onClick:R=>{R.stopPropagation(),p(K.name)},children:e.jsx(Ql,{className:"h-3.5 w-3.5","aria-hidden":"true"})}):e.jsx(Zs,{checked:s.includes(K.id),disabled:c||d,onCheckedChange:()=>C(K.id),onClick:R=>R.stopPropagation(),"aria-label":k(s.includes(K.id)?"Deselect mockup":"Select mockup"),className:"h-3.5 w-3.5 rounded data-[state=checked]:bg-[#15B67F] data-[state=checked]:border-[#15B67F]"})}),e.jsxs("button",{type:"button",className:"min-w-0 flex-1 cursor-pointer text-left","aria-label":P?`${k("Unlock")} ${K.name}`:k("Select mockup"),onClick:()=>{P?p(K.name):(x(K.id),b(null))},children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 text-xs font-medium text-slate-600",children:[e.jsx("span",{className:"truncate",children:K.name}),K.isPremium&&e.jsxs(Xs,{className:"shrink-0 gap-1 border-0 bg-amber-50 px-1.5 py-0 text-[9px] text-amber-800",children:[e.jsx(ec,{className:"h-2.5 w-2.5","aria-hidden":"true"}),k("Premium")]})]}),B&&e.jsxs("span",{className:"mt-0.5 inline-flex items-center gap-1 text-[11px] font-semibold text-[#0f8f65]",children:[e.jsx(Ro,{className:"h-3 w-3 fill-[#15B6
1707F]"}),k("Primary mockup")]})]}),!P&&e.jsx(ac,{isPrimary:B,disabled:c||d,primaryLabel:k("Generated mockup is primary"),makePrimaryLabel:k("Make generated mockup primary"),onMakePrimary:()=>L(K.id)})]},K.id)})})]}),op=({primaryVariant:t,currentColor:s,displayCustomerUploadedMockups:n,selectedCustomMockupKeys:a,previewCustomMockupKey:c,primaryCustomMockupKey:d,mockupSourceMode:u,getCustomPreviewMockup:y,previewMockupId:p,displayedMockups:x,generatedMockups:b,generatingMockups:C})=>{var I,ue,me;const L=Pr,k=t||s,K=n.filter(Se=>Se.colorName===k),P=Hm(K,a,c,d),B=P?or(P):null,R=u==="upload"?P:y(c),A=Ym({previewCustomMockupKey:c,previewMockupId:p,displayedMockups:x,displayColor:k,canUseTemplate:L,generatedMockupsMap:b});let D=R==null?void 0:R.mockupUrl;u==="generated"&&!D&&(D=(I=A.activePreviewGenerated)==null?void 0:I.mockupUrl),u==="generated"&&!D&&A.activePreviewLocked&&(D=(ue=A.activePreviewMockup)==null?void 0:ue.thumbnailUrl);const _=(R==null?void 0:R.templateName)||((me=A.activePreviewMockup)==null?void 0:me.name)||"Mockup preview",O=!A.activePreviewLocked&&u==="generated"&&A.activePreviewKey?C.includes(A.activePreviewKey):!1;return{displayColor:k,uploadedMockupsForDisplayColor:K,activeUploadPreviewKey:B,activeCustomPreview:R,...A,activePreviewUrl:D,activePreviewName:_,activePreviewGenerating:O}},lp=({workspaceProps:t,uploadedMockupsForDisplayColor:s,activeUploadPreviewKey:n,displayColor:a,activePreviewId:c})=>e.jsxs("div",{className:"w-full lg:w-[30%] space-y-5 lg:pl-2",children:[e.jsx(Wm,{mockupSourceMode:t.mockupSourceMode,mockupControlsLocked:t.mockupControlsLocked,setMockupSourceMode:t.setMockupSourceMode,setPreviewCustomMockupKey:t.setPreviewCustomMockupKey,setPreviewMockupId:t.setPreviewMockupId,activeUploadPreviewKey:n,mockupsCopy:t.mockupsCopy}),e.jsx(qm,{isViewOnly:t.isViewOnly,uploadInputRef:t.uploadInputRef,replaceInputRef:t.replaceInputRef,replaceCustomMockupKeyRef:t.replaceCustomMockupKeyRef,handleCustomMockupFile:t.handleCustomMockupFile}),t.mockupSourceMode==="upload"?e.jsxs(e.Fragment,{children:[!t.isViewOnly&&e.jsx(Zm,{displayColor:a,selectedColorsCount:t.selectedColors.length,uploadScope:t.uploadScope,setUploadScope:t.setUploadScope,openCustomMockupUploadPicker:t.openCustomMockupUploadPicker,isUploadingCustomMockup:t.isUploadingCustomMockup,customMockupBusyKey:t.customMockupBusyKey,customMockupError:t.customMockupError,mockupsCopy:t.mockupsCopy}),e.jsx(Jm,{uploadedMockupsForDisplayColor:s,selectedCustomMockupKeys:t.selectedCustomMockupKeys,primaryCustomMockupKey:t.primaryCustomMockupKey,activeUploadPreviewKey:n,displayColor:a,handleUploadedMockupPrimaryClick:t.handleUploadedMockupPrimaryClick,handleSelectCustomMockup:t.handleSelectCustomMockup,openCustomMockupUploadPicker:t.openCustomMockupUploadPicker,isViewOnly:t.isViewOnly,isUploadingCustomMockup:t.isUploadingCustomMockup,mockupsCopy:t.mockupsCopy}),e.jsx(Qm,{selectedColors:t.selectedColors,colorVariants:t.colorVariants,displayCustomerUploadedMockups:t.displayCustomerUploadedMockups,primaryVariant:t.primaryVariant,onColorChoice:t.handleColorChoice,mockupsCopy:t.mockupsCopy}),e.jsx(ep,{uploadedMockupsForDisplayColor:s,selectedCustomMockupKeys:t.selectedCustomMockupKeys,primaryCustomMockupKey:t.primaryCustomMockupKey,activeUploadPreviewKey:n,displayColor:a,customMockupBusyKey:t.customMockupBusyKey,isViewOnly:t.isViewOnly,markMockupSelectionDirty:t.markMockupSelectionDirty,setSelectedCustomMockupKeys:t.setSelectedCustomMockupKeys,setPrimaryCustomMockupKey:t.setPrimaryCustomMockupKey,setPreviewCustomMockupKey:t.setPreviewCustomMockupKey,setPreviewMockupId:t.setPreviewMockupId,handleSelectCustomMockup:t.handleSelectCustomMockup,handleSetPrimaryCustomMockup:t.handleSetPrimaryCustomMockup,openCustomMockupReplacePicker:t.openCustomMockupReplacePicker,handleDeleteCustomMockup:t.handleDeleteCustomMockup,mockupsCopy:t.mockupsCopy})]}):e.jsxs(e.Fragment,{children:[e.jsx(rp,{stockViews:t.stockViews,stockViewIndex:t.stockViewIndex,stockCount:t.stockCount,displayedMockups:t.displayedMockups,filteredMockups:t.filteredMockups,displayColor:a,generatedMockups:t.generatedMockups,generatingMockups:t.generatingMockups,savingMockupTaskKey:t.savingMockupTaskKey,failedMockups:t.failedMockups,activePreviewId:c,designedPrintAreasPerColorRef:t.designedPrintAreasPerColorRef,selectedMockups:t.selectedMockups,isViewOnl
170y:t.isViewOnly,mockupControlsLocked:t.mockupControlsLocked,primaryMockup:t.primaryMockup,setLockedPremiumMockupName:t.setLockedPremiumMockupName,handleGeneratedMockupPrimaryClick:t.handleGeneratedMockupPrimaryClick,handleRetry:t.handleRetry,handleSelectMockup:t.handleSelectMockup,renderGeneratedThumbnailLoading:t.renderGeneratedThumbnailLoading,mockupsCopy:t.mockupsCopy}),t.stockNotices,e.jsx(sp,{hasSecondaryMockups:t.hasSecondaryMockups,isLoadingSecondary:t.isLoadingSecondary,isParallelGenerating:t.isParallelGenerating,mockupControlsLocked:t.mockupControlsLocked,handleLoadMoreMockups:t.handleLoadMoreMockups,nextSecondaryBatchCount:t.nextSecondaryBatchCount,remainingSecondaryCount:t.remainingSecondaryCount,mockupsCopy:t.mockupsCopy}),e.jsx(np,{visible:t.hasRenderProfileAMockups,mockupColorMode:t.mockupColorMode,mockupControlsLocked:t.mockupControlsLocked,requestMockupColorMode:t.requestMockupColorMode,mockupsCopy:t.mockupsCopy}),e.jsx(ap,{selectedColors:t.selectedColors,colorVariants:t.colorVariants,primaryVariant:t.primaryVariant,onColorChoice:t.handleColorChoice,mockupsCopy:t.mockupsCopy}),e.jsx(ip,{displayedMockups:t.displayedMockups,selectedMockups:t.selectedMockups,primaryMockup:t.primaryMockup,activePreviewId:c,isViewOnly:t.isViewOnly,mockupControlsLocked:t.mockupControlsLocked,markMockupSelectionDirty:t.markMockupSelectionDirty,setSelectedMockups:t.setSelectedMockups,setLockedPremiumMockupName:t.setLockedPremiumMockupName,setPreviewMockupId:t.setPreviewMockupId,setPreviewCustomMockupKey:t.setPreviewCustomMockupKey,handleSelectMockup:t.handleSelectMockup,handleSetPrimary:t.handleSetPrimary,mockupsCopy:t.mockupsCopy})]})]}),cp=t=>{if(t.mockupsLoading)return e.jsx(Vm,{});const s=t.displayCustomerUploadedMockups.length>0||!!t.primaryCustomMockupKey;if(t.availableMockups.length===0&&!t.stockUnavailable&&t.stockCount===0&&t.isViewOnly&&!s)return e.jsx(ed,{onContinue:t.goToNextStep});if(t.hasPrintAreaMismatch&&!t.stockUnavailable&&t.stockCount===0)return e.jsx(Km,{designedPrintAreasList:t.designedPrintAreasList,mockupPrintAreasList:t.mockupPrintAreasList,mockupsCopy:t.mockupsCopy});const n=op(t);return e.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[t.stockPreview?e.jsx("div",{className:"min-w-0 lg:w-[70%]",children:t.stockPreview}):e.jsx(Xm,{activePreviewGenerating:n.activePreviewGenerating,activePreviewUrl:n.activePreviewUrl,activePreviewName:n.activePreviewName,activePreviewMockup:n.activePreviewMockup,activePreviewLocked:n.activePreviewLocked,mockupSourceMode:t.mockupSourceMode,displayColor:n.displayColor,isViewOnly:t.isViewOnly,isUploadingCustomMockup:t.isUploadingCustomMockup,openCustomMockupUploadPicker:t.openCustomMockupUploadPicker,setLockedPremiumMockupName:t.setLockedPremiumMockupName,handleZoom:t.handleZoom,mockupsCopy:t.mockupsCopy}),e.jsx(lp,{workspaceProps:t,uploadedMockupsForDisplayColor:n.uploadedMockupsForDisplayColor,activeUploadPreviewKey:n.activeUploadPreviewKey,displayColor:n.displayColor,activePreviewId:t.stockPreview?null:n.activePreviewId})]})},dp=({interactionLocked:t=!1,onPreparationStateChange:s,onProgressChange:n})=>{var fa,Li,ga,ba,Di;const a=Js(),d=((fa=Ll().state)==null?void 0:fa.forceMockupRegenerationAt)??null,{goToNextStep:u,goToPreviousStep:y,draftId:p,productId:x,selectedProvider:b,selectedVariants:C,variantsLoaded:L,activeVariantColor:k,variantCanvases:K,setSelectedMockupIds:P,setSelectedMockupKeys:B,setPrimaryMockupId:R,setPrimaryMockupKey:A,selectedMockupIds:D,selectedMockupKeys:_,primaryMockupId:O,primaryMockupKey:I,mockupColorMode:ue="rgb",setMockupColorMode:me,setPrimaryVariantColor:Se,primaryVariantColor:be,setPrimaryMockupPreview:G,isEditMode:ye,isViewOnly:we,registerBeforeLeave:re,registerDraftScope:X,markDraftScopeDirty:Q,scheduleDraftAutosave:S,refreshSavedMockups:w,designRevision:M,isBeforeLeaveRunning:E,customerNeckLabel:Me}=mi(),Y=Oc(b==null?void 0:b.configId,sl(C),Me),Ee=Bc(Y,_),[Be,Ae]=r.useState(),Ze=(_==null?void 0:_.filter(i=>ri(i)).length)??0,Ye=r.useCallback(()=>{we||(Q==null||Q("design"),Q==null||Q("mockups"),S==null||S())},[we,Q,S]),kt=Fo(I)?I:null,he=kt!==null,ne=Rm(I,O),[ee,nt]=r.useState(bn(wo(((D==null?void 0:D.length)??0)>0?D||[]:[],I,O),ne)),[Ue,Le]=r.useState((_==null?void 0:_.filter(i=>i.startsWith("custom:")))||[]),[Te,$e]=r.useState(he?null:ne),[Ke,pt]=r.useState(kt),[ot,at]=r.useState(new Map),He=r.useRef(new Map),De=r.useRef(new Map),Gt=r.useRef(new Set),[es,ke]=r.useState(0),[lt,Wt]=r.useState([]),[Qe,ht]=r.useState([]),rr=r.useRef([]),Oe=r.useCallback(i=>{const l=typeof i=="function"?i(rr.current):i;rr.current=l,ht(l)},[]),[St,ze]=r.useState(new Map),[it,Lt]=r.useState([]),[xt,et]=r.useState("generated"),[Lr,Dr]=r.useState("current"),[Dt,qt]=r.useState(!1),[lr,Ct]=r.useState(null),[yr,Mt]=r.useState(null),[At,Tt]=r.useState(null),Vt=r.useRef(null),Kt=r.useRef(null),Xt=r.useRef(null),[Nt,Ve]=r.useState(!1),[N,U]=r.useState(be??null),ae=r.useRef(!1),le=r.useRef(!1),ct=r.useRef(!1),Pt=le.current||ae.current||ee.length>0||Ue.length>0,Yt=(i=a("Generating"))=>e.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center gap-2 bg-gradient-to-br from-slate-50 to-slate-100 px-2",children:[e.jsx("div",{className:"h-6 w-6 rounded-lg bg-white/80 shadow-sm flex items-center justify-center",children:e.jsx(Ir,{className:"h-3.5 w-3.5 text-slate-300"})}),e.jsx("div",{className:"h-1.5 w-12 overflow-hidden rounded-full bg-slate-200",children:e.jsx("div",{className:"h-full w-2/3 animate-pulse rounded-full bg-[#15B67F]"})}),e.jsx("span",{className:"text-[9px] font-semibold uppercase tracking-wide text-slate-400",children:i})]});r.useEffect(()=>{P&&Pt&&P(ee)},[Pt,ee,P]),r.useEffect(()=>{R&&R(Ke?null:Te)},[Ke,Te,R]),r.useEffect(()=>{Se&&Se(N)},[N,Se]);const[Rt,$]=r.useState(new Map),de=r.useRef(new Map),[ce,xe]=r.useState(!0),[f,j]=r.useState(!1),[Z,oe]=r.useState(0),[z,fe]=r.useState(1),[ve,qe]=r.useState({x:0,y:0}),[Ot,jt]=r.useState(!1),sr=()=>z<=1?"cursor-zoom-in":Ot?"cursor-grabbing":"cursor-grab",[nr,ar]=r.useState({x:0,y:0}),[Qs,ft]=r.useState(null),[gt,Wr]=r.useState(null),qr=r.useMemo(()=>sl(C),[C]),ir=k||qr[0]||"White",ts=r.useMemo(()=>
170{if(!k)return!1;for(const[i,l]of K.entries())if(i.startsWith(`${k}-`)&&Yi(l))return!0;return!1},[k,K]),We=r.useMemo(()=>qr.length>0?qr:!L&&k&&ts?[k]:[],[k,ts,qr,L]),{data:tt,loading:vr,error:Jn}=Ht(bm,{variables:{productId:x},skip:!x}),Xe=r.useMemo(()=>xo(Y.resolved?((tt==null?void 0:tt.getAvailableMockupsByProductId)||[]).filter(i=>!Y.unavailable||!il(i.printAreaId)):[]),[tt,Y.resolved,Y.unavailable]);r.useEffect(()=>{if(!Y.unavailable||vr)return;const i=new Set(((tt==null?void 0:tt.getAvailableMockupsByProductId)||[]).filter(l=>il(l.printAreaId)).map(l=>l.id));nt(l=>l.some(h=>i.has(h))?l.filter(h=>!i.has(h)):l),$e(l=>l!==null&&i.has(l)?null:l)},[tt,Y.unavailable,vr]);const Sa=r.useRef(new Set);Sa.current=new Set(Xe.filter(i=>Xo(i.publicRenderProfile)).map(i=>i.id)),r.useEffect(()=>{if(!B||!Pt||!Y.resolved||_!==void 0&&!le.current||vr&&ee.length>0)return;const i=bd(ee,Ue,Xe,Vo(_,(tt==null?void 0:tt.getAvailableMockupsByProductId)||[],Y.unavailable));(_==null?void 0:_.length)===i.length&&_.every((h,v)=>h===i[v])||B(i)},[Y.resolved,tt,Y.unavailable,Xe,_,Pt,vr,Ue,ee,B]),r.useEffect(()=>{if(!A||!Y.resolved||I!=null&&!ct.current||vr&&Te!=null)return;const i=Zo(Te,Ke,Xe,Vo(I?[I]:[],(tt==null?void 0:tt.getAvailableMockupsByProductId)||[],Y.unavailable)[0]);I!==i&&A(i)},[Y.unavailable,tt,Y.resolved,Xe,I,vr,Ke,Te,A]);const Aa=Ko(Y.photos,N||ir,I).preview,Mn=Aa&&Na(Aa)===I?Aa:void 0,Ta=$c(Mn),Qn=Mn?Na(Mn):void 0,ea=r.useRef(null);r.useEffect(()=>{if(!G)return;const i=!Ke&&Te!==null&&N?`${Te}-${N}`:null,l=i?De.current.get(i):void 0,h=l!=null&&l.objectUrl?Zo(Te,null,Xe,I):null,v=Ta&&Qn&&N&&p?{objectUrl:Ta,mockupKey:Qn,colorName:N,designId:p,printAreaId:"inner_neck",sourceToken:Qn}:l!=null&&l.objectUrl&&h&&N&&p?{objectUrl:l.objectUrl,mockupKey:h,colorName:N,designId:p,printAreaId:l.printAreaId,sourceToken:l.sourceToken}:null,g=ea.current;g===v||g!==null&&v!==null&&g.objectUrl===v.objectUrl&&g.mockupKey===v.mockupKey&&g.colorName===v.colorName&&g.printAreaId===v.printAreaId&&g.sourceToken===v.sourceToken||(ea.current=v,G(v))},[Ta,Qn,Xe,es,I,p,Ke,Te,N,G]),r.useEffect(()=>{if(Gt.current.size===0)return;const i=window.requestAnimationFrame(()=>{const l=new Set(Array.from(He.current.values(),h=>h.mockupUrl));Gt.current.forEach(h=>{l.has(h)||(oi(h),Gt.current.delete(h))})});return()=>window.cancelAnimationFrame(i)},[es,ot]),r.useEffect(()=>()=>{De.current.forEach(({objectUrl:i})=>oi(i)),De.current.clear(),Gt.current.forEach(oi),Gt.current.clear()},[]);const Ls=r.useMemo(()=>Xe.filter(Pr),[Xe]),Ra=r.useMemo(()=>Ls.filter(i=>Hr(i.publicRenderProfile)),[Ls]),Ds=Ra.length>0,F=r.useMemo(()=>Ls.filter(i=>qn(i.publicRenderProfile)),[Ls]).length>0;r.useEffect(()=>{vr||xt==="upload"||(!we&&Xe.length===0||we&&Ke)&&et("upload")},[Xe.length,we,xt,vr,Ke]);const{isReady:ds,progress:pi,completedCount:Ea,totalCount:ta,timedOut:tn,hasFailure:dt,failedItems:cr}=zc(p,F?We:[]),hi=r.useMemo(()=>(l=>{var g;if(!l)return!1;const h=((g=l.message)==null?void 0:g.toLowerCase())||"",v=l.graphQLErrors||[];return h.includes("unauthenticated")||h.includes("unauthorized")||h.includes("token")||h.includes("expired")||v.some(T=>{var W,se;return((W=T.extensions)==null?void 0:W.code)==="UNAUTHENTICATED"||((se=T.message)==null?void 0:se.toLowerCase().includes("unauthenticated"))})})(Jn),[Jn]),{data:ra,loading:ks}=Ht(Mu,{variables:{productId:x},skip:!x}),Ft=(ra==null?void 0:ra.getProductColors)||[],{data:rn,loading:pr}=Ht(jm,{variables:{productId:x},skip:!x}),Ua=(Li=rn==null?void 0:rn.getProductById)==null?void 0:Li.mockupTemplateId,sn=r.useRef(ue),[Cs]=qs(ym),[xi]=qs(vm),[nn]=qs(Nm),[an,Ms]=r.useState(null),sa=r.useCallback((i,l,h)=>{const v=`${i}-${l}`,g=gn({...h,mockupTemplateId:i,colorName:l});at(T=>{const W=new Map(T);return W.set(v,g),He.current=W,W})},[]),[dr,Re]=r.useState(null),[na,on]=r.useState(null),[La,hr]=r.useState(),[ln,Ps]=r.useState(""),[fi,Da]=r.useState(),Is=r.useRef(""),Bt=r.useRef(void 0),[Pn,xr]=r.useState(!1),[Oa,bt]=r.useState(!1),[Pe,Or]=r.useState({totalMockups:0,completedMockups:0,currentColor:"",totalColors:0,completedColors:0}),[Br,ut]=r.useState(null),[us,cn]=r.useState(null),[Ss,In]=r.useState(),[Os,Ba]=r.useState([]),Ar=r.useRef([]),[Nr,gi]=r.useState(!1),Ce=r.useRef(!0),rs=r.useRef(!0),ms=r.useRef(!1),jr=r.useRef(_c()).current;r.useEffect(()=>()=>
170{jr.invalidate()},[jr]);const[Sn,fr]=r.useState(!1),dn=r.useRef([]),$r=r.useCallback((i,l=[])=>{jr.isCurrent(i)&&(dn.current=l,fr(!0))},[jr]),zr=r.useCallback(i=>jr.isCurrent(i)?(dn.current=[],fr(!1),!0):!1,[jr]),wr=r.useCallback(()=>{const i=jr.begin();return dn.current=[],fr(!1),i},[jr]),_r=r.useCallback(i=>{const l=typeof i=="function"?i(Ar.current):i;Ar.current=l,Ba(l)},[]),ss=r.useCallback(i=>{ms.current=i,gi(i)},[]),An=r.useCallback(i=>{Ce.current=!i.some(l=>Hr(l.publicRenderProfile)),rs.current=!i.some(l=>qn(l.publicRenderProfile))},[]),Tn=r.useCallback(i=>{An(i),_r(i),ss(!0)},[An,ss,_r]),As=r.useCallback(i=>{Hr(i.publicRenderProfile)&&(Ce.current=!1),qn(i.publicRenderProfile)&&(rs.current=!1),_r(l=>[...l,i]),ss(!0)},[ss,_r]),ns=r.useCallback(i=>{Ce.current=!0,rs.current=!0,fr(!1),bt(!0),ss(!1),_r([]),Oe([]),Ve(!1),i||xr(!1)},[Oe,ss,_r]),Tr=r.useCallback(()=>{if(!ms.current||!Ce.current||!rs.current||rr.current.length>0)return;const i=Ar.current.some(l=>qn(l.publicRenderProfile));ns(i)},[ns]),kr=r.useCallback(()=>Ar.current.filter(i=>Hr(i.publicRenderProfile)),[]),{data:$t,loading:Zt,refetch:Gr}=Ht(wm,{variables:{designId:p},skip:!p,fetchPolicy:"network-only",notifyOnNetworkStatusChange:!0}),un=r.useRef(!1),ps=r.useRef(!1),Ts=r.useRef(!1),Vr=r.useRef(null),mn=r.useRef([]),Rs=r.useRef(!1),It=r.useRef(null),Fs=r.useRef(null),hs=r.useRef(void 0),aa=r.useRef(new Map),Cr=r.useRef(new Map),xs=r.useRef(new Map),Jt=r.useMemo(()=>new yd(async(i,l)=>{if(!p)throw new Error("The design draft is not ready.");return vd(Qr,p,i,l)},({completed:i,total:l,activeTaskKey:h})=>{ut(l>0?{phase:"saving",completed:i,total:l}:null),cn(h)}),[p]),yt=r.useCallback(({taskId:i,mockupId:l,colorName:h,previewUrl:v,renderProfile:g,designLastModified:T},W)=>{const se=Xe.find(Ne=>Ne.id===l),q=W?gn({...W,mockupTemplateId:l,colorName:h}):{id:`${g}-${i}`,mockupTemplateId:l,mockupUrl:v,templateName:(se==null?void 0:se.name)||`mockup-${l}`,colorName:h,generatedAt:new Date().toISOString(),designLastModified:T??void 0},J=new Map(He.current).set(i,q);He.current=J,at(J),In(q.mockupUrl)},[Xe]),{enqueue:Rn,defer:Fn,discard:fs,clear:En}=Gc({getKey:km,reveal:yt}),$a=r.useCallback((i,l)=>{const h=gn({...l,mockupTemplateId:i.mockupTemplateId,colorName:i.colorName});Fn(i.taskKey,h)||(sa(i.mockupTemplateId,i.colorName,l),In(l.mockupUrl))},[Fn,sa]),Et=r.useCallback((i,l,h)=>{const v=Cr.current.get(i);if(h&&(v==null?void 0:v.generationOperationId)!==h)return;const g=l instanceof Error?l:new Error(a("Mockup generation failed"));v?Jt.fail(v,g):xs.current.set(i,g),ze(T=>new Map(T).set(i,g.message))},[Jt,a]),Bs=r.useCallback(async(i,l,h,v)=>{const g=Cr.current.get(i);if(!g)throw new Error("Generated mockup attempt metadata is unavailable.");if(l&&g.generationOperationId!==l)return!1;const T=Xe.find(je=>je.id===g.mockupTemplateId),W=await Nd(h,v),[se,q]=await Promise.all([jd(W),wd(g.renderIdentity)]);if(Array.from(He.current.values()).find(je=>kd(je,g,q,se)))return Jt.discard(i),!0;const Ne=Jt.complete(g,{imageData:W,templateName:(T==null?void 0:T.name)||`mockup-${g.mockupTemplateId}`,renderSignature:q,designLastModified:g.canvasReference.lastModified,onCommitted:je=>$a(g,je)});return Ne&&(S==null||S()),Ne},[Xe,Jt,$a,S]),Mr=r.useCallback(i=>{Rn(i)},[Rn]),as=r.useCallback((i,l)=>{var v;fs(g=>g.taskId===i&&g.previewUrl===l);const h=De.current.get(i);if((h==null?void 0:h.objectUrl)===l&&(De.current.delete(i),Gt.current.add(l),ke(g=>g+1)),((v=He.current.get(i))==null?void 0:v.mockupUrl)===l){const g=new Map(He.current);g.delete(i),He.current=g,at(g)}},[fs]),pn=r.useCallback(i=>i.flatMap(l=>{const h=Xe.find(q=>q.id===l.mockupId),v=l.printAreaId||(h==null?void 0:h.printAreaId),g=l.publicRenderProfile,T=v?aa.current.get(`${l.colorName}::${v}`):void 0;if(!h||!v||!Xo(g)||!T&&!Hr(g)){Jt.discard(l.taskId),Cr.current.delete(l.taskId);const q=new Error("The saved canvas reference is not ready for mockup generation.");return xs.current.set(l.taskId,q),ze(J=>new Map(J).set(l.taskId,q.message)),Oe(J=>J.filter(Ne=>Ne!==l.taskId)),[]}const W=T??Pm;fs(q=>q.taskId===l.taskId);const se=Jt.begin({taskKey:l.taskId,mockupTemplateId:l.mockupId,mockupKey:Md(l.mockupId,h.mockupKey),colorName:l.colorName,printAreaId:v,renderProfile:g,canvasReference:W,renderIdentity:Cd(l,h,W,ue)});return Cr.current.set(l.taskId,se),xs.current.delete(l.taskId),[{...l,generationOperationId:se.generationOperationId}]}),[Xe,fs,Jt,ue]),Xr=r.useCallback(i=>{const l=pn(i);
170if(l.length===0){const h=new Set(i.map(v=>v.taskId));Oe(v=>v.filter(g=>!h.has(g))),xr(!1),bt(!0),Or(v=>({...v,totalMockups:0,completedMockups:0}));return}Q==null||Q("mockups"),ut(null),cn(null),Or(h=>({...h,totalMockups:l.length,completedMockups:0})),Tn(l)},[Q,Tn,pn]),bi=r.useCallback(i=>{const[l]=pn([i]);l&&(Q==null||Q("mockups"),As(l))},[As,Q,pn]),ia=r.useRef(ee);r.useEffect(()=>{ia.current=ee},[ee]),r.useEffect(()=>{if(X)return X({scope:"mockups",dependsOn:["design"],hasDeferredWork:i=>Jt.hasUncommittedCandidates(Jo(ia.current,i)),capture:i=>{const l=new Set(ia.current),h=new Set(Array.from(l).filter(T=>Sa.current.has(T))),v=Jt.capture(Jo(l,i)),g=Vc(xs.current,h);return{validate:()=>{var T;if(g)throw g;(T=v.validate)==null||T.call(v)},commit:v.commit,afterAccepted:()=>{w==null||w()}}}})},[Jt,w,X]);const oa=r.useRef(new Map),yi=r.useRef(new Map),Qt=r.useCallback((i,l)=>{if(l){const h=oa.current.get(Eo(i,l));if(h)return h}return yi.current.get(i)||null},[]);r.useEffect(()=>{p&&Vr.current!==p&&(ps.current=!1,Ts.current=!1,un.current=!1,ae.current=!1,le.current=!1,ct.current=!1,ms.current=!1,jr.invalidate(),dn.current=[],Ar.current=[],He.current=new Map,De.current.forEach(({objectUrl:i})=>{Gt.current.add(i)}),De.current.clear(),ke(i=>i+1),aa.current=new Map,Cr.current=new Map,xs.current=new Map,Jt.clear(),En(),oa.current=new Map,yi.current=new Map,Fs.current=null,hs.current=void 0,Vr.current=p,at(new Map),Wt([]),Lt([]),Le((_==null?void 0:_.filter(i=>i.startsWith("custom:")))||[]),pt(kt),$e(he?null:ne),Tt(null),Ba([]),gi(!1),Ve(!1),fr(!1),Oe([]))},[En,p,Jt,jr]);const la=r.useRef(!1);r.useEffect(()=>{ds&&p&&!la.current&&!Ts.current&&(la.current=!0,ps.current=!1,Gr())},[ds,p,Gr]),r.useEffect(()=>{p&&Vr.current!==p&&(la.current=!1)},[p]),r.useEffect(()=>{if(Zt){xe(!0);return}const i=$t==null?void 0:$t.getDesign;if(aa.current=$m(i,M??null),ps.current||vr)return;const l=($t==null?void 0:$t.getSavedMockups)||[],{uploadedMockups:h,uploadedMockupMap:v}=Um(l);if(!(tt!=null&&tt.getAvailableMockupsByProductId)){at(v),Wt(h),He.current=v,ps.current=!0,xe(!1);return}if($t!=null&&$t.getSavedMockups){const g=$t.getDesign,T=tt.getAvailableMockupsByProductId,{byColorArea:W,maxByColor:se}=Bm(g==null?void 0:g.printAreas);if(oa.current=W,yi.current=se,l.length>0){const q=zm(l,v,T,W,se,!!d);at(q),Wt(h),He.current=q,ps.current=!0}else Wt([]),ps.current=!0;if(g!=null&&g.printAreas){const q=_m(g.printAreas,K);$(q),de.current=q}xe(!1)}else!Zt&&p&&(ps.current=!0,xe(!1))},[M,$t,Zt,tt,vr,p,K.size,d]),r.useEffect(()=>{We.length>0&&!N&&!un.current&&(U(We[0]),un.current=!0)},[We.length,N]);const is=r.useRef(null);r.useEffect(()=>{const i=is.current;i!==null&&We.filter(h=>!i.includes(h)).length>0&&(Ts.current=!1),is.current=[...We]},[We]);const os=r.useCallback(async(i,l,h,v=3)=>{try{const g=await Qo(Qr,i,l,h);if(g||!h||v<=0)return g;await new Promise(T=>setTimeout(T,1e3));for(let T=v;T>0;T-=1){await new Promise(se=>setTimeout(se,1e3));const W=await Qo(Qr,i,l,h);if(W)return W}return null}catch(g){return console.error("Failed to find matching mockup template:",g),null}},[]),gr=Y.resolved?Xe:void 0,za=(gr==null?void 0:gr.length)??0;r.useEffect(()=>{if(!Y.resolved)return;const i=(_==null?void 0:_.filter(zl))??[];if(!le.current&&i.length>0&&vr)return;const l=Fm(_,D,I,O,ne,Xe);!le.current&&l&&(nt(l.templateIds),l.customKeys&&Le(l.customKeys),le.current=!0,ae.current=!0);const h=_!==void 0||D!==void 0,v=I!=null||O!=null,g=h||v;if(!ct.current&&g){const T=Em(I,kt,he,ne,Xe);pt(T.customKey),$e(T.templateId),ct.current=!0}},[Y.resolved,Xe,D,_,O,I,kt,he,ne,vr]);const er=r.useCallback(i=>{const l=fo(i);if(_!==void 0||((D==null?void 0:D.length)??0)>0)!he&&ne!=null&&Te===null&&$e(ne);else{const v=bn(l.map(g=>g.id));nt(v),ae.current=v.length>0,v.length>0&&ne==null&&!he&&$e(v[0]??null)}return l},[he,ne,D,_,Te]);r.useEffect(()=>{(ds||Ds&&(!F||dt))&&za>0&&!Ts.current&&!ms.current&&p&&gr&&!Zt&&ps.current&&Ft.length>0&&!ce&&We.length>0&&(Ts.current=!0,(async()=>{const h=wr();if(!p||We.length===0||!gr)return;const v=xo(gr).filter(Pr),g=de.current,T=new Set(We.flatMap(je=>Array.from(Ws(g,je)))),W=v.filter(je=>Hs(je.publicRenderProfile,je.printAreaId,T));if(W.length===0){bt(!0);return}const se=er(W),q=d?fo(W):se,J=Im(We,q,g,ds,He.current),Ne=J.reduce((je,Fe)=>je+Fe.mockups.length,0);if(Ne>0){xr(!0),Or({totalMockups:Ne,completedMockups:0,currentColor:"All colors",totalColors:We.length,completedColors:0});const je=J.flatMap(({color:wt,mockups:ge})=>{var o;const Jr=(o=Ft.find(m=>m.colorName===wt))==null?void 0:o.colorHex;return ge.map(m=>sc(m,wt,Jr,Qt(wt,m.printAreaId)))});$r(h,je.map(wt=>wt.taskId));const Fe=await yl(je,p,os,d);if(!zr(h))return;if(Fe.length>0){if(ms.current)return;Oe(Fe.map(wt=>wt.taskId)),Xr(Fe)}else xr(!1),bt(!0)}else bt(!0)})())},[ds,dt,Ds,F,za,p,ir,We,Zt,Ft.length,ce,Xr,Qt,d,er,wr,$r,zr]);const _a=r.useRef(Date.now());r.useEffect(()=>{_a.current=Date.now()},[Br,ot,Qe,Pe,Sn]),r.useEffect(()=>{if(!(Sn||Qe.length>0||Nr||Nt))return;const l=setTimeout(()=>{if(Date.now()-_a.current<Yo)return;
170jr.invalidate();const h=[...rr.current],v=[...new Set([...h,...dn.current])];dn.current=[],console.warn("[MockupsStep] Generation batch went silent; failing stuck tasks:",v),v.forEach(g=>{Et(g,new Error(a("Mockup generation failed")))}),ns(!1)},Yo);return()=>clearTimeout(l)},[Br,ot,Qe,Pe,Nr,Nt,Sn,Et,ns,jr,a]);const Kr=N||ir,Ga=Be===void 0?I:Be,Un=Ko(Y.photos,Kr,Ga),gs=Un.preview,eo=Y.unavailable&&ri(Ga)&&!gs,Ln=Ws(Rt,Kr),mt=Xe.filter(i=>!(!ce&&!Hs(i.publicRenderProfile,i.printAreaId,Ln))),Dn=r.useMemo(()=>fo(mt),[mt]),ca=r.useMemo(()=>new Set(Dn.map(i=>i.id)),[Dn]),On=r.useMemo(()=>new Set(it),[it]),da=r.useMemo(()=>mt.filter(i=>!ca.has(i.id)&&On.has(i.id)),[mt,ca,On]),$s=r.useMemo(()=>xo([...Dn,...da]),[Dn,da]),Bn=r.useMemo(()=>new Set($s.map(i=>i.id)),[$s]),$n=r.useMemo(()=>mt.filter(i=>!ca.has(i.id)&&!On.has(i.id)),[mt,ca,On]),Es=$n.length,to=Math.min(bl,Es),zn=Es>0;r.useEffect(()=>{At||$s.length===0||gt&&Bn.has(gt)||Wr($s[0].id)},[Bn,$s,At,gt]);const ua=new Set(Xe.map(i=>i.printAreaId)),ro=!ce&&Ln.size>0&&Xe.length>0&&mt.length===0,zs=i=>i.charAt(0).toUpperCase()+i.slice(1).toLowerCase(),Ut=Array.from(Ln).map(zs),H=Array.from(ua).map(zs),ma=async i=>{var v;const l=Xe.find(g=>g.id===i);if(l&&!Pr(l)){ft(l.name);return}if(ee.includes(i))Ye(),nt(g=>g.filter(T=>T!==i)),Te===i&&$e(ee.find(g=>g!==i)||null);else{if(ee.length+Ze+Ue.length>=ws){ie.error(`${a("Select up to")} ${ws} ${a("generated mockups per color")}`);return}Ye(),nt(W=>bn([...W,i],Te)),Tt(null);const g=N||ir,T=(v=Ft.find(W=>W.colorName===g))==null?void 0:v.colorHex;await Ni(i,g,T,l==null?void 0:l.printAreaId),ee.length===0&&!Ke&&!ri(I)&&$e(i)}},vi=r.useCallback(async()=>{if(Nt||ms.current||$n.length===0||!p)return;const i=$n.slice(0,bl);if(i.length===0)return;const l=wr();Ve(!0),Lt(g=>{const T=new Set(g);return i.forEach(W=>T.add(W.id)),Array.from(T)});const h=Sm(i,We,ot,de.current,Ft,Qt);if(h.length===0){Ve(!1);return}$r(l,h.map(g=>g.taskId));const v=await yl(h,p,os,d);if(zr(l))if(v.length>0){if(ms.current){Ve(!1),xr(!1);return}xr(!0),Or({totalMockups:v.length,completedMockups:0,currentColor:"Loading more mockups",totalColors:We.length,completedColors:0}),Oe(g=>[...g,...v.map(T=>T.taskId)]),Xr(v)}else Ve(!1)},[Nt,$n,We,ot,Ft,p,os,Qt,d,Xr,wr,$r,zr]),bs=async()=>{var Ne,je;if(mn.current.length===0){Rs.current=!1;return}Rs.current=!0;const i=mn.current.shift(),{mockupId:l,colorName:h,colorHex:v,printAreaId:g,resolve:T,reject:W}=i;Is.current=h,Bt.current=v,Fs.current=Qt(h,g),hr(v),Ps(h),Da(g),It.current={resolve:T,reject:W};const se=`${l}-${h}`;Oe(Fe=>[...Fe,se]);const q=Xe.find(Fe=>Fe.id===l);if(q&&!Pr(q)){Oe(Fe=>Fe.filter(wt=>wt!==se)),It.current=null,T(),bs();return}if(Hr(q==null?void 0:q.publicRenderProfile)){const Fe={taskId:se,mockupId:l,colorName:h,colorHex:v,psdTemplateUrl:"",designImageUrl:"",publicRenderProfile:"RENDER_PROFILE_A",mockupCode:q.mockupCode,printAreaId:q.printAreaId,designLastModified:Qt(h,q.printAreaId)};bi(Fe),It.current=null,T(),bs();return}if(!q||!qn(q.publicRenderProfile)||!q.psdUrl){const Fe=new Error("Mockup template renderer is unsupported for client-side generation.");console.warn("[MockupsStep] Skipping unsupported mockup template",{mockupId:l,colorName:h,publicRenderProfile:q==null?void 0:q.publicRenderProfile}),ze(wt=>new Map(wt).set(se,Fe.message)),Oe(wt=>wt.filter(ge=>ge!==se)),It.current=null,W(Fe),bs();return}const J=await os(p,h,q.printAreaId);if(J){const[Fe]=pn([{taskId:se,mockupId:l,colorName:h,colorHex:v,psdTemplateUrl:q.psdUrl,designImageUrl:ni(J,Fs.current??d),colorLayerPaths:q.colorLayerPaths,designLayerPath:(je=(Ne=q.designLayers)==null?void 0:Ne.find(wt=>wt.printAreaId===q.printAreaId))==null?void 0:je.layerPath,publicRenderProfile:q.publicRenderProfile,mockupCode:q.mockupCode,printAreaId:q.printAreaId,designLastModified:Fs.current}]);if(!Fe){const wt=xs.current.get(se)??new Error("The saved canvas reference is not ready for mockup generation.");hs.current=void 0,It.current=null,W(wt),bs();return}hs.current=Fe.generationOperationId,Q==null||Q("mockups"),on(J),Re(q)}else console.warn("[MockupsStep] Skipping mockup generation - no design for side",{mockupId:l,colorName:h,printAreaId:q==null?void 0:q.printAreaId,reason:"No designImageUrl for this printArea+color combination"}
170),Oe(Fe=>Fe.filter(wt=>wt!==se)),It.current=null,T(),bs()},Ni=async(i,l,h,v)=>{if(!p)return;const g=Xe.find(W=>W.id===i);if(!g||!Pr(g))return;const T=`${i}-${l}`;if(!He.current.has(T))return new Promise((W,se)=>{mn.current.push({mockupId:i,colorName:l,colorHex:h,printAreaId:v,resolve:W,reject:se}),Rs.current||bs()})},Yr=r.useCallback(async i=>{var se;const l=Is.current;if(!dr||!p||!l)return;const h=dr.id,v=l,g=`${h}-${v}`,T=hs.current;if(!lo((se=Cr.current.get(g))==null?void 0:se.generationOperationId,T))return;const W=i.startsWith("blob:")||i.startsWith("data:")?i:`data:image/jpeg;base64,${i}`;try{Mr({taskId:g,mockupId:h,colorName:v,previewUrl:W,renderProfile:"RENDER_PROFILE_B",designLastModified:Fs.current??void 0}),await Bs(g,T,i)||as(g,W),It.current&&(It.current.resolve(),It.current=null)}catch(q){as(g,W),Et(g,q,T),console.error("[MockupsStep] Failed to capture generated mockup",{key:g,error:q}),It.current&&(It.current.reject(q instanceof Error?q:new Error("Failed to capture generated mockup")),It.current=null)}finally{const q=`${h}-${v}`;Oe(J=>J.filter(Ne=>Ne!==q)),Re(null),on(null),Fs.current=null,hs.current=void 0,bs()}},[Bs,as,p,Et,dr,Mr]),ys=r.useCallback(i=>{const l=Is.current;if(dr&&l){const h=`${dr.id}-${l}`;Oe(v=>v.filter(g=>g!==h)),Et(h,new Error(i),hs.current),console.error("[MockupsStep] Mockup generation failed",{key:h,error:i})}It.current&&(It.current.reject(new Error(i)),It.current=null),Re(null),on(null),Fs.current=null,hs.current=void 0,bs()},[Et,dr]),Va=r.useCallback((i,l)=>{var h;((h=Cr.current.get(i))==null?void 0:h.generationOperationId)===l&&(Oe(v=>v.filter(g=>g!==i)),Tr())},[Tr,Oe]),ji=r.useCallback(async i=>{var je;const{taskId:l,generationOperationId:h,mockupId:v,colorName:g,success:T,imageData:W,imageUrl:se,error:q}=i;if(!(T&&(W||se))){const Fe=q||"Mockup generation failed";console.error("[MockupsStep] Mockup generation failed",{taskId:l,error:q}),Et(l,new Error(Fe),h),Va(l,h);return}const Ne=Am(W,se);try{if(!lo((je=Cr.current.get(l))==null?void 0:je.generationOperationId,h))return;Mr({taskId:l,mockupId:v,colorName:g,previewUrl:Ne,renderProfile:"RENDER_PROFILE_B"}),await Bs(l,h,W,se)||as(l,Ne)}catch(Fe){as(l,Ne),console.error("[MockupsStep] Failed to capture generated mockup",{taskId:l,captureError:Fe}),Et(l,Fe,h)}finally{Va(l,h)}},[Bs,as,Et,Va,Mr]),wi=r.useCallback(()=>{rs.current=!0,Tr()},[Tr]),ki=r.useCallback((i,l)=>{Or(h=>({...h,completedMockups:i,totalMockups:l}))},[]),Ci=r.useCallback(()=>{xr(!1)},[]),pa=r.useMemo(()=>_l(K),[K]),rt=r.useMemo(()=>Os.filter(i=>Hr(i.publicRenderProfile)),[Os]),ha=r.useMemo(()=>Os.filter(i=>qn(i.publicRenderProfile)),[Os]),_s=r.useMemo(()=>Ra.map(i=>({mockupId:i.id,mockupCode:i.mockupCode||i.id.toString(),printAreaId:i.printAreaId,extractedShadowUrl:i.extractedShadowUrl||null,extractedHighlightUrl:i.extractedHighlightUrl||null,extractedForegroundUrl:i.extractedForegroundUrl||null,extractedMaskUrl:i.extractedMaskUrl||null,extractedBackgroundUrl:i.extractedBackgroundUrl||null,designPlacementX:i.designPlacementX??null,designPlacementY:i.designPlacementY??null,designPlacementWidth:i.designPlacementWidth??null,designPlacementHeight:i.designPlacementHeight??null,designPlacementRotation:i.designPlacementRotation??null,psdWidth:i.psdWidth||1200,psdHeight:i.psdHeight||1200,templateId:Ua||""})),[Ra,Ua]),Mi=r.useCallback(i=>{var se,q;const{taskId:l,generationOperationId:h,mockupId:v,colorName:g,blobUrl:T}=i;if(!lo((se=Cr.current.get(l))==null?void 0:se.generationOperationId,h)){URL.revokeObjectURL(T);return}const W=Cr.current.get(l);if(W){const J=K.get(`${W.colorName}-${W.printAreaId}`),Ne=Pd(J),je=(q=De.current.get(l))==null?void 0:q.objectUrl;je!==T&&Gl(T),je&&je!==T&&Gt.current.add(je),De.current.set(l,{objectUrl:T,printAreaId:W.printAreaId,sourceToken:Ne}),ke(Fe=>Fe+1)}Mr({taskId:l,mockupId:v,colorName:g,previewUrl:T,renderProfile:"RENDER_PROFILE_A"}),Bs(l,h,T).then(J=>{J||as(l,T)}).catch(J=>{as(l,T),Et(l,J,h)}).finally(()=>{var J;((J=Cr.current.get(l))==null?void 0:J.generationOperationId)===h&&(Oe(Ne=>Ne.filter(je=>je!==l)),Tr())})},[Bs,as,Et,Tr,Mr,Oe,K]),Ka=r.useCallback(i=>{const l=kr(),h=new Set;for(const v of l){const g=_s.find(se=>se.mockupId===v.mockupId),T=(g==null?void 0:g.mockupCode)||"",W=i.get(T);W!=null&&W.has(v.colorName)||(h.add(v.taskId),Et(v.taskId,new Error("No design image available or render failed"),v.generationOperationId))}h.size>0&&Oe(v=>v.filter(g=>!h.has(g))),Ce.current=!0,Tr()},[Et,Tr,kr,_s,Oe]),Pi=r.useCallback((i,l)=>{Or(h=>({...h,completedMockups:i,totalMockups:l}
170)),Ho(i,l)&&(Ce.current=!0,Tr())},[Tr]);r.useEffect(()=>{var l;if(sn.current===ue)return;if(sn.current=ue,wr(),En(),!Ds||_s.length===0){xr(!1),bt(!0);return}console.log(`[MockupsStep] Color mode â ${ue}, rebuilding tasks`);const i=[];for(const h of We){const v=(l=Ft.find(g=>g.colorName===h))==null?void 0:l.colorHex;for(const g of _s)i.push({taskId:`${g.mockupId}-${h}`,mockupId:g.mockupId,colorName:h,colorHex:v,psdTemplateUrl:"",designImageUrl:"",publicRenderProfile:"RENDER_PROFILE_A",mockupCode:g.mockupCode,printAreaId:g.printAreaId,designLastModified:Qt(h,g.printAreaId)})}i.length>0?(Oe(i.map(h=>h.taskId)),Xr(i)):(xr(!1),bt(!0))},[ue,Ds,_s,We,Ft,Qt,Xr,En,wr]);const hn=r.useMemo(()=>Kc(St.keys(),ee),[St,ee]),_n=Qc({requiredDesignImagesFailed:F&&dt,selectedGenerationFailureCount:hn}),Ya=xt==="generated"&&We.length>0&&Ft.length>0&&Ls.some(i=>Ks(i.publicRenderProfile,i.psdUrl)),Ii=Ya&&ot.size>0&&We.every(i=>{const l=Ws(Rt,i);return Ls.every(h=>!Ks(h.publicRenderProfile,h.psdUrl)||!Hs(h.publicRenderProfile,h.printAreaId,l)||ot.has(`${h.id}-${i}`))}),vs=Yc({mockupsLoading:vr,savedMockupsLoading:Zt,designedAreasLoading:ce,rendererInputsLoading:ks||pr,hasRenderableMockupWork:Ya,imagesReady:!F||ds,designImagesFailed:dt,isGenerationComplete:Oa,isParallelGenerating:Nr,generatingTaskCount:Qe.length,isLoadingSecondaryMockups:Nt,isPreparingGeneration:Sn,savedMockupsCoverSelection:Ii}),Gn=t||vs,Vn=!!we||Gn||Y.loading,Ha=i=>{Vn||(B==null||B(i),ri(I)&&!i.includes(I)&&(A==null||A(null)),Ye())},Si=r.useCallback(i=>{Gn||i===ue||(bt(!1),me==null||me(i))},[ue,Gn,me]);r.useEffect(()=>{s==null||s(vs)},[vs,s]),r.useEffect(()=>{if(Br){n==null||n(Br);return}if(vs&&(Nr||Qe.length>0)&&Pe.totalMockups>0){n==null||n({phase:"preparing",completed:Pe.completedMockups,total:Pe.totalMockups});return}if(vs&&!ds&&ta>0){n==null||n({phase:"preparing",completed:Ea,total:ta});return}n==null||n(null)},[Br,Ea,Pe.completedMockups,Pe.totalMockups,Qe.length,ds,Nr,vs,n,ta]),r.useEffect(()=>{!t&&Br&&Ho(Br.completed,Br.total)&&(ut(null),cn(null))},[Br,t]),r.useEffect(()=>()=>{s==null||s(!1),n==null||n(null)},[s,n]),r.useEffect(()=>re?(re("mockups",async()=>{if(Ms(null),Ee)throw ie.error(a(Ee)),new Error(Ee);if(vs||Pn||Nr||Qe.length>0){const l=a("Mockups are still preparing. Please wait until generation finishes before continuing.");throw Ms(l),ie.error(a("Mockups are still preparing"),{description:a("We will keep you on this step so your store does not publish with missing images.")}),new Error(l)}if(_n==="design-images"){const l=a("One or more high-resolution design images could not be prepared. Please retry from the design step or contact support.");throw Ms(l),ie.error(a("Design image rendering failed"),{description:l}),new Error(l)}if(_n==="selected-mockups"){const l=`${hn} ${a(hn>1?"selected mockups":"selected mockup")} ${a("failed to generate. Retry generation before continuing.")}`;throw Ms(l),ie.error(a("Some selected mockups need attention"),{description:a("Retry the failed mockups before moving to the next step.")}),new Error(l)}}),()=>re("mockups",null)):void 0,[re,Ee,vs,Pn,Nr,Qe.length,_n,a,hn]);const Ai=r.useCallback(async()=>{var je,Fe,wt;const i=wr(),l=new Set(St.keys());if(fs(ge=>l.has(ge.taskId)),l.forEach(ge=>{Jt.discard(ge),Cr.current.delete(ge),xs.current.delete(ge)}),ze(new Map),bt(!1),ss(!1),_r([]),Oe([]),await new Promise(ge=>setTimeout(ge,100)),!jr.isCurrent(i)||!p||!gr||We.length===0||Ft.length===0)return;const h=gr.filter(Pr),v=de.current,g=new Set;for(const ge of We)Ws(v,ge).forEach(o=>g.add(o));const T=h.filter(ge=>Hs(ge.publicRenderProfile,ge.printAreaId,g)),W=[];let se=0;for(const ge of We){const Jr=Ws(v,ge),o=T.filter(m=>{const V=`${m.id}-${ge}`,te=Hs(m.publicRenderProfile,m.printAreaId,Jr),Ie=Ks(m.publicRenderProfile,m.psdUrl),_e=!He.current.has(V);return Ie&&te&&_e});W.push({color:ge,mockups:o}),se+=o.length}if(se===0){xr(!1),bt(!0);return}xr(!0),Or({totalMockups:se,completedMockups:0,currentColor:"All colors",totalColors:We.length,completedColors:0});const q=[];for(const{color:ge,mockups:Jr}of W){const o=(je=Ft.find(m=>m.colorName===ge))==null?void 0:je.colorHex;for(const m of Jr)Ks(m.publicRenderProfile,m.psdUrl)&&q.push({taskId:`${m.id}-${ge}`,mockupId:m.id,colorName:ge,colorHex:o,psdTemplateUrl:m.psdUrl||"",printAreaId:m.printAreaId,colorLayerPaths:m.colorLayerPaths,designLayerPath:(wt=(Fe=m.designLayers)==null?void 0:Fe.find(V=>V.printAreaId===m.printAreaId))==null?void 0:wt.layerPath,publicRenderProfile:m.publicRenderProfile,mockupCode:m.mockupCode,designLastModified:Qt(ge,m.printAreaId)})}$r(i,q.map(ge=>ge.taskId));const Ne=(await Promise.all(q.map(async ge=>{if(Hr(ge.publicRenderProfile))return{task:ge,designUrl:""};const Jr=await os(p,ge.colorName,ge.printAreaId);return{task:ge,designUrl:Jr}}))).filter(({designUrl:ge})=>ge!==null).map(({task:ge,designUrl:Jr})=>({taskId:ge.taskId,mockupId:ge.mockupId,colorName:ge.colorName,colorHex:ge.colorHex,psdTemplateUrl:ge.psdTemplateUrl,designImageUrl:ni(Jr||"",ge.designLastModified??d),colorLayerPaths:ge.colorLayerPaths,designLayerPath:ge.designLayerPath,publicRenderProfile:ge.publicRenderProfile,mockupCode:ge.mockupCode,printAreaId:ge.printAreaId,designLastModified:ge.designLastModified}));zr(i)&&(Ne.length>0?(Oe(Ne.map(ge=>ge.taskId)),Xr(Ne)):(xr(!1),bt(!0)))},[p,gr,We,Ft,os,Qt,d,Xr,St,fs,Jt,jr,wr,$r,zr]),Ti=r.useCallback(async()=>{u&&await u()},[u]),Kn=r.useCallback(i=>{Wt(l=>{const h=new Map;
170return[...l,...i].forEach(v=>{const g=or(v);!g||!v.colorName||h.set(`${g}-${v.colorName}`,gn(v))}),Array.from(h.values())})},[]),Ns=r.useCallback(async i=>{try{await Gr()}catch(l){console.warn("%s",i,l)}},[Gr]),Yn=r.useCallback(i=>{Ye(),Kn(i);const l=i.map(or).filter(T=>!!T);Le(T=>[...new Set([...T,...l])]);const h=N||ir,v=i.find(T=>T.colorName===h)||i[0],g=v?or(v):l[0];g&&Tt(g),!Ke&&Te===null&&g&&pt(g)},[ir,Ye,Kn,Ke,Te,N]),Gs=r.useCallback(async(i,l,h,v,g)=>{var J;const W=(J=(await xi({variables:{designId:i,mockupKey:l,imageData:h,templateName:v,originalFileName:g}})).data)==null?void 0:J.replaceCustomerMockup,se=W?gn(W):void 0;if(!(se!=null&&se.mockupUrl))throw new Error(a("Replace returned no mockup URL"));const q=or(se)||l;Ye(),Kn([se]),Le(Ne=>Ne.includes(q)?Ne:[...Ne,q]),Ke===l&&pt(q),(At===l||xt==="upload")&&Tt(q),ie.success(a("Uploaded mockup replaced")),await Ns("[MockupsStep] Failed to refresh uploaded mockups after replacement")},[Ye,Kn,xt,a,At,Ke,Ns,xi]),Wa=r.useCallback(async(i,l,h,v,g,T)=>{var W;for(const se of l){const J=(W=(await Cs({variables:{designId:i,colorName:se,imageData:h,templateName:v,printAreaId:"front",originalFileName:g}})).data)==null?void 0:W.uploadCustomerMockup,Ne=J?gn(J):void 0;Ne!=null&&Ne.mockupUrl&&T.push(Ne)}},[Cs]),ls=r.useCallback(async(i,l)=>{const h=i instanceof Error?i.message:a("Failed to upload mockup");if(l.length===0){Mt(h),ie.error(a("Mockup upload failed"),{description:h});return}Yn(l),await Ns("[MockupsStep] Failed to refresh uploaded mockups after partial upload");const v=`${a("Uploaded")} ${l.length} ${a(l.length>1?"mockups":"mockup")}, ${a("but the remaining upload failed:")} ${h}`;Mt(v),ie.error(a("Some mockups uploaded"),{description:v})},[Yn,a,Ns]),Ri=r.useCallback(()=>{Vt.current&&(Vt.current.value="",Vt.current.click())},[]),qa=r.useCallback(i=>{Xt.current=i,Kt.current&&(Kt.current.value="",Kt.current.click())},[]),xn=r.useCallback(async(i,l)=>{if(!p){Mt(a("Save your design before uploading a mockup."));return}const h=Om(i,a);if(h){Mt(h);return}Mt(null),qt(!0),Ct(l||"upload");let v=[];try{const g=await Lm(i,a("Failed to read image file")),T=Dm(i.name)||"Uploaded mockup";if(l){await Gs(p,l,g,T,i.name);return}const W=Lr==="all"?We:[N||ir],se=[];if(v=se,await Wa(p,W,g,T,i.name,se),se.length===0)throw new Error(a("Upload returned no mockups"));Yn(se),ie.success(`${a("Uploaded")} ${se.length} ${a(se.length>1?"mockups":"mockup")}`),await Ns("[MockupsStep] Failed to refresh uploaded mockups after upload")}catch(g){await ls(g,v)}finally{qt(!1),Ct(null),Xt.current=null,Vt.current&&(Vt.current.value=""),Kt.current&&(Kt.current.value="")}},[ir,p,Yn,a,N,Ns,ls,Gs,We,Wa,Lr]),cs=r.useCallback(i=>{Ye(),Le(l=>{if(l.includes(i)){const h=l.filter(v=>v!==i);return Ke===i&&pt(null),h}return ee.length===0&&Te===null&&!Ke&&!ri(I)&&pt(i),l.length+ee.length+Ze>=ws?(ie.error("Select up to 10 mockup views. Deselect a view first."),l):[...l,i]})},[Ze,I,Ye,Ke,Te,ee.length]),Xa=r.useCallback(i=>{if(we)return;if(!Ue.includes(i)&&ee.length+Ue.length+Ze>=ws){ie.error("Select up to 10 mockup views. Deselect a view first.");return}if(!(Ke!==i||Te!==null||!Ue.includes(i))){Tt(i);return}Ye(),pt(i),$e(null),Le(h=>h.includes(i)?h:[...h,i]),Tt(i)},[Ze,ee.length,we,Ye,Ke,Te,Ue]),Fi=r.useCallback(async i=>{var l;if(!(!p||we)&&!(ye&&!globalThis.confirm(a("Remove this uploaded mockup from the design? Store updates will no longer include it.")))){Ct(i),Mt(null);try{if(((l=(await nn({variables:{designId:p,mockupKey:i}})).data)==null?void 0:l.deleteCustomerMockup)!==!0)throw new Error(a("Delete was not confirmed by the server"));Ye(),Wt(v=>v.filter(g=>or(g)!==i)),Le(v=>v.filter(g=>g!==i)),Ke===i&&pt(null),At===i&&Tt(null),ie.success(a("Uploaded mockup removed")),await Gr()}catch(h){const v=h instanceof Error?h.message:a("Failed to delete mockup");Mt(v),ie.error(a("Could not remove mockup"),{description:v})}finally{Ct(null)}}},[nn,p,ye,we,Ye,a,At,Ke,Gr]),Ei=i=>{if(!ee.includes(i)&&ee.length+Ze+Ue.length>=ws){ie.error(`${a("Select up to")} ${ws} ${a("generated mockups per color")}`);return}(Te!==i||Ke!==null||!ee.includes(i))&&(Ye(),$e(i),pt(null),nt(h=>h.includes(i)?h:bn([...h,i],i)))},Za=i=>{Ae(null),Wr(i),Tt(null),Ei(i)},Zr=i=>{Ae(null),Xa(i)},Hn=(i,l)=>{if(l){const h=mt.findIndex(v=>v.id===i.id);h!==-1&&(oe(h),j(!0))}},Ja=r.useMemo(()=>[...lt].sort((l,h)=>l.colorName===Kr&&h.colorName!==Kr?-1:h.colorName===Kr&&l.colorName!==Kr?1:(h.uploadedAt||h.generatedAt||"").localeCompare(l.uploadedAt||l.generatedAt||"")).filter((l,h,v)=>{const g=or(l);return g?v.findIndex(W=>or(W)===g&&W.colorName===l.colorName)===h:!1}),[lt,Kr]),Qa=r.useCallback(i=>{if(i)return lt.find(l=>or(l)===i&&l.colorName===Kr)||lt.find(l=>or(l)===i)},[lt,Kr]),xa=()=>{j(!1),fe(1),qe({x:0,y:0}),jt(!1)},so=i=>{i.stopPropagation(),z===1?fe(2):z===2?fe(3):(fe(1),qe({x:0,y:0}))},no=i=>{z>1&&(i.preventDefault(),jt(!0),ar({x:i.clientX-ve.x,y:i.clientY-ve.y}))},ao=i=>{if(Ot&&z>1){const l=i.clientX-nr.x,h=i.clientY-nr.y,v=(z-1)*200;qe({x:Math.max(-v,Math.min(v,l)),y:Math.max(-v,Math.min(v,h))})}},Ui=()=>{jt(!1)},fn=i=>{oe(i),fe(1),qe({x:0,y:0})};r.useEffect(()=>{if(!f)return;const i=l=>{if(l.key==="Escape")xa();else if(l.key==="ArrowLeft"){const h=Z>0?Z-1:mt.length-1;fn(h)}else if(l.key==="ArrowRight"){const h=Z<mt.length-1?Z+1:0;fn(h)}};return globalThis.addEventListener("keydown",i),()=>globalThis.removeEventListener("keydown",i)},[f,Z,mt.length]);const io=r.useCallback(async(i,l)=>{var J,Ne;const h=wr(),v=`${i}-${l}`;fs(je=>je.taskId===v),Jt.discard(v),Cr.current.delete(v),xs.current.delete(v),ze(je=>{const Fe=new Map(je);return Fe.delete(v),Fe}),at(je=>{const Fe=new Map(je);return Fe.delete(v),He.current=Fe,Fe});const g=Xe.find(je=>je.id===i);if(!g||!p){console.error("[MockupsStep] Mockup template not found for retry",{mockupId:i});return}if(!Pr(g)){ft(g.name);return}if(!Ks(g.publicRenderProfile,g.psdUrl)){const je=a("Mockup template renderer is unsupported for client-side generation.");console.error("[MockupsStep] Unsupported mockup renderer",{message:je,mockupId:i,publicRenderProfile:g.publicRenderProfile}),ze(Fe=>new Map(Fe).set(v,je));return}const T=Ft.find(je=>je.colorName===l),W=T==null?void 0:T.colorHex;xr(!0),Or({totalMockups:1,completedMockups:0,currentColor:l,totalColors:1,completedColors:0}),$r(h,[v]);const se=Hr(g.publicRenderProfile)?"":await os(p,l,g.printAreaId);if(!zr(h))return;if(!se&&!Hr(g.publicRenderProfile)){console.error(`[MockupsStep] No design URL for retry: ${v}`),xr(!1),ze(je=>
170new Map(je).set(v,a("No design image available for this print area")));return}const q={taskId:v,mockupId:i,colorName:l,colorHex:W,psdTemplateUrl:g.psdUrl||"",designImageUrl:ni(se||"",Qt(l,g.printAreaId)??d),colorLayerPaths:g.colorLayerPaths,designLayerPath:(Ne=(J=g.designLayers)==null?void 0:J[0])==null?void 0:Ne.layerPath,publicRenderProfile:g.publicRenderProfile,mockupCode:g.mockupCode,designCoverage:g.designCoverage,coverageWidth:g.coverageWidth,coverageHeight:g.coverageHeight,designLayers:g.designLayers,printAreaId:g.printAreaId,designLastModified:Qt(l,g.printAreaId)};Oe([v]),Xr([q])},[Xe,Ft,p,d,Qt,a,Xr,fs,Jt,wr,$r,zr]);if(hi)return e.jsx(Rr.div,{className:"space-y-6",initial:{opacity:0},animate:{opacity:1},transition:{duration:.4},children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-4",children:[e.jsx("div",{className:"p-4 rounded-full bg-red-100 mb-4",children:e.jsx(Fr,{className:"h-8 w-8 text-red-600"})}),e.jsx("h2",{className:"text-xl font-semibold text-slate-900 mb-2",children:a("Session Expired")}),e.jsx("p",{className:"text-slate-600 text-center mb-6 max-w-md",children:a("Your session has expired. Please log in again to continue generating mockups.")}),e.jsx(pe,{onClick:()=>globalThis.location.href="/login",className:"bg-emerald-600 hover:bg-emerald-700 text-white",children:a("Log In Again")})]})});const ei=async i=>{var g;if(N!==i&&Ye(),U(i),xt==="upload"){const T=Ja.find(W=>W.colorName===i);Tt(T?or(T):null),Wr(null);return}if(Nr||Pn)return;const l=Ws(de.current,i),h=(g=Ft.find(T=>T.colorName===i))==null?void 0:g.colorHex,v=Xe.filter(T=>{const W=`${T.id}-${i}`,se=Hs(T.publicRenderProfile,T.printAreaId,l),q=Ks(T.publicRenderProfile,T.psdUrl),J=ee.includes(T.id),Ne=!He.current.has(W);return Pr(T)&&q&&se&&J&&Ne});if(v.length>0){const T=wr();xr(!0),Or({totalMockups:v.length,completedMockups:0,currentColor:i,totalColors:1,completedColors:0});const W=v.filter(J=>Ks(J.publicRenderProfile,J.psdUrl)).map(J=>{var Ne,je;return{taskId:`${J.id}-${i}`,mockupId:J.id,colorName:i,colorHex:h,psdTemplateUrl:J.psdUrl||"",printAreaId:J.printAreaId,colorLayerPaths:J.colorLayerPaths,designLayerPath:(je=(Ne=J.designLayers)==null?void 0:Ne[0])==null?void 0:je.layerPath,publicRenderProfile:J.publicRenderProfile,mockupCode:J.mockupCode,designLastModified:Qt(i,J.printAreaId)}});$r(T,W.map(J=>J.taskId));const q=(await Promise.all(W.map(async J=>{if(Hr(J.publicRenderProfile))return{task:J,designUrl:""};const Ne=await os(p,J.colorName,J.printAreaId);return{task:J,designUrl:Ne}}))).filter(({designUrl:J})=>J!==null).map(({task:J,designUrl:Ne})=>({taskId:J.taskId,mockupId:J.mockupId,colorName:J.colorName,colorHex:J.colorHex,psdTemplateUrl:J.psdTemplateUrl,designImageUrl:ni(Ne||"",J.designLastModified??d),colorLayerPaths:J.colorLayerPaths,designLayerPath:J.designLayerPath,publicRenderProfile:J.publicRenderProfile,mockupCode:J.mockupCode,printAreaId:J.printAreaId,designLastModified:J.designLastModified}));if(!zr(T))return;q.length>0?(Oe(J=>[...J,...q.map(Ne=>Ne.taskId)]),Xr(q)):xr(!1)}};return e.jsxs(Rr.div,{className:"space-y-6",initial:{opacity:0}
170,animate:{opacity:1},transition:{duration:.4},children:[e.jsx(Hc,{isVisible:Pn,totalMockups:Pe.totalMockups,completedMockups:Pe.completedMockups,currentColor:Pe.currentColor,totalColors:Pe.totalColors,completedColors:Pe.completedColors,latestMockupUrl:Ss,onRefresh:Ai,failedCount:St.size,isComplete:Oa,onDismiss:Ci}),e.jsxs(Rr.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},transition:{duration:.4,delay:.1},className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2.5 rounded-xl bg-gradient-to-br from-emerald-500 to-teal-600 shadow-lg shadow-emerald-500/20",children:e.jsx(Ir,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold bg-gradient-to-r from-slate-900 to-slate-700 bg-clip-text text-transparent",children:a("Select Mockups")}),e.jsx("p",{className:"text-sm text-slate-500",children:a("Choose product mockups to showcase your design")})]})]}),an&&e.jsxs(Rr.div,{initial:{opacity:0,y:-8},animate:{opacity:1,y:0},className:"flex flex-col gap-3 rounded-[14px] border border-amber-200 bg-amber-50 p-4 shadow-sm sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full bg-amber-100 text-amber-700",children:e.jsx(Fr,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold text-amber-900",children:a("Mockups are not fully saved")}),e.jsx("p",{className:"mt-1 text-sm text-amber-800",children:an})]})]}),e.jsxs(pe,{type:"button",size:"sm",variant:"outline",onClick:()=>void Ti(),disabled:E,className:"h-9 flex-shrink-0 border-amber-300 bg-white text-amber-900 hover:bg-amber-100",children:[E?e.jsx(mr,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Us,{className:"mr-2 h-4 w-4"}),a("Retry save")]})]}),ye&&e.jsxs(Rr.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},transition:{duration:.3},className:"flex items-start gap-3 p-4 bg-amber-50 border border-amber-200 rounded-xl",children:[e.jsx(Fr,{className:"h-5 w-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-amber-800",children:a("Updating mockups will replace existing media")}),e.jsx("p",{className:"text-sm text-amber-700 mt-0.5",children:a("Updating mockups will remove your existing mockups and media files from your store listing. Any mockups you select here will replace the current product images.")})]})]}),we&&e.jsxs(Rr.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},transition:{duration:.3},className:"flex items-start gap-3 p-4 bg-slate-100 border border-slate-200 rounded-xl",children:[e.jsx(Zn,{className:"h-5 w-5 text-slate-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-slate-800",children:a("View Only Mode")}),e.jsx("p",{className:"text-sm text-slate-600 mt-0.5",children:a("You are viewing this design in read-only mode. Mockup selection is disabled.")})]})]}),e.jsx(Bi,{children:dt&&F&&e.jsxs(Rr.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},exit:{opacity:0,y:-10},className:"flex items-start gap-3 p-4 bg-red-50 border border-red-200 rounded-xl",children:[e.jsx(Fr,{className:"h-5 w-5 text-red-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-red-900",children:a("Design image rendering failed")}),e.jsx("p",{className:"text-sm text-red-700 mt-0.5",children:((ga=cr[0])==null?void 0:ga.errorMessage)||a("One or more high-resolution design images could not be prepared. Please retry from the design step or contact support.")})]})]})}),e.jsx(Bi,{children:!ds&&!dt&&F&&e.jsxs(Rr.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},exit:{opacity:0,y:-10},className:"relative overflow-hidden bg-gradient-to-r from-blue-50 via-indigo-50 to-blue-50 border border-blue-200/60 rounded-2xl p-5 shadow-sm",children:[e.jsx(Rr.div,{className:"absolute inset-0 bg-gradient-to-r from-transparent via-white/40 to-transparent",animate:{x:["-100%","200%"]},transition:{duration:2,repeat:1/0,ease:"linear"}}),e.jsxs("div",{className:"relative flex items-center gap-4",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsxs("div",{className:"relative w-12 h-12",children:[e.jsxs("svg",{className:"w-full h-full -rotate-90",children:[e.jsx("circle",{cx:"24",cy:"24",r:"20",stroke:"#e0e7ff",strokeWidth:"4",fill:"none"}
170),e.jsx("circle",{cx:"24",cy:"24",r:"20",stroke:"url(#progressGradient)",strokeWidth:"4",fill:"none",strokeDasharray:2*Math.PI*20,strokeDashoffset:2*Math.PI*20*(1-pi),className:"transition-all duration-300",strokeLinecap:"round"}),e.jsx("defs",{children:e.jsxs("linearGradient",{id:"progressGradient",x1:"0%",y1:"0%",x2:"100%",y2:"0%",children:[e.jsx("stop",{offset:"0%",stopColor:"#3b82f6"}),e.jsx("stop",{offset:"100%",stopColor:"#8b5cf6"})]})})]}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsxs("span",{className:"text-sm font-bold bg-gradient-to-r from-blue-600 to-indigo-600 bg-clip-text text-transparent",children:[Math.round(pi*100),"%"]})})]})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Ca,{className:"h-4 w-4 text-blue-500"}),e.jsxs("p",{className:"text-sm font-semibold text-slate-800",children:[a("Preparing design images")," (",Ea,"/",ta,")"]})]}),e.jsx("p",{className:"text-xs text-slate-500",children:a("Your high-resolution designs are being rendered. You can browse mockups while waiting.")})]})]})]})}),e.jsx(Bi,{children:tn&&F&&e.jsx(Rr.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},exit:{opacity:0,y:-10},className:"bg-gradient-to-r from-amber-50 via-orange-50 to-amber-50 border border-amber-200/60 rounded-2xl p-5 shadow-sm",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"w-10 h-10 rounded-xl flex items-center justify-center shadow-lg bg-gradient-to-br from-amber-400 to-orange-500 shadow-amber-500/20",children:e.jsx(Fr,{className:"h-5 w-5 text-white"})})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-amber-800",children:a("Your design images are taking longer than usual")}),e.jsx("p",{className:"text-xs text-amber-600 mt-0.5",children:a("We are still preparing them. Keep this page open; mockup generation will begin automatically when every image is ready.")})]}),e.jsx(pe,{variant:"outline",size:"sm",className:"flex-shrink-0 border-amber-300 text-amber-700 hover:bg-amber-100",onClick:()=>globalThis.location.reload(),children:a("Retry")})]})})}),e.jsx(Bi,{children:ro&&e.jsx(Rr.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},exit:{opacity:0,y:-10},className:"bg-gradient-to-r from-blue-50 via-indigo-50 to-blue-50 border border-blue-200/60 rounded-2xl p-5 shadow-sm",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"w-10 h-10 rounded-xl bg-gradient-to-br from-blue-400 to-indigo-500 flex items-center justify-center shadow-lg shadow-blue-500/20",children:e.jsx(Fr,{className:"h-5 w-5 text-white"})})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-blue-800",children:a("No mockups available for your designed print area")}),e.jsxs("p",{className:"text-xs text-blue-600 mt-1",children:[a("You designed on the")," ",e.jsx("span",{className:"font-semibold",children:Ut.join(", ")})," ",a(Ut.length===1?"area":"areas"),", ",a("but mockups are only available for")," ",e.jsx("span",{className:"font-semibold",children:H.join(", ")}),"."]}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-3",children:[e.jsxs(pe,{variant:"outline",size:"sm",className:"border-blue-300 text-blue-700 hover:bg-blue-100",onClick:y,children:[a("Add")," ",H[0]," ",a("Design")]}),e.jsx(pe,{variant:"ghost",size:"sm",className:"text-blue-600 hover:bg-blue-100",onClick:u,children:a("Continue Without Mockups")})]})]})]})})}),e.jsx(Rr.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.4,delay:.2},children:e.jsx(cp,{stockUnavailable:Y.unavailable,stockCount:Un.photos.length,stockViewIndex:Zc($s,(tt==null?void 0:tt.getAvailableMockupsByProductId)||[]),stockViews:e.jsx(Xc,{photos:Un.photos,selectedKeys:_||[],primaryKey:I,previewKey:gs?Na(gs):null,disabled:Vn,onPreview:Ae,onSelectionChange:Ha}),stockNotices:e.jsx(qc,{disabled:Vn,visiblePhotoCount:Un.photos.length,stock:Y,selectedKeys:_||[],onSelectionChange:Ha}),stockPreview:gs?e.jsx(Wc,{photo:gs,primary:I===Na(gs),selected:(_==null?void 0:_.includes(Na(gs)))??!1,disabled:Vn,onPrimary:()=>{$e(null),pt(null),A==null||A(Na(gs)),Ye()}}):eo?e.jsx("p",{role:"status",children:"No label reference is available for this color."}
170):null,mockupsLoading:vr,availableMockups:Xe,isViewOnly:we??!1,hasPrintAreaMismatch:ro,designedPrintAreasList:Ut,mockupPrintAreasList:H,goToNextStep:u,mockupsCopy:a,primaryVariant:N,currentColor:ir,selectedColors:We,colorVariants:Ft,displayCustomerUploadedMockups:Ja,selectedCustomMockupKeys:Ue,primaryCustomMockupKey:Ke,previewCustomMockupKey:At,mockupSourceMode:xt,getCustomPreviewMockup:Qa,previewMockupId:gt,displayedMockups:$s,filteredMockups:mt,generatedMockups:ot,generatingMockups:Qe,savingMockupTaskKey:us,failedMockups:St,designedPrintAreasPerColorRef:de,selectedMockups:ee,mockupControlsLocked:Gn,isParallelGenerating:Nr,primaryMockup:Te,uploadScope:Lr,isUploadingCustomMockup:Dt,customMockupBusyKey:lr,customMockupError:yr,hasSecondaryMockups:zn,isLoadingSecondary:Nt,nextSecondaryBatchCount:to,remainingSecondaryCount:Es,hasRenderProfileAMockups:Ds,mockupColorMode:ue,uploadInputRef:Vt,replaceInputRef:Kt,replaceCustomMockupKeyRef:Xt,setMockupSourceMode:i=>{Ae(null),et(i)},setPreviewCustomMockupKey:i=>{Ae(null),Tt(i)},setPreviewMockupId:i=>{Ae(null),Wr(i)},setUploadScope:Dr,setPrimaryCustomMockupKey:pt,setSelectedCustomMockupKeys:Le,setSelectedMockups:i=>nt(l=>bn(typeof i=="function"?i(l):i,Te,ws-Ze-Ue.length)),setLockedPremiumMockupName:ft,markMockupSelectionDirty:Ye,requestMockupColorMode:Si,openCustomMockupUploadPicker:Ri,openCustomMockupReplacePicker:qa,handleZoom:Hn,handleCustomMockupFile:xn,handleColorChoice:ei,handleSelectMockup:ma,handleSetPrimary:Ei,handleSelectCustomMockup:cs,handleSetPrimaryCustomMockup:Xa,handleUploadedMockupPrimaryClick:Zr,handleGeneratedMockupPrimaryClick:Za,handleDeleteCustomMockup:Fi,handleRetry:io,handleLoadMoreMockups:vi,renderGeneratedThumbnailLoading:Yt})}),Nr&&Ds&&rt.length>0&&e.jsx(Id,{tasks:rt,mockupItems:_s,getCanvasJson:pa,getCurrentTasks:kr,designId:p||"",colorMode:ue,onMockupComplete:Mi,onAllComplete:Ka,onProgress:Pi},`renderProfileA-generator-${rt.map(i=>i.generationOperationId).join("|")}`),Nr&&ha.length>0&&e.jsx(Jc,{tasks:ha,designId:p||void 0,maxConcurrency:2,onMockupComplete:ji,onAllComplete:wi,onProgress:ki},`parallel-generator-${ha.map(i=>i.generationOperationId).join("|")}`),!Nr&&dr&&qn(dr.publicRenderProfile)&&na&&e.jsx(Iu,{psdTemplateUrl:dr.psdUrl,designImageUrl:na,colorHex:La,onMockupGenerated:Yr,onError:ys,onProgress:()=>{},colorLayerPaths:dr.colorLayerPaths,designLayerPath:(Di=(ba=dr.designLayers)==null?void 0:ba.find(i=>i.printAreaId===dr.printAreaId))==null?void 0:Di.layerPath},`renderProfileB-${dr.id}-${ln}-${hs.current||"untracked"}`),f&&mt.length>0&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/80 backdrop-blur-md animate-in fade-in duration-300",role:"presentation",onClick:xa,onKeyDown:i=>{i.key==="Escape"&&xa()},onMouseMove:ao,onMouseUp:Ui,onMouseLeave:Ui,children:[e.jsxs("div",{className:"absolute top-0 left-0 right-0 z-50 px-4 py-4 flex items-center justify-between bg-gradient-to-b from-black/60 to-transparent",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"bg-white/10 backdrop-blur-xl border border-white/10 text-white px-4 py-2 rounded-full text-sm font-medium shadow-lg",children:[e.jsx("span",{className:"text-emerald-400 font-bold",children:Z+1}),e.jsx("span",{className:"text-white/50 mx-1",children:"/"}),e.jsx("span",{className:"text-white/70",children:mt.length})]}),z>1&&e.jsxs("div",{className:"bg-emerald-500/20 backdrop-blur-xl border border-emerald-500/30 text-emerald-400 px-3 py-2 rounded-full text-sm font-bold shadow-lg animate-in fade-in slide-in-from-left-2 duration-200",children:[z,"Ã"]})]}),e.jsx("div",{className:"hidden md:block absolute left-1/2 -translate-x-1/2",children:e.jsx("h3",{className:"text-white/80 text-sm font-medium tracking-wide truncate max-w-xs",children:a("Mockup Preview")})}),e.jsx("button",{type:"button",onClick:xa,className:"group relative w-11 h-11 rounded-full bg-white/10 backdrop-blur-xl border border-white/10 flex items-center justify-center transition-all duration-300 hover:bg-white/20 hover:border-white/20 hover:scale-110 shadow-lg",children:e.jsx(Po,{className:"h-5 w-5 text-white/80 group-hover:text-white transition-colors"})})]}),e.jsxs("div",{className:"flex h-full w-full pt-16 pb-24 md:pb-20",children:[mt.length>1&&e.jsx("div",{className:"hidden md:flex flex-col items-center gap-3 px-4 py-6 w-28 h-full overflow-y-auto scrollbar-thin scrollbar-thumb-white/20 scrollbar-track-transparent",role:"presentation",onClick:i=>i.stopPropagation(),onKeyDown:i=>i.stopPropagation(),children:mt.map((i,l)=>{const h=`${i.id}-${Kr}`,v=ot.get(h),g=v==null?void 0:v.mockupUrl;return g?e.jsxs("button",{type:"button",onClick:()=>fn(l),className:`group relative flex-shrink-0 w-18 h-18 rounded-xl overflow-hidden transition-all duration-300 ${l===Z?"ring-2 ring-emerald-500 ring-offset-2 ring-offset-slate-900 scale-105 shadow-lg shadow-emerald-500/20":"opacity-50 hover:opacity-100 hover:scale-105"}`,children:[e.jsx("img",{src:g,alt:`${a("View")} ${l+1}`,className:"w-full h-full object-cover"}),e.jsx("div",{className:`absolute inset-0 bg-gradient-to-t from-black/50 to-transparent opacity-0 group-hover:opacity-100 transition-opacity ${l===Z?"opacity-100":""}`}),l===Z&&e.jsx("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 w-6 h-1 bg-emerald-500 rounded-full"})]},i.id):null})}),e.jsxs("div",{className:"flex-1 flex items-center justify-center relative overflow-hidden px-4 md:px-8",children:[mt.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"absolute left-2 md:left-4 top-1/2 -translate-y-1/2 z-40 w-12 h-12 md:w-14 md:h-14 roun
170ded-full bg-white/10 backdrop-blur-xl border border-white/10 flex items-center justify-center transition-all duration-300 hover:bg-white/20 hover:scale-110 hover:border-white/20 group shadow-lg",onClick:i=>{i.stopPropagation(),fn(Z>0?Z-1:mt.length-1)},children:e.jsx(Jl,{className:"h-6 w-6 text-white/80 group-hover:text-white transition-colors"})}),e.jsx("button",{type:"button",className:"absolute right-2 md:right-4 top-1/2 -translate-y-1/2 z-40 w-12 h-12 md:w-14 md:h-14 rounded-full bg-white/10 backdrop-blur-xl border border-white/10 flex items-center justify-center transition-all duration-300 hover:bg-white/20 hover:scale-110 hover:border-white/20 group shadow-lg",onClick:i=>{i.stopPropagation(),fn(Z<mt.length-1?Z+1:0)},children:e.jsx(Io,{className:"h-6 w-6 text-white/80 group-hover:text-white transition-colors"})})]}),e.jsx("div",{className:`relative transition-all duration-300 ease-out ${sr()}`,style:{transform:`scale(${z}) translate(${ve.x/z}px, ${ve.y/z}px)`},role:"presentation",onClick:i=>i.stopPropagation(),onKeyDown:i=>i.stopPropagation(),onDoubleClick:so,onMouseDown:no,children:(()=>{const i=mt[Z],l=`${i.id}-${Kr}`,h=ot.get(l),v=h==null?void 0:h.mockupUrl;return v?e.jsx("img",{src:v,alt:i.name,className:"max-h-[75vh] max-w-[calc(100vw-100px)] md:max-w-[calc(100vw-220px)] object-contain rounded-2xl select-none shadow-2xl shadow-black/50",draggable:!1}):e.jsxs("div",{className:"flex flex-col items-center gap-3 text-white/40",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-white/5 flex items-center justify-center",children:e.jsx(Ir,{className:"w-8 h-8"})}),e.jsx("p",{className:"font-medium",children:a("Mockup not generated")})]})})()})]}),e.jsx("div",{className:"hidden md:flex flex-col items-center justify-center gap-2 px-4 w-20",role:"presentation",onClick:i=>i.stopPropagation(),onKeyDown:i=>i.stopPropagation(),children:e.jsxs("div",{className:"bg-white/10 backdrop-blur-xl border border-white/10 rounded-2xl p-2 flex flex-col gap-1 shadow-lg",children:[e.jsx("button",{type:"button",onClick:i=>{i.stopPropagation(),z<3&&fe(z+1)},disabled:z>=3,className:"w-10 h-10 rounded-xl flex items-center justify-center transition-all duration-200 hover:bg-white/10 disabled:opacity-30 disabled:cursor-not-allowed group",children:e.jsx(Su,{className:"w-5 h-5 text-white/70 group-hover:text-white"})}),e.jsxs("div",{className:"w-10 h-10 flex items-center justify-center text-white/50 text-xs font-bold",children:[z,"Ã"]}),e.jsx("button",{type:"button",onClick:i=>{i.stopPropagation(),z>1&&(fe(z-1),z-1===1&&qe({x:0,y:0}))},disabled:z<=1,className:"w-10 h-10 rounded-xl flex items-center justify-center transition-all duration-200 hover:bg-white/10 disabled:opacity-30 disabled:cursor-not-allowed group",children:e.jsx(Au,{className:"w-5 h-5 text-white/70 group-hover:text-white"})}),e.jsx("div",{className:"w-full h-px bg-white/10 my-1"}),e.jsx("button",{type:"button",onClick:i=>{i.stopPropagation(),fe(1),qe({x:0,y:0})},disabled:z===1,className:"w-10 h-10 rounded-xl flex items-center justify-center transition-all duration-200 hover:bg-white/10 disabled:opacity-30 disabled:cursor-not-allowed group",title:a("Reset zoom"),children:e.jsx(Tu,{className:"w-4 h-4 text-white/70 group-hover:text-white"})})]})})]}),e.jsxs("div",{className:"absolute bottom-0 left-0 right-0 z-50 px-4 py-4 bg-gradient-to-t from-black/60 to-transparent",children:[mt.length>1&&e.jsx("div",{className:"md:hidden flex justify-center gap-2 mb-3 overflow-x-auto pb-2",role:"presentation",onClick:i=>i.stopPropagation(),onKeyDown:i=>i.stopPropagation(),children:mt.map((i,l)=>{const h=`${i.id}-${Kr}`,v=ot.get(h),g=v==null?void 0:v.mockupUrl;return g?e.jsx("button",{type:"button",onClick:()=>fn(l),className:`flex-shrink-0 w-14 h-14 rounded-xl overflow-hidden transition-all duration-300 ${l===Z?"ring-2 ring-emerald-500 ring-offset-2 ring-offset-slate-900 scale-105":"opacity-50"}`,children:e.jsx("img",{src:g,alt:`${a("View")} ${l+1}`,className:"w-full h-full object-cover"})},i.id):null})}),e.jsxs("div",{className:"flex justify-center",children:[e.jsxs("div",{className:"hidden md:flex items-center gap-4 bg-white/5 backdrop-blur-xl border border-white/10 px-5 py-2.5 rounded-full text-sm shadow-lg",children:[e.jsxs("span",{className:"text-white/50 flex items-center gap-2",children:[e.jsx("kbd",{className:"px-2 py-0.5 bg-white/10 rounded text-xs font-mono",children:a("ESC")}),e.jsx("span",{children:a("close")})]}),e.jsx("span",{className:"w-px h-4 bg-white/20"}),e.jsxs("span",{className:"text-white/50 flex items-center gap-2",children:[e.jsx("kbd",{className:"px-2 py-0.5 bg-white/10 rounded text-xs font-mono",children:"â"}),e.jsx("kbd",{className:"px-2 py-0.5 bg-white/10 rounded text-xs font-mono",children:"â"}),e.jsx("span",{children:a("navigate")})]}),e.jsx("span",{className:"w-px h-4 bg-white/20"}),e.jsx("span",{className:"text-white/50",children:a("double-click to zoom")}),z>1&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"w-px h-4 bg-white/20"}),e.jsx("span",{className:"text-emerald-400 font-medium",children:a("drag to pan")})]})]}),e.jsx("div",{className:"md:hidden bg-white/5 backdrop-blur-xl border border-white/10 px-4 py-2 rounded-full text-xs text-white/50 shadow-lg",children:a("Swipe ⢠Pinch to zoom ⢠Tap outside to close")})]})]})]}),e.jsx(Sd,{mockupName:Qs,onClose:()=>ft(null)})]})},up=Ur` 171 fragment BrandingOptionPricingFields on BrandingOptionPricing { 172 optionPricingId 173 optionCategory 174 optionValue 175 isBaseOption 176 isAvailable 177 additionalPrice 178 } 179`,mp=Ur` 180 fragment BrandingColorAvailabilityFields on BrandingColorAvailability { 181 colorAvailabilityId 182 configId 183 colorName 184 colorHex 185 isAvailable 186 leadTimeDays 187 } 188`,oc=Ur` 189 fragment ProviderBrandingPricingFields on ProviderBrandingPricing { 190 configId 191 providerId 192 productId 193 brandingProductType 194 basePricePerUnit 195 maxQuantity 196 currency 197 notes 198 status 199 optionPricing { 200 ...BrandingOptionPricingFields 201 } 202 colors { 203 ...BrandingColorAvailabilityFields 204 } 205 } 206 ${up} 207 ${mp} 208`,lc=Ur` 209 query GetProviderBrandingOptions($providerId: ID!) { 210 getProviderBrandingPricing(providerId: $providerId, status: APPROVED) { 211 ...ProviderBrandingPricingFields 212 } 213 } 214 ${oc}
214 215`;Ur` 216 query GetBrandingPricingByType($providerId: ID!, $brandingProductType: String!) { 217 getBrandingPricingByType(providerId: $providerId, brandingProductType: $brandingProductType) { 218 ...ProviderBrandingPricingFields 219 } 220 } 221 ${oc} 222`;const si=[{key:"packaging-insert",label:"Packaging Insert",description:"Thank you cards and promotional inserts",iconName:"FileText"},{key:"branded-label",label:"Branded Label / Sticker",description:"Custom stickers and labels",iconName:"Tag"},{key:"hang-tag",label:"Hang Tag",description:"Product hang tags with string",iconName:"Bookmark"},{key:"tissue-paper",label:"Tissue Paper",description:"Custom branded wrapping paper",iconName:"Layers"},{key:"gift-box",label:"Gift Box",description:"Premium branded gift boxes",iconName:"Gift"},{key:"shopping-bag",label:"Shopping Bag",description:"Custom shopping bags",iconName:"ShoppingBag"}],pp={paperType:"Paper Type",paperWeight:"Paper Weight",finish:"Finish",corners:"Corners",material:"Material",adhesive:"Adhesive Type",string:"String/Fastener",printType:"Print Type",handle:"Handle Type",size:"Size"};function hp(t){return t.reduce((s,n)=>(s[n.optionCategory]||(s[n.optionCategory]=[]),s[n.optionCategory].push(n),s),{})}function cc(t,s,n){let a=t;for(const c of s){const d=n.find(u=>u.optionCategory===c.category&&u.optionValue===c.value);d&&!d.isBaseOption&&(a+=d.additionalPrice)}return a}const xp=t=>Object.entries(t.selectedOptions??{}).map(([s,n])=>({category:s,value:n.value})),qi=(t,s)=>{const n=s.filter(a=>a.brandingProductType===t.brandingProductType);return t.productId?n.find(a=>a.productId===t.productId):t.providerConfigId?n.find(a=>a.configId===t.providerConfigId):n.length===1?n[0]:void 0},fp=(t,s,n)=>t.productId===s.productId&&t.providerId===s.providerId&&t.providerConfigId===s.configId&&t.providerCost===s.basePricePerUnit&&t.basePricePerUnit===s.basePricePerUnit&&t.unitPrice===n&&t.currency===s.currency,ko=(t,s)=>{const n=cc(s.basePricePerUnit,xp(t),s.optionPricing);return fp(t,s,n)?t:{...t,productId:s.productId,providerId:s.providerId,providerConfigId:s.configId,providerCost:s.basePricePerUnit,basePricePerUnit:s.basePricePerUnit,unitPrice:n,currency:s.currency}},Nl={"packaging-insert":rc,"branded-label":tc,"hang-tag":Lu,"tissue-paper":Uu,"gift-box":Eu,"shopping-bag":bc},gp=()=>e.jsx(Er,{className:"p-4 border border-gray-200 rounded-xl",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(Je,{className:"w-12 h-12 rounded-lg"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Je,{className:"h-5 w-32"}),e.jsx(Je,{className:"h-4 w-48"})]}),e.jsx(Je,{className:"h-6 w-16"}),e.jsx(Je,{className:"h-6 w-10"})]})}),bp=()=>{var re,X,Q;const t=Js(),{locale:s}=Dl(),{user:n}=Ol(),{selectedProvider:a,brandingItems:c,setBrandingItems:d,updateBrandingItem:u,providerName:y,isViewOnly:p}=mi(),[x,b]=r.useState(new Set),[C,L]=r.useState(null),[k,K]=r.useState(!1),{data:P,loading:B,error:R}=Ht(lc,{variables:{providerId:a==null?void 0:a.providerId},skip:!(a!=null&&a.providerId),fetchPolicy:"network-only"}),{data:A,loading:D,refetch:_}=Ht(Fu,{variables:{userId:n==null?void 0:n.id},skip:!(n!=null&&n.id),client:Qr,fetchPolicy:"cache-and-network"}),O=(P==null?void 0:P.getProviderBrandingPricing)||[],I=(A==null?void 0:A.getBrandingDesigns)||[];r.useEffect(()=>{if(!O.length||!d)return;if(!c||c.length===0){const M=O.map(E=>{const Me={};return E.optionPricing.forEach(Y=>{Y.isBaseOption&&Y.isAvailable&&(Me[Y.optionCategory]={value:Y.optionValue,additionalPrice:0})}),{brandingProductType:E.brandingProductType,productId:E.productId,enabled:!1,designId:null,designName:void 0,designThumbnail:void 0,unitPrice:E.basePricePerUnit,quantity:1,selectedOptions:Me,basePricePerUnit:E.basePricePerUnit,currency:E.currency,providerId:E.providerId,providerConfigId:E.configId,providerCost:E.basePricePerUnit}});d(M);return}const S=c.map(M=>{const E=qi(M,O);return E?ko(M,E):M});S.some((M,E)=>M!==c[E])&&d(S)},[O,d,c]),r.useEffect(()=>{!I.length||!(c!=null&&c.length)||!u||c.forEach(S=>{var w,M;if(S.designId&&!S.designThumbnail){const E=I.find(Me=>Me.id===S.designId);(M=(w=E==null?void 0:E.printAreaThumbnails)==null?void 0:w[0])!=null&&M.thumbnailUrl&&u(S.brandingProductType,{designThumbnail:E.printAreaThumbnails[
2220].thumbnailUrl})}})},[I,c,u]);const ue=r.useCallback(S=>I.filter(w=>w.brandingProductType===S),[I]),me=r.useCallback(S=>{if(!u)return;const w=c==null?void 0:c.find(M=>M.brandingProductType===S);w&&u(S,{enabled:!w.enabled,...w.enabled?{designId:null,designName:void 0,designThumbnail:void 0}:{}})},[c,u]),Se=r.useCallback((S,w)=>{var M,E;u&&u(S,{designId:(w==null?void 0:w.id)||null,designName:(w==null?void 0:w.name)||void 0,designThumbnail:((E=(M=w==null?void 0:w.printAreaThumbnails)==null?void 0:M[0])==null?void 0:E.thumbnailUrl)||void 0})},[u]),be=r.useCallback((S,w,M,E)=>{if(!u)return;const Me=c==null?void 0:c.find(Ae=>Ae.brandingProductType===S);if(!Me)return;const Y={...Me.selectedOptions,[w]:{value:M,additionalPrice:E}},Ee=qi(Me,O);if(!Ee)return;const Be=cc(Ee.basePricePerUnit,Object.entries(Y).map(([Ae,Ze])=>({category:Ae,value:Ze.value})),Ee.optionPricing);u(S,{selectedOptions:Y,unitPrice:Be})},[c,u,O]),G=r.useCallback(S=>{b(w=>{const M=new Set(w);return M.has(S)?M.delete(S):M.add(S),M})},[]),ye=r.useMemo(()=>c?c.filter(S=>S.enabled).reduce((S,w)=>S+w.unitPrice*w.quantity,0):0,[c]),we=((re=O[0])==null?void 0:re.currency)??"";return B?e.jsx("div",{className:"h-full flex flex-col bg-gray-50/50 p-6",children:e.jsxs("div",{className:"max-w-4xl mx-auto w-full space-y-4",children:[e.jsx(Je,{className:"h-8 w-64 mb-2"}),e.jsx(Je,{className:"h-5 w-96 mb-6"}),[1,2,3,4].map(S=>e.jsx(gp,{},`skeleton-${S}`))]})}):R?e.jsx("div",{className:"h-full flex flex-col items-center justify-center bg-gray-50/50 p-8",children:e.jsxs("div",{className:"max-w-md text-center",children:[e.jsx("div",{className:"mx-auto w-16 h-16 rounded-full bg-red-100 flex items-center justify-center mb-4",children:e.jsx(yn,{className:"w-8 h-8 text-red-600"})}),e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:t("Unable to Load Branding Options")}),e.jsx("p",{className:"text-gray-600",children:t("There was an error loading branding options. Please try again.")})]})}):a!=null&&a.providerId?O.length===0?e.jsx("div",{className:"h-full flex flex-col items-center justify-center bg-gray-50/50 p-8",children:e.jsxs("div",{className:"max-w-md text-center",children:[e.jsx("div",{className:"mx-auto w-16 h-16 rounded-full bg-gray-100 flex items-center justify-center mb-4",children:e.jsx(wa,{className:"w-8 h-8 text-gray-400"})}),e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:t("No Branding Options Available")}),e.jsxs("p",{className:"text-gray-600 mb-4",children:[y||t("This provider")," ",t("doesn't offer custom branding and packaging options yet.")]}),e.jsx("p",{className:"text-sm text-gray-500",children:t("You can continue to the next step. Standard packaging will be used for your orders.")})]})}):e.jsxs("div",{className:"h-full flex flex-col bg-gray-50/50 overflow-auto",children:[e.jsxs("div",{className:"max-w-4xl mx-auto w-full p-6 space-y-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("h2",{className:"text-2xl font-semibold text-gray-900 flex items-center gap-2",children:[e.jsx(Ca,{className:"w-6 h-6 text-[#15B67F]"}),t("Add Branding to Your Orders")]}),e.jsxs("p",{className:"text-gray-600",children:[t("Elevate your customer experience with custom branding from")," ",y||t("your provider"),"."," ",t("Prices shown are per unit.")]})]}),p&&e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-slate-100 border border-slate-200 rounded-xl",children:[e.jsx(Zn,{className:"h-5 w-5 text-slate-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-slate-800",children:t("View Only Mode")}),e.jsx("p",{className:"text-sm text-slate-600 mt-0.5",children:t("You are viewing this design in read-only mode. Branding options cannot be modified.")})]})]}),e.jsx("div",{className:"space-y-3",children:O.map(S=>{var Ye,kt;const w=si.find(he=>he.key===S.brandingProductType),M=c==null?void 0:c.find(he=>he.brandingProductType===S.brandingProductType),E=(M==null?void 0:M.enabled)||!1,Me=x.has(S.brandingProductType),Y=M!=null&&M.designId?I.find(he=>he.id===M.designId):null,Ee=ue(S.brandingProductType),Be=Nl[S.brandingProductType]||wa,Ae=hp(S.optionPricing),Ze=M!=null&&M.selectedOptions?Object.values(M.selectedOptions).map(he=>he.value).join(", "):t("Base options");return e.jsx(Er,{className:`border rounded-xl transition-all duration-200 ${E?"border-[#15B67F] bg-[#15B67F]/5 shadow-sm":"border-gray-200 bg-white hover:border-gray-300"}`,children:e.jsxs("div",{className:"p-4",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`w-12 h-12 rounded-lg flex items-center justify-center shrink-0 ${E?"bg-[#15B67F]/20":"bg-gray-100"}
222`,children:e.jsx(Be,{className:`w-6 h-6 ${E?"text-[#15B67F]":"text-gray-500"}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-2 mb-1",children:e.jsx("h3",{className:"font-medium text-gray-900",children:(w==null?void 0:w.label)||S.brandingProductType})}),e.jsx("p",{className:"text-sm text-gray-500 mb-2",children:(w==null?void 0:w.description)||t("Custom branding item")}),E&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 mt-3",children:[e.jsxs(ol,{value:(M==null?void 0:M.designId)||"",onValueChange:he=>{const ne=I.find(ee=>ee.id===he);Se(S.brandingProductType,ne||null)},disabled:p,children:[e.jsx(ll,{className:"w-[320px] h-14 text-sm border-gray-300 hover:border-[#15B67F]/50 focus:ring-[#15B67F]/20 bg-white",children:M!=null&&M.designId&&Y?e.jsxs("div",{className:"flex items-center gap-3",children:[(kt=(Ye=Y.printAreaThumbnails)==null?void 0:Ye[0])!=null&&kt.thumbnailUrl?e.jsx("img",{src:Y.printAreaThumbnails[0].thumbnailUrl,alt:Y.name,className:"w-10 h-10 rounded-lg object-cover border border-gray-200 shadow-sm bg-white"}):e.jsx("div",{className:"w-10 h-10 rounded-lg bg-gradient-to-br from-gray-100 to-gray-200 flex items-center justify-center",children:e.jsx(Ir,{className:"w-5 h-5 text-gray-400"})}),e.jsx("span",{className:"truncate font-medium text-gray-900",children:Y.name})]}):e.jsxs("div",{className:"flex items-center gap-2 text-gray-500",children:[e.jsx(Ir,{className:"w-5 h-5"}),e.jsx("span",{children:t("Choose a design...")})]})}),e.jsx(cl,{className:"w-[380px] p-3 max-h-[400px]",children:Ee.length===0?e.jsxs("div",{className:"py-10 px-4 text-center",children:[e.jsx("div",{className:"w-20 h-20 mx-auto mb-4 rounded-full bg-gradient-to-br from-gray-100 to-gray-200 flex items-center justify-center",children:e.jsx(Ir,{className:"w-9 h-9 text-gray-400"})}),e.jsx("p",{className:"text-base font-medium text-gray-600 mb-1",children:t("No designs yet")}),e.jsx("p",{className:"text-sm text-gray-400",children:t("Create your first branding design")})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide px-2 mb-2",children:s==="ar"?e.jsxs(e.Fragment,{children:[t("Designs")," ",(w==null?void 0:w.label)||t("Branding")," ",t("Your")]}):e.jsxs(e.Fragment,{children:[t("Your")," ",(w==null?void 0:w.label)||t("Branding")," ",t("Designs")]})}),Ee.map(he=>{var nt,Ue,Le,Te;const ne=(Ue=(nt=he.printAreaThumbnails)==null?void 0:nt[0])==null?void 0:Ue.thumbnailUrl,ee=(M==null?void 0:M.designId)===he.id;return e.jsx(dl,{value:he.id,className:`rounded-xl p-3 cursor-pointer transition-all ${ee?"bg-[#15B67F]/10 border-2 border-[#15B67F]":"hover:bg-gray-50 border-2 border-transparent"}`,children:e.jsxs("div",{className:"flex items-center gap-4",children:[ne?e.jsxs("div",{className:"relative shrink-0",children:[e.jsx("img",{src:ne,alt:he.name,className:"w-20 h-20 rounded-xl object-cover border border-gray-200 shadow-md bg-white"}),ee&&e.jsx("div",{className:"absolute -top-2 -right-2 w-6 h-6 bg-[#15B67F] rounded-full flex items-center justify-center shadow-lg ring-2 ring-white",children:e.jsx(Xn,{className:"w-4 h-4 text-white"})})]}):e.jsx("div",{className:"w-20 h-20 rounded-xl bg-gradient-to-br from-gray-100 to-gray-200 flex items-center justify-center border border-gray-200 shrink-0",children:e.jsx(Ir,{className:"w-8 h-8 text-gray-400"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`font-semibold truncate ${ee?"text-[#15B67F]":"text-gray-900"}`,children:he.name}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:((Le=si.find($e=>$e.key===he.brandingProductType))==null?void 0:Le.dimensions)||t("Custom size")}),((Te=he.printAreaThumbnails)==null?void 0:Te.length)>1&&e.jsxs("p",{className:"text-xs text-gray-400 mt-1",children:[he.printAreaThumbnails.length," ",t("print areas")]})]})]})},he.id)})]})})]}),Y&&e.jsxs(pe,{variant:"outline",size:"sm",onClick:()=>{L(Y),K(!0)},className:"h-9 px-3 text-sm",children:[e.jsx(Ir,{className:"w-4 h-4 mr-1"}),t("Preview")]}),e.jsxs(pe,{variant:"outline",size:"sm",onClick:()=>{globalThis.open("/catalog/branding-packaging/branding-products","_blank","noopener,noreferrer"),ie.info(t("Create your branding design in the new tab, then come back to select it here."))}
222,className:"h-9 px-3 text-sm text-[#15B67F] border-[#15B67F] hover:bg-[#15B67F]/10",children:[e.jsx(ql,{className:"w-4 h-4 mr-1"}),t("Create New")]}),Object.keys(Ae).length>0&&e.jsx(pe,{variant:"ghost",size:"sm",onClick:()=>G(S.brandingProductType),className:"h-9 px-3 text-sm ml-auto text-gray-500 hover:text-gray-700",children:Me?e.jsxs(e.Fragment,{children:[e.jsx(Du,{className:"w-4 h-4 mr-1"}),t("Details")]}):e.jsxs(e.Fragment,{children:[e.jsx(Bl,{className:"w-4 h-4 mr-1"}),t("Details")]})})]}),!Me&&e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsxs("p",{className:"text-xs text-gray-500",children:[t("Current:")," ",Ze]}),e.jsxs("p",{className:"text-sm font-medium text-gray-700",children:[((M==null?void 0:M.unitPrice)||S.basePricePerUnit).toFixed(2)," ",we,"/",t("unit")]})]})]})]}),e.jsxs("div",{className:"text-right shrink-0",children:[e.jsxs("div",{className:"font-semibold text-gray-900",children:["+",we," ",((M==null?void 0:M.unitPrice)||S.basePricePerUnit).toFixed(2)]}),e.jsx("div",{className:"text-xs text-gray-500",children:t("per unit")})]}),e.jsx("div",{className:"shrink-0",children:e.jsx(yc,{checked:E,onCheckedChange:()=>me(S.brandingProductType),className:"data-[state=checked]:bg-[#15B67F]",disabled:p})})]}),E&&Me&&Object.keys(Ae).length>0&&e.jsxs("div",{className:"mt-4 pt-4 border-t border-gray-100 space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600",children:t("Customize your branding options:")}),e.jsx("div",{className:"grid grid-cols-2 gap-4",children:Object.entries(Ae).map(([he,ne])=>{var Ue;const ee=(Ue=M==null?void 0:M.selectedOptions)==null?void 0:Ue[he],nt=ne.filter(Le=>Le.isAvailable);return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:pp[he]||he}),e.jsxs(ol,{value:(ee==null?void 0:ee.value)||"",onValueChange:Le=>{const Te=ne.find($e=>$e.optionValue===Le);Te&&be(S.brandingProductType,he,Le,Te.isBaseOption?0:Te.additionalPrice)},disabled:p,children:[e.jsx(ll,{className:"h-10",children:e.jsx(Ru,{placeholder:t("Select...")})}),e.jsx(cl,{children:nt.map(Le=>e.jsx(dl,{value:Le.optionValue,children:e.jsxs("div",{className:"flex items-center justify-between w-full gap-4",children:[e.jsx("span",{children:Le.optionValue}),e.jsx("span",{className:`text-sm ${Le.isBaseOption?"text-gray-400":"text-[#15B67F]"}`,children:Le.isBaseOption?t("Base"):Le.additionalPrice>=0?`+${we} ${Le.additionalPrice.toFixed(2)}`:`${we} ${Le.additionalPrice.toFixed(2)}`})]})},Le.optionValue))})]})]},he)})})]})]})},S.configId)})}),e.jsxs(Er,{className:"p-4 border border-gray-200 rounded-xl bg-white",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wa,{className:"w-5 h-5 text-gray-500"}),e.jsx("span",{className:"font-medium text-gray-700",children:t("Branding Add-on Total")}),e.jsx(jn,{children:e.jsxs(wn,{children:[e.jsx(kn,{asChild:!0,children:e.jsx(Vi,{className:"w-4 h-4 text-gray-400"})}),e.jsx(Cn,{className:"max-w-xs",children:e.jsx("p",{children:t("This amount will be added to each order. Your profit margins on the Prices step already account for base product costs.")})})]})})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:"text-xl font-bold text-[#15B67F]",children:["+",we," ",ye.toFixed(2)]}),e.jsx("div",{className:"text-xs text-gray-500",children:t("per unit")})]})]}),(c==null?void 0:c.some(S=>S.enabled))&&e.jsx("div",{className:"mt-3 pt-3 border-t border-gray-100",children:e.jsx("div",{className:"flex flex-wrap gap-2",children:c.filter(S=>S.enabled).map(S=>{const w=si.find(E=>E.key===S.brandingProductType);if(!w)return null;const M=Nl[S.brandingProductType]||wa;return e.jsxs(Xs,{variant:"secondary",className:"flex items-center gap-1 bg-[#15B67F]/10 text-[#15B67F] border-0",children:[e.jsx(M,{className:"w-3 h-3"}),w.label,!S.designId&&e.jsx("span",{className:"text-amber-600 ml-1",children:t("(no design)")})]},S.brandingProductType)})})})]}),e.jsx("div",{className:"p-4 bg-blue-50 rounded-xl border border-blue-100",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-blue-100 flex items-center justify-center shrink-0",children:e.jsx(Ca,{className:"w-4 h-4 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-blue-900 mb-1",children:t("Pro Tip")}),e.jsxs("p",{className:"text-sm text-blue-700",children:[t("Packaging inserts with discount codes can increase repeat purchases by up to 25%.")," ",t("Browse")," ",e.jsx("a",{href:"/catalog/branding-packaging/branding-products",target:"_blank",className:"underline hover:text-blue-900",children:t("Branding Products")})," ",t("to create custom designs, then select them here.")]})]})]})})]}),e.jsx(Xi,{open:k,onOpenChange:K,children:e.jsx(Zi,{className:"max-w-3xl p-0 overflow-hidden rounded-2xl border-0 shadow-2xl",children:C&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative bg-gradient-to-r from-[#15B67F] to-[#0ea66d] px-6 py-5",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmYiIGZpbGwtb3BhY2l0eT0iMC4wNSI+PHBhdGggZD0iTTM2IDM0djZoNnYtNmgtNnptMCAwdi02aC02djZoNnptLTYgMGgtNnY2aDZ2LTZ6bTAgMHYtNmgtNnY2aDZ6Ii8+PC9nPjwvZz48L3N2Zz4=')] opacity-50"}),e.jsx("div",{className:"relative flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-white/20 backdrop-blur-sm flex items-center justify-center shadow-lg",children:e.jsx(Ir,{className:"w-6 h-6 text-white"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-white",children:C.name}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Xs,{className:"bg-white/20 text-white border-0 hover:bg-white/30",children:((X=si.find(S=>S.key===C.brandingProductType))==null?void 0:X.label)||C.brandingProductType}),e.jsx("span",{className:"text-white/80 text-sm",children:(Q=si.find(S=>S.key===C.brandingProductType))==null?void 0:Q.dimensions})]})]})]})})]}),e.jsxs("div",{className:"p-6 bg-gradient-to-b from-gray-50 to-white",children:[C.printAreaThumbnails&&C.printAreaThumbnails.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(Ca,{className:"w-4 h-4 text-[#15B6
2227F]"}),e.jsx("span",{className:"text-sm font-medium text-gray-700",children:t("Design Preview")}),e.jsxs("span",{className:"text-xs text-gray-500",children:["(",C.printAreaThumbnails.length," ",t(C.printAreaThumbnails.length===1?"print area":"print areas"),")"]})]}),e.jsx("div",{className:`grid gap-6 ${C.printAreaThumbnails.length===1?"grid-cols-1 max-w-md mx-auto":"grid-cols-1 md:grid-cols-2"}`,children:C.printAreaThumbnails.map((S,w)=>e.jsxs("div",{className:"group relative bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden hover:shadow-lg transition-all duration-300",children:[e.jsx("div",{className:"absolute top-3 left-3 z-10",children:e.jsx(Xs,{className:`capitalize font-semibold shadow-md px-3 py-1 ${S.printArea==="front"?"bg-[#15B67F] text-white":"bg-gray-800 text-white"}`,children:S.printArea.replace("-"," ")})}),e.jsxs("div",{className:"relative aspect-square bg-gradient-to-br from-gray-50 to-gray-100 flex items-center justify-center p-4",children:[e.jsx("div",{className:"absolute inset-0 opacity-[0.03] bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAiIGhlaWdodD0iMjAiIHZpZXdCb3g9IjAgMCAyMCAyMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSIjMDAwIj48Y2lyY2xlIGN4PSIxMCIgY3k9IjEwIiByPSIxIi8+PC9nPjwvc3ZnPg==')]"}),e.jsx("img",{src:S.thumbnailUrl,alt:`${S.printArea} ${t("preview")}`,className:"relative max-w-full max-h-full object-contain rounded-lg shadow-md group-hover:scale-[1.02] transition-transform duration-300"})]}),e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/5 transition-colors duration-300 pointer-events-none"})]},w))})]}):e.jsxs("div",{className:"py-12 flex flex-col items-center justify-center",children:[e.jsx("div",{className:"w-20 h-20 rounded-full bg-gradient-to-br from-gray-100 to-gray-200 flex items-center justify-center mb-4",children:e.jsx(Ir,{className:"w-10 h-10 text-gray-400"})}),e.jsx("p",{className:"text-gray-600 font-medium mb-1",children:t("No preview available")}),e.jsx("p",{className:"text-sm text-gray-400",children:t("Design preview will appear after saving")})]}),e.jsxs("div",{className:"mt-6 pt-4 border-t border-gray-200 flex items-center justify-between bg-gray-50/50 -mx-6 -mb-6 px-6 py-4 rounded-b-2xl",children:[e.jsx("p",{className:"text-sm text-gray-600",children:t("This design will be added to your orders")}),e.jsx(pe,{onClick:()=>K(!1),className:"px-6 py-2 bg-[#15B67F] hover:bg-[#129b6b] text-white font-medium shadow-md hover:shadow-lg transition-all",children:t("Close Preview")})]})]})]})})})]}):e.jsx("div",{className:"h-full flex flex-col items-center justify-center bg-gray-50/50 p-8",children:e.jsxs("div",{className:"max-w-md text-center",children:[e.jsx("div",{className:"mx-auto w-16 h-16 rounded-full bg-amber-100 flex items-center justify-center mb-4",children:e.jsx(wa,{className:"w-8 h-8 text-amber-600"})}),e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:t("Provider Not Selected")}),e.jsx("p",{className:"text-gray-600",children:t("Please select a provider on the product page to see available branding options.")})]})})},ii=t=>String(t).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),yp=t=>{var c,d;const s=(d=(c=t.sizeTable)==null?void 0:c.metric)==null?void 0:d.data;if(!t.attachSizeTable||!s)return"";const n=Object.keys(Object.values(s)[0]??{});if(n.length===0)return"";let a='<div style="margin-top: 24px;">';return a+='<h3 style="font-size: 18px; font-weight: 600; margin-bottom: 16px;">Size Guide</h3>',t.sizeGuideImageUrls.length>0&&(a+='<div style="display: flex; gap: 12px; margin-bottom: 16px; flex-wrap: wrap;">',t.sizeGuideImageUrls.forEach(u=>{a+=`<img src="${ii(u)}" alt="Size Guide" style="max-width: 200px; height: auto; border-radius: 8px; border: 1px solid #e5e7eb;" />`}),a+="</div>"),a+='<table style="width: 100%; border-collapse: collapse; margin-bottom: 16px;">',a+='<thead><tr style="background-color: #f9fafb;">',a+='<th style="padding: 12px; text-align: left; border: 1px solid #e5e7eb; font-weight: 600;"></th>
222',n.forEach(u=>{a+=`<th style="padding: 12px; text-align: center; border: 1px solid #e5e7eb; font-weight: 600;">${ii(u)}</th>`}),a+="</tr></thead><tbody>",Object.entries(s).forEach(([u,y])=>{a+="<tr>",a+=`<td style="padding: 12px; border: 1px solid #e5e7eb; font-weight: 500;">${ii(u)}</td>`,n.forEach(p=>{const x=y[p]||"-";a+=`<td style="padding: 12px; text-align: center; border: 1px solid #e5e7eb;">${ii(x)}</td>`}),a+="</tr>"}),`${a}</tbody></table></div>`},vp=t=>{if(!t.attachCareInstructions||!t.careInstructions)return"";let s='<div style="margin-top: 24px;">';return s+='<h3 style="font-size: 18px; font-weight: 600; margin-bottom: 16px;">Care Instructions</h3>',s+='<div style="display: flex; flex-direction: column; gap: 12px;">',[["General",t.careInstructions.general],["Wash",t.careInstructions.wash],["Dry",t.careInstructions.dry],["Iron",t.careInstructions.iron],["Bleach",t.careInstructions.bleach]].forEach(([a,c])=>{c&&(s+=`<div><strong>${a}:</strong> ${ii(c)}</div>`)}),`${s}</div></div>`},Uo=t=>[t.productDetails.description,yp(t),vp(t)].filter(Boolean).join(` 223`),Np=(t,s)=>{if(t==null||String(t).trim()==="")return"-";if(s==="cm")return t;const n=Number(t);if(Number.isFinite(n))return(n/2.54).toFixed(1);const a=String(t).split("-");return a.length===2&&a.every(c=>c.trim()&&Number.isFinite(Number(c)))?a.map(c=>(Number(c)/2.54).toFixed(1)).join("-"):t};function jp({sizeTable:t,sizes:s,notes:n,images:a,copy:c}){var x;const[d,u]=r.useState("cm"),y=jo.sanitize(n,{RETURN_DOM_FRAGMENT:!0}),p=!!((x=y.textContent)!=null&&x.trim()||y.querySelector("img[src]"));return e.jsxs("div",{className:"flex flex-col md:flex-row gap-4 md:gap-5",children:[e.jsxs("div",{className:"order-2 md:order-1 min-w-0 flex-1 overflow-hidden rounded-xl border-2 border-gray-200 bg-white",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b-2 border-gray-200 bg-slate-50 px-4 py-3",children:[e.jsx("p",{className:"text-base font-semibold text-foreground",children:c("Size Measurements")}),e.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-slate-100 p-1",children:["cm","inches"].map(b=>e.jsx("button",{type:"button","aria-pressed":d===b,onClick:()=>u(b),className:`rounded-md px-3 py-1.5 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary ${d===b?"bg-white text-emerald-700 shadow-sm":"text-slate-600 hover:text-slate-700"}`,children:c(b)},b))})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-200 bg-slate-50",children:[e.jsxs("th",{scope:"col",className:"whitespace-nowrap px-4 py-3 text-start font-semibold text-foreground",children:[c("Measurement ("),c(d),")"]}),s.map(b=>e.jsx("th",{scope:"col",className:"px-4 py-3 text-center font-semibold text-foreground",children:b},b))]})}),e.jsx("tbody",{children:Object.entries(t.metric.data).map(([b,C])=>e.jsxs("tr",{className:"border-b border-gray-100 last:border-0 hover:bg-slate-50/50",children:[e.jsx("th",{scope:"row",className:"whitespace-nowrap px-4 py-3 text-start font-medium text-foreground",children:c(b.endsWith(" (cm)")?b.slice(0,-5):b)}),s.map(L=>e.jsx("td",{className:"px-4 py-3 text-center text-foreground",children:Np(C[L],d)},L))]},b))})]})})]}),(a.length>0||p)&&e.jsxs("div",{className:"order-1 flex shrink-0 flex-col gap-4 md:order-2 md:w-[240px] xl:w-[280px]",children:[a.map(b=>e.jsx("button",{type:"button","aria-label":`${c("View")} ${b.fileName}`,onClick:()=>vc(b.storageUrl),className:"flex min-h-40 flex-1 items-center justify-center overflow-hidden rounded-lg border border-slate-200 bg-white p-2 transition-shadow hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx("img",{src:b.storageUrl,alt:b.fileName,className:"max-h-80 max-w-full object-contain"})},b.fileId)),p&&e.jsxs("div",{className:"rounded-lg border border-slate-200 bg-slate-50 p-4",children:[e.jsx("h4",{className:"mb-3 text-sm font-bold text-slate-900",children:c("Size Guide Information")}),e.jsx("div",{className:"prose prose-sm max-w-none text-sm leading-relaxed text-slate-600",dangerouslySetInnerHTML:{__html:jo.sanitize(n)}})]})]})]})}const wp=(t,s,n,a,c)=>t===n&&s===a&&c!==t,kp=(t,s,n)=>s||t!=null&&n===t,Cp=(t,s)=>{const[n,a]=r.useState([]),[c,d]=r.useState(""),u=r.useRef(null),y=r.useRef(null);return r.useEffect(()=>{y.current!==t&&(y.current=t,u.current=null,a([]),d(""))},[t]),r.useEffect(()=>{s===void 0||u.current===t||(u.current=t,a([...s]))},[t,s]),{tags:n,setTags:a,tagInput:c,setTagInput:d,initializedDraftRef:u}},Mp=Ur` 224 query GetSavedMockups($designId: ID!) { 225 getSavedMockups(designId: $designId) { 226 id 227 mockupTemplateId 228 mockupKey 229 source 230 customMockupId 231 templateName 232 colorName 233 mockupUrl 234 generatedAt 235 } 236 } 237`,Pp=Ur` 238 query GetPrimaryMockupRecomposeMetadata($productId: ID!) { 239 getAvailableMockupsByProductId(productId: $productId) { 240 id 241 mockupKey 242 printAreaId 243 canUse 244 publicRenderProfile 245 mockupCode 246 extractedShadowUrl 247 extractedHighlightUrl 248 extractedForegroundUrl 249 extractedMaskUrl
250 extractedBackgroundUrl 251 designPlacementX 252 designPlacementY 253 designPlacementWidth 254 designPlacementHeight 255 designPlacementRotation 256 psdWidth 257 psdHeight 258 } 259 } 260`,Ip=Ur` 261 query GetSizeGuideImages($productId: ID!) { 262 getSizeGuideImages(productId: $productId) { 263 fileId 264 fileName 265 storageUrl 266 fileSize 267 uploadedAt 268 } 269 } 270`,Sp=Ur` 271 query GetProductDetailsExtended($productSlug: String!) { 272 getProductBySlug(slug: $productSlug) { 273 productId 274 sku 275 productSlug 276 productName 277 productDescription 278 shortDescription 279 basePrice 280 status 281 isCustomizable 282 sizeGuideNotes 283 fileSpecifications 284 productDetails 285 mockupTemplateId 286 shippingCost 287 deliveryEstimate 288 shippingFrom 289 shippingCurrency 290 averageRating 291 reviewCount 292 images { 293 imageId 294 thumbnailUrl 295 mediumUrl 296 largeUrl 297 colorName 298 position 299 } 300 variants { 301 variantId 302 size 303 colorName 304 colorHex 305 priceOverride 306 isActive 307 } 308 } 309 } 310`,dc=t=>t.mockupKey?t.mockupKey:t.customMockupId?`custom:${t.customMockupId}`:t.mockupTemplateId?`template:${t.mockupTemplateId}`:null,Ap=(t,s,n)=>{if(s&&n){const a=t.find(c=>dc(c)===s&&c.colorName===n);if(a!=null&&a.mockupUrl)return a.mockupUrl}return null},Tp=(t,s,n)=>{if(s){const a=Vl(s);return a!=null?t.find(c=>c.id===a)??null:t.find(c=>c.mockupKey===s)??null}return n!=null?t.find(a=>a.id===n)??null:null},Rp=(t,s)=>({mockupId:t.id,mockupCode:t.mockupCode||t.id.toString(),printAreaId:t.printAreaId,extractedShadowUrl:t.extractedShadowUrl||null,extractedHighlightUrl:t.extractedHighlightUrl||null,extractedForegroundUrl:t.extractedForegroundUrl||null,extractedMaskUrl:t.extractedMaskUrl||null,extractedBackgroundUrl:t.extractedBackgroundUrl||null,designPlacementX:t.designPlacementX??null,designPlacementY:t.designPlacementY??null,designPlacementWidth:t.designPlacementWidth??null,designPlacementHeight:t.designPlacementHeight??null,designPlacementRotation:t.designPlacementRotation??null,psdWidth:t.psdWidth||1200,psdHeight:t.psdHeight||1200,templateId:s||""}),jl=t=>{const s={notes:"",referenceTable:{chest:{},length:{},sleeve:{}},renderConfig:null};if(!t)return s;try{const n=JSON.parse(t);if(n&&typeof n=="object")return{notes:n.notes||"",referenceTable:n.referenceTable||s.referenceTable,renderConfig:n.renderConfig||null}}catch{return{...s,notes:t}}return s},Fp=(t,s,n)=>{if(s===n)return t;const a=String(t).trim();if(!/^-?\d+(\.\d+)?$/.test(a))return t;const c=Number.parseFloat(a);return(s==="cm"?c/2.54:c*2.54).toFixed(1)},Ep=(t,s)=>`${t.replace(/^[A-Z]\)\s*/,"")} (cm)`,go=(t,s,n)=>{var C;if((C=n==null?void 0:n.measurements)!=null&&C.length){const L={};for(const k of n.measurements){const K=s==null?void 0:s[k.key];if(!K||Object.keys(K).length===0)continue;const P=Ep(k.label);L[P]={};for(const B of t){const R=K[B];L[P][B]=R?Fp(R,k.unit,"cm"):"-"}}if(Object.keys(L).length>0)return{metric:{enabled:!0,data:L},imperial:{enabled:!1,data:{}}}}const a=(s==null?void 0:s.chest)&&Object.keys(s.chest).length>0,c=(s==null?void 0:s.length)&&Object.keys(s.length).length>0,d=(s==null?void 0:s.sleeve)&&Object.keys(s.sleeve).length>0,u=a||c||d,y={};return a&&(y["Chest (cm)"]=s.chest),c&&(y["Length (cm)"]=s.length),d&&(y["Sleeve (cm)"]=s.sleeve),{metric:{enabled:!0,data:(L=>{const k={};for(const[K,P]of Object.entries(L))if(P){k[K]={};for(const B of t)k[K][B]=P[B]??"-"}return k})(u?y:{"Chest (cm)":{XS:"81-86",S:"91-96",M:"96-101",L:"101-107",XL:"107-112","2XL":"112-117","3XL":"117-122","4XL":"122-127","5XL":"127-132"},"Length (cm)":{XS:66,S:69,M:71,L:74,XL:76,"2XL":79,"3XL":81,"4XL":83,"5XL":85},"Sleeve (cm)":{XS:18,S:20,M:20,L:21.5,XL:23,"2XL":23,"3XL":24,"4XL":24,"5XL":25}})},imperial:{enabled:!1,data:{}}}},wl={general:"A durable, comfortable, and versatile t-shirt that excels in printability and wearability, making it a top choice for custom designs.",wash:"The t-shirt should be washed with similar colors and can sustain regular washing without losing color or shape.",dry:"Tumble dry low or hang dry to maintain the integrity of the print and fabric.",iron:"Iron on low heat. Do not iron directly on the print.",bleach:"Do not bleach."},Up=t=>{if(!t)return null;try{const s=JSON.parse(t);if(!Object.prototype.hasOwnProperty.call(s,"careInstructions"))return null;const n=s==null?void 0:s.careInstructions;if(!n||typeof n!="object"||Array.isArray(n))return null;const a=["general","wash","dry","iron","bleach"],c={general:"",wash:"",dry:""};for(const d of a){const u=n[d],y=typeof u=="string"?u.trim():"";c[d]=y}return c}catch{return null}},Lp=()=>{var Yt,Rt;const t=Js(),{productSlug:s,draftId:n,primaryMockupId:a,primaryMockupKey:c,primaryVariantColor:d,primaryMockupPreview:u,variantCanvase
310s:y,setProductDetails:p,setAttachSizeTable:x,setSizeTableData:b,setSizeGuideImageUrls:C,setAttachCareInstructions:L,setCareInstructionsData:k,printingTechnology:K,listingDraft:P,setListingDraft:B,registerDraftScope:R,markDraftScopeDirty:A,scheduleDraftAutosave:D,isViewOnly:_}=mi(),[O,I]=r.useState({title:"",description:""}),{tags:ue,setTags:me,tagInput:Se,setTagInput:be,initializedDraftRef:G}=Cp(n,P==null?void 0:P.tags),[ye,we]=r.useState(!0),[re,X]=r.useState(()=>go(["XS","S","M","L","XL","2XL","3XL"])),[Q,S]=r.useState(!0),[w,M]=r.useState(wl),E=r.useRef(null),Me=r.useRef(null),Y=r.useRef(null),Ee=r.useRef(null),Be=r.useRef(n),Ae=r.useRef(null),[Ze,Ye]=r.useState(null),{data:kt,loading:he}=Ht(Sp,{variables:{productSlug:s},skip:!s}),ne=kt==null?void 0:kt.getProductBySlug,ee=(ne==null?void 0:ne.productId)??"",nt=(ne==null?void 0:ne.productName)??"",Ue=(ne==null?void 0:ne.productDescription)??"",Le=(ne==null?void 0:ne.sizeGuideNotes)??null,Te=(ne==null?void 0:ne.productDetails)??null,$e=(P==null?void 0:P.tags)!==void 0,[Ke,{loading:pt,error:ot}]=No(fu,{fetchPolicy:"network-only"}),at=!$e&&G.current!==n,[He]=qs(So,{client:Qr,fetchPolicy:"no-cache"}),{data:De,loading:Gt}=Ht(Mp,{variables:{designId:n},skip:!n,client:Qr,fetchPolicy:"cache-and-network"}),[es,ke]=r.useState(null),lt=u&&u.designId===n&&c&&d&&u.mockupKey===c&&u.colorName===d&&u.sourceToken===Fd(c,y.get(`${d}-${u.printAreaId}`))&&u.objectUrl!==es?u.objectUrl:null,Wt=(()=>{var ce;const $=De==null?void 0:De.getSavedMockups;if(!$||$.length===0)return null;const de=Ap($,c,d);if(de)return de;if(c){const xe=$.find(f=>dc(f)===c);if(xe!=null&&xe.mockupUrl)return xe.mockupUrl}if(a&&d){const xe=$.find(f=>f.mockupTemplateId===a&&f.colorName===d);if(xe!=null&&xe.mockupUrl)return xe.mockupUrl}if(a){const xe=$.find(f=>f.mockupTemplateId===a);if(xe!=null&&xe.mockupUrl)return xe.mockupUrl}if(d){const xe=$.find(f=>f.colorName===d);if(xe!=null&&xe.mockupUrl)return xe.mockupUrl}return((ce=$[0])==null?void 0:ce.mockupUrl)||null})(),[Qe,ht]=r.useState(null),[rr,Oe]=r.useState(!1),St=r.useRef(null),[ze,{data:it,loading:Lt,called:xt}]=No(Pp),et=r.useRef(it);r.useEffect(()=>{et.current=it});const Lr=r.useMemo(()=>{if(!d)return!1;for(const[$,de]of y.entries())if($.startsWith(`${d}-`)&&Yi(de))return!0;return!1},[d,y]),Dr=d?((Rt=(Yt=ne==null?void 0:ne.variants)==null?void 0:Yt.find($=>$.colorName===d))==null?void 0:Rt.colorHex)??void 0:void 0,Dt=!lt&&!Gt&&!!n&&!!ee&&!!(c||a!=null)&&Lr;r.useEffect(()=>{!Dt||xt||!ee||ze({variables:{productId:ee}})},[Dt,xt,ze,ee]),r.useEffect(()=>{St.current=null,ht(null)},[c,a,d]),r.useEffect(()=>{var ve;if(!Dt||Lt)return;const $=d,de=n;if(!$||!de)return;const ce=(ve=et.current)==null?void 0:ve.getAvailableMockupsByProductId;if(!ce||ce.length===0)return;const xe=`${c??""}|${a??""}|${$}`;if(St.current===xe)return;const f=Tp(ce,c,a);if(!f||!Hr(f.publicRenderProfile)||!Pr(f)||!Yi(y.get(`${$}-${f.printAreaId}`)))return;St.current=xe;const j=Rp(f,ne==null?void 0:ne.mockupTemplateId),Z={taskId:`${f.id}-${$}`,mockupId:f.id,colorName:$,colorHex:Dr,psdTemplateUrl:"",designImageUrl:"",publicRenderProfile:"RENDER_PROFILE_A",mockupCode:j.mockupCode,printAreaId:f.printAreaId},oe=new AbortController;let z=!1,fe=!1;return Oe(!0),Ed({tasks:[Z],mockupItems:[j],getCanvasJson:_l(y),designId:de,signal:oe.signal}).then(qe=>{var jt;const Ot=((jt=qe.get(j.mockupCode))==null?void 0:jt.get($))??null;if(z){Ot&&URL.revokeObjectURL(Ot);return}ht(Ot)}).catch(qe=>{console.error("[DetailsStep] Failed to recompose primary mockup preview",qe)}).finally(()=>{fe=!0,z||Oe(!1)}),()=>{z=!0,oe.abort(),fe||(St.current=null)}},[n,Dt,a,c,d,Dr,xt,Lt,ne==null?void 0:ne.mockupTemplateId,y]),r.useEffect(()=>{if(Qe)return()=>URL.revokeObjectURL(Qe)},[Qe]);const qt=lt??Qe??Wt,{data:lr,loading:Ct}=Ht(Ip,{variables:{productId:ee},skip:!ee}),yr=(lr==null?void 0:lr.getSizeGuideImages)||[],Mt=yr.map($=>$.storageUrl).join(` 311`),At=r.useMemo(()=>P?[...P.sizeGuideImageUrls]:Mt.split(` 312`).filter(Boolean),[P,Mt]),Tt=r.useMemo(()=>({productDetails:{...O},attachSizeTable:ye,sizeTable:ye?re:null,sizeGuideImageUrls:At,attachCareInstructions:Q,careInstructions:Q?{...w}:null}),[Q,ye,w,At,O,re]),Vt=r.useMemo(()=>Uo(Tt),[Tt]),Kt=r.useRef(!1),Xt=r.useRef(null);r.useEffect(()=>{Xt.current!==n&&(Xt.current=n??null,Kt.current=!1,Y.current=null,Ee.current=null,Ye(null))},[n]),r.useEffect(()=>{if(Ye(null),!P){Kt.current=!1,I({title:"",description:""}),we(!0),X(go(["XS","S","M","L","XL","2XL","3XL"])),S(!0),M(wl);return}Kt.current=!0,I({...P.productDetails}
312),we(P.attachSizeTable),P.sizeTable&&X(structuredClone(P.sizeTable)),S(P.attachCareInstructions),P.careInstructions&&M({...P.careInstructions})},[n,P]),r.useEffect(()=>{!n||he||Ct||!ee||P&&!Kt.current||Ye($=>$===n?$:n)},[n,P,ee,he,Ct]);const Nt=r.useMemo(()=>Ze!==n||he||Ct||lr===void 0||!ee||!O.title.trim()?null:{productId:ee,title:O.title,descriptionHtml:Vt||null,productType:"Apparel",printingTechnology:K||null},[n,Ze,ee,K,O.title,he,lr,Ct,Vt]),Ve=r.useMemo(()=>Nt?JSON.stringify(Nt):null,[Nt]);r.useEffect(()=>{Be.current=n,Ae.current=Ve,Ee.current!==null&&Ee.current!==Ve&&(Y.current=null,Ee.current=null)},[n,Ve]);const N=r.useCallback(()=>{if(!n||!Nt||!Ve||G.current===n||Y.current===n)return;const $=n,de=Ve;Y.current=$,Ee.current=de,Ke({variables:{input:Nt}}).then(ce=>{var f,j;if(!wp($,de,Be.current,Ae.current,G.current))return;const xe=(j=(f=ce.data)==null?void 0:f.previewProductOrganization)==null?void 0:j.tags;if(!Array.isArray(xe)){Y.current=null,Ee.current=null;return}G.current=$,me(xe)}).catch(()=>{Y.current===$&&Ee.current===de&&(Y.current=null,Ee.current=null)})},[n,G,Ke,me,Nt,Ve]);r.useEffect(()=>{$e||N()},[$e,N]),r.useEffect(()=>{var $,de;if(ee&&!Kt.current){const ce={title:nt,description:Ue};I(ce),p==null||p(ce);const xe=jl(Le),f=(de=($=xe.renderConfig)==null?void 0:$.sizes)!=null&&de.length?xe.renderConfig.sizes:(()=>{const j=["XS","S","M","L","XL","2XL","3XL","4XL","5XL"],Z=new Set;return Object.values(xe.referenceTable).forEach(oe=>{Object.keys(oe).forEach(z=>{Z.add(z)})}),Array.from(Z).sort((oe,z)=>{const fe=j.indexOf(oe),ve=j.indexOf(z);return fe===-1&&ve===-1?0:fe===-1?1:ve===-1?-1:fe-ve})})();if(f.length>0){const j=go(f,xe.referenceTable,xe.renderConfig);X(j),b&&b(j)}x&&x(!0),L&&L(!0),k&&k(w)}},[n,ee,nt,Ue,Le,p,b,x,L,k,w]),r.useEffect(()=>{if(!ee||Kt.current)return;const $=Up(Te);$&&M($)},[n,ee,Te]);const U=r.useCallback(()=>{A==null||A("details"),D==null||D()},[A,D]),ae=r.useCallback(()=>{const $=Se.trim();if(!$){ie.error(t("Enter a tag before adding it."));return}if($.length>Gi){ie.error(t("Tags must be at most {limit} characters.").replace("{limit}",String(Gi)));return}if(ue.length>=ka){ie.error(t("You can add up to {limit} tags.").replace("{limit}",String(ka)));return}const de=$.toLowerCase();if(ue.some(ce=>ce.toLowerCase()===de)){ie.error(t("That tag is already listed."));return}G.current=n,me(ce=>[...ce,$]),be(""),U()},[t,n,G,U,be,me,Se,ue]),le=r.useCallback($=>{G.current=n,me(de=>de.filter(ce=>ce!==$)),U()},[n,G,U,me]);r.useEffect(()=>{if(!(!R||!n))return R({scope:"details",dependsOn:["design"],capture:()=>{const $=P?[...P.sizeGuideImageUrls]:Mt.split(` 313`).filter(Boolean),de={productDetails:{...O},...kp(n,$e,G.current)?{tags:[...ue]}:{},attachSizeTable:ye,sizeTable:ye?structuredClone(re):null,sizeGuideImageUrls:$,attachCareInstructions:Q,careInstructions:Q?{...w}:null};return{commit:async ce=>{var j;const f=(j=(await He({variables:{id:ce.draftId,input:{listingDraft:de,expectedRevision:ce.expectedRevision,clientOperationId:ce.clientOperationId}}})).data)==null?void 0:j.updateDesignDraft;if(!f)throw new Error("Listing details update returned no committed draft.");return{revision:f.revision??ce.expectedRevision}},afterAccepted:()=>B==null?void 0:B(de)}}})},[Q,ye,w,n,$e,P,O,R,Mt,re,ue,B,He]),r.useEffect(()=>{!n||_||$e||he||Ct||!ee||!O.title.trim()||G.current!==n||Me.current===n||(Me.current=n,A==null||A("details"),D==null||D())},[Q,ye,w,n,$e,G,_,P,ee,A,O.title,he,D,Ct,re,ue]),r.useEffect(()=>{p&&O.title&&p(O)},[O,p]),r.useEffect(()=>{x&&x(ye),b&&b(ye?re:null)},[ye,re,x,b]),r.useEffect(()=>{C&&C(P?[...P.sizeGuideImageUrls]:Mt.split(` 314`).filter(Boolean))},[P,Mt,C]),r.useEffect(()=>{L&&L(Q),k&&k(Q?w:null)},[Q,w,L,k]);const Pt=(()=>{const $=Object.values(re.metric.data).flatMap(ce=>Object.keys(ce)).filter(ce=>ce!==void 0),de=[...new Set($)];if(de.length>0){const ce=["XS","S","M","L","XL","2XL","3XL","4XL","5XL"];return de.sort((xe,f)=>{const j=ce.indexOf(xe),Z=ce.indexOf(f);return j===-1&&Z===-1?0:j===-1?1:Z===-1?-1:j-Z})}return["XS","S","M","L","XL","2XL","3XL"]})();return he?e.jsx("div",{className:"h-full overflow-y-auto bg-gray-50 p-8",children:e.jsxs("div",{className:"max-w-4xl mx-auto
314space-y-6",children:[e.jsx(Je,{className:"h-10 w-2/3"}),e.jsx(Je,{className:"h-6 w-1/2"}),e.jsx(Er,{className:"p-6",children:e.jsx(Je,{className:"h-48 w-full"})}),e.jsx(Er,{className:"p-6",children:e.jsx(Je,{className:"h-64 w-full"})})]})}):e.jsx("div",{className:"h-full overflow-y-auto bg-gray-50",children:e.jsxs("div",{className:"max-w-6xl mx-auto p-4 sm:p-8 space-y-6",children:[e.jsx("div",{children:e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:t("Add your product title and description")})}),_&&e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-slate-100 border border-slate-200 rounded-xl",children:[e.jsx(Zn,{className:"h-5 w-5 text-slate-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-slate-800",children:t("View Only Mode")}),e.jsx("p",{className:"text-sm text-slate-600 mt-0.5",children:t("You are viewing this design in read-only mode. Product details cannot be edited.")})]})]}),e.jsx(Er,{children:e.jsxs(Oi,{className:"!p-6",children:[e.jsx("h2",{className:"text-lg font-semibold mb-4",children:t("Description")}),e.jsxs("div",{className:"flex gap-6",children:[e.jsx("div",{className:"w-[37.5%] flex-shrink-0",children:e.jsx("div",{className:"h-[300px] bg-gray-50 rounded-lg flex items-center justify-center overflow-hidden",children:(()=>{var $,de,ce;return qt?e.jsx("img",{src:qt,alt:O.title,className:"w-full h-full object-contain",onError:()=>{lt&&qt===lt&&ke(lt)}}):rr?e.jsx(Je,{className:"w-full h-full"}):(ce=(de=($=kt==null?void 0:kt.getProductBySlug)==null?void 0:$.images)==null?void 0:de[0])!=null&&ce.largeUrl?e.jsx("img",{src:kt.getProductBySlug.images[0].largeUrl,alt:O.title,className:"w-full h-full object-contain"}):e.jsx(Ir,{className:"w-16 h-16 text-gray-400"})})()})}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{children:[e.jsx(vn,{htmlFor:"product-title",className:"text-sm font-medium text-gray-700",children:t("Title")}),e.jsx(ci,{id:"product-title",value:O.title,onChange:$=>{I(de=>({...de,title:$.target.value})),U()},className:"mt-1",placeholder:t("Enter product title"),disabled:_})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(vn,{className:"text-sm font-medium text-gray-700",children:t("Description")}),e.jsx(sm,{className:"w-4 h-4 text-gray-400"})]}),e.jsxs("div",{className:"border border-gray-300 rounded-t-md bg-gray-50 p-2 flex items-center gap-1 flex-wrap",children:[e.jsx("select",{className:"text-xs border border-gray-300 rounded px-2 py-1",children:e.jsx("option",{children:t("Default")})}),e.jsx("div",{className:"w-px h-4 bg-gray-300 mx-1"}),e.jsx("button",{type:"button",className:"p-1 hover:bg-gray-200 rounded",children:e.jsx(Gu,{className:"w-3.5 h-3.5"})}),e.jsx("button",{type:"button",className:"p-1 hover:bg-gray-200 rounded",children:e.jsx(Vu,{className:"w-3.5 h-3.5"})}),e.jsx("button",{type:"button",className:"p-1 hover:bg-gray-200 rounded",children:e.jsx(Ku,{className:"w-3.5 h-3.5"})}),e.jsx("div",{className:"w-px h-4 bg-gray-300 mx-1"}),e.jsx("button",{type:"button",className:"p-1 hover:bg-gray-200 rounded",children:e.jsx(Pu,{className:"w-3.5 h-3.5"})}),e.jsx("button",{type:"button",className:"p-1 hover:bg-gray-200 rounded",children:e.jsx(Ud,{className:"w-3.5 h-3.5"})}),e.jsx("button",{type:"button",className:"p-1 hover:bg-gray-200 rounded",children:e.jsx(Ld,{className:"w-3.5 h-3.5"})}),e.jsx("div",{className:"w-px h-4 bg-gray-300 mx-1"}),e.jsx("button",{type:"button",className:"p-1 hover:bg-gray-200 rounded",children:e.jsx(Yu,{className:"w-3.5 h-3.5"})}),e.jsx("button",{type:"button",className:"p-1 hover:bg-gray-200 rounded",children:e.jsx(Hu,{className:"w-3.5 h-3.5"})}),e.jsx("div",{className:"w-px h-4 bg-gray-300 mx-1"}),e.jsx("button",{type:"button",className:"p-1 hover:bg-gray-200 rounded",children:e.jsx(Wu,{className:"w-3.5 h-3.5"})}),e.jsx("button",{type:"button",className:"p-1 hover:bg-gray-200 rounded",children:e.jsx(am,{className:"w-3.5 h-3.5"})}),e.jsx("button",{type:"button",className:"p-1 hover:bg-gray-200 rounded",children:e.jsx(nm,{className:"w-3.5 h-3.5"})}),e.jsx("button",{type:"button",className:"p-1 hover:bg-gray-200 rounded",children:e.jsx(Ir,{className:"w-3.5 h-3.5"})})]}),e.jsx("div",{ref:E,contentEditable:!0,className:"border border-t-0 border-gray-300 rounded-b-md p-3 min-h-[200px] focus:outline-none focus:ring-2 focus:ring-[#15B6
3147F] text-sm",dangerouslySetInnerHTML:{__html:jo.sanitize(O.description)},onInput:$=>{I(de=>({...de,description:$.target.innerHTML})),U()}})]})]})]})]})}),e.jsx(Er,{children:e.jsxs(Oi,{className:"!p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3 mb-4",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"store-listing-tags-heading",className:"text-lg font-semibold",children:t("Tags")}),e.jsx("p",{className:"mt-1 text-sm text-gray-500",children:t("These tags will be published with your product. You can add or remove tags as needed.")})]}),e.jsxs("span",{className:"text-xs text-gray-500",children:[ue.length,"/",ka]})]}),pt&&ue.length===0?e.jsx(Je,{className:"h-10 w-full"}):ue.length>0?e.jsx("ul",{"aria-labelledby":"store-listing-tags-heading",className:"flex flex-wrap gap-2",children:ue.map($=>e.jsxs("li",{className:"inline-flex h-8 items-center gap-1 rounded-full border border-[#15B67F]/30 bg-[#15B67F]/10 py-0 pl-3 pr-1 text-[13px] font-medium leading-none text-gray-800",children:[e.jsx("span",{children:$}),e.jsx(pe,{type:"button",variant:"ghost",size:"icon",onClick:()=>le($),disabled:_,"aria-label":t("Remove tag {tag}").replace("{tag}",$),className:"h-6 w-6 rounded-full text-gray-500 hover:bg-white hover:text-gray-800",children:e.jsx(Po,{className:"h-3 w-3","aria-hidden":"true"})})]},$.toLowerCase()))}):e.jsx("p",{className:"text-sm text-gray-500",children:t("No tags selected.")}),ot&&!$e&&e.jsxs("div",{role:"alert",className:"mt-3 flex flex-wrap items-center gap-2 text-sm text-amber-700",children:[e.jsx("span",{children:t("Default tags could not be loaded yet. Try again before publishing.")}),e.jsx(pe,{type:"button",variant:"outline",onClick:N,disabled:pt,className:"h-11 border-amber-300 font-medium hover:bg-amber-50",children:t("Retry")})]}),e.jsxs("div",{className:"mt-4 flex flex-col gap-2 sm:flex-row",children:[e.jsx(ci,{value:Se,onChange:$=>be($.target.value),onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),ae())},maxLength:Gi,placeholder:t("Add a tag"),"aria-label":t("Add a tag"),disabled:_||at||ue.length>=ka}),e.jsx(pe,{type:"button",onClick:ae,disabled:_||at||!Se.trim()||ue.length>=ka,className:"h-11",children:t("Add tag")})]})]})}),e.jsx(Er,{children:e.jsxs(Oi,{className:"!p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Zs,{id:"attach-size-table",checked:ye,onCheckedChange:$=>{we($),U()},disabled:_}),e.jsx(vn,{htmlFor:"attach-size-table",className:"text-lg font-semibold cursor-pointer",children:t("Attach size table")})]}),e.jsx("span",{className:"text-sm text-gray-500",children:t("You can edit size table in your store's platform")})]}),ye&&e.jsx(jp,{sizeTable:re,sizes:Pt,notes:jl(Le).notes,images:yr,copy:t})]})}),e.jsx(Er,{children:e.jsxs(Oi,{className:"!p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Zs,{id:"attach-care-instructions",checked:Q,onCheckedChange:$=>{S($),U()},disabled:_}),e.jsx(vn,{htmlFor:"attach-care-instructions",className:"text-lg font-semibold cursor-pointer",children:t("Attach care instructions")})]}),e.jsx("span",{className:"text-sm text-gray-500",children:t("You can edit care instructions in your store's platform")})]}),Q&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"font-semibold text-gray-900",children:t("Care Instructions")}),w.general&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("img",{src:Ou,alt:"",width:20,height:20,className:"mt-0.5 shrink-0","aria-hidden":"true"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-sm font-medium text-gray-700",children:t("General")}),e.jsx("p",{className:"text-sm text-gray-700",children:w.general})]})]}),w.wash&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("img",{src:Bu,alt:"",width:20,height:20,className:"mt-0.5 shrink-0","aria-hidden":"true"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-sm font-medium text-gray-700",children:t("Wash")}),e.jsx("p",{className:"text-sm text-gray-700",children:w.wash})]})]}),w.dry&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("img",{src:$u,alt:"",width:20,height:20,className:"mt-0.5 shrink-0","aria-hidden":"true"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-sm font-medium text-gray-700",children:t("Dry")}),e.jsx("p",{className:"text-sm text-gray-700",children:w.dry})]})]}),w.iron&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("img",{src:zu,alt:"",width:20,height:20,className:"mt-0.5 shrink-0","aria-hidden":"true"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-sm font-medium text-gray-700",children:t("Iron")}),e.jsx("p",{className:"text-sm text-gray-700",children:w.iron})]})]}),w.bleach&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("img",{src:_u,alt:"",width:20,height:20,className:"mt-0.5 shrink-0","aria-hidden":"true"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-sm font-medium text-gray-700",children:t("Bleach")}),e.jsx("p",{className:"text-sm text-gray-700",children:w.bleach})]})]})]})]})}),e.jsx("div",{className:"h-8"})]})})},Dp=t=>{if(!t||typeof t!="object"||Array.isArray(t))return!1;const s=t;return typeof s.colorName=="string"&&typeof s.size=="string"&&typeof s.retailPrice=="number"&&(s.printTechnology===void 0||typeof s.printTechnology=="string")},Op=(t,s,n)=>t!=null?t.toString():s.length>0&&s[0].profitMargin?s[0].profitMargin.toString():n,kl=(t,s)=>t.map((n,a)=>({colorName:n.colorName,size:n.size,printTechnology:n.printTechnology,baseProviderPrice
314:n.baseProviderPrice,printAreaCost:n.printAreaCost,productCost:n.productCost,brandingCost:n.brandingCost,shippingCost:n.shippingCost,retailPrice:n.retailPrice,profit:n.profit,profitMargin:n.profitMargin,...a===0?{globalProfitMarginInput:Number.parseFloat(s)||50}:{}})),Cl=t=>{const s=t[0],n=s&&typeof s=="object"&&!Array.isArray(s)?Number(s.globalProfitMarginInput??50):50,a=d=>{const u=Number(d??0);return Number.isFinite(u)?u:0},c=t.filter(d=>!!d&&typeof d=="object"&&!Array.isArray(d)).map(d=>({colorName:String(d.colorName??""),size:String(d.size??""),printTechnology:String(d.printTechnology??""),baseProviderPrice:a(d.baseProviderPrice),printAreaCost:a(d.printAreaCost),productCost:a(d.productCost),brandingCost:a(d.brandingCost),shippingCost:a(d.shippingCost),retailPrice:a(d.retailPrice),profit:a(d.profit),profitMargin:a(d.profitMargin)})).sort((d,u)=>`${d.colorName}|${d.size}|${d.printTechnology}`.localeCompare(`${u.colorName}|${u.size}|${u.printTechnology}`));return JSON.stringify({globalProfitMarginInput:n,entries:c})},Bp=({value:t,minimumPrice:s,currencySymbol:n,onChange:a,disabled:c=!1})=>{const d=Js(),[u,y]=r.useState(t.toFixed(2)),[p,x]=r.useState(!1);r.useEffect(()=>{p||y(t.toFixed(2))},[t,p]);const b=()=>{x(!0)},C=k=>{y(k.target.value)},L=()=>{x(!1);const k=Number.parseFloat(u)||0;k<s&&ie.info(`${d("Minimum price is")} ${n}${s.toFixed(2)}`),a(k)};return e.jsx(ci,{type:"number",value:u,onChange:C,onFocus:b,onBlur:L,className:"w-16 text-center h-6 text-xs px-1",step:"0.01",min:s.toFixed(2),disabled:c})},$p=()=>{var Yt,Rt,$,de,ce,xe;const t=Js(),{productSlug:s,draftId:n,providerId:a,providerName:c,selectedVariants:d,variantCanvases:u,variantPricing:y,setVariantPricing:p,acknowledgeVariantPricingPersisted:x,invalidateVariantPricingPersistence:b,brandingItems:C,setBrandingItems:L,isViewOnl
314y:k,printingTechnology:K,setPrintingTechnology:P,registerBeforeLeave:B,registerDraftScope:R,markDraftScopeDirty:A,discardDraftScope:D,scheduleDraftAutosave:_,commitDraft:O}=mi(),[I,ue]=r.useState(!1),[me,Se]=r.useState("50"),[be,G]=r.useState([]),[ye,we]=r.useState([]),[re,X]=r.useState(!1),[Q,S]=r.useState(!1),[w,M]=r.useState(!1),E=r.useRef(null),Me=r.useRef(null),Y=r.useRef(null),Ee=r.useRef(n),[Be,Ae]=r.useState(!1),Ze=r.useRef(null),Ye=r.useRef(!1),kt=r.useRef("50");r.useEffect(()=>{Ee.current!==n&&(Ee.current=n,Me.current=null,Y.current=null,E.current=null,G([]),we([]),Se("50"),M(!1),S(!1))},[n]),r.useEffect(()=>{Ye.current=Q},[Q]),r.useEffect(()=>{kt.current=me},[me]);const he=r.useCallback(()=>{S(!0),n&&(b==null||b(n)),A==null||A("pricing"),_==null||_()},[n,b,A,_]);r.useEffect(()=>{if(be.length>0&&p){const f=be.map((j,Z)=>({colorName:j.colorName,size:j.size,printTechnology:j.printTechnology,baseProviderPrice:j.baseProviderPrice,printAreaCost:j.printAreaCost,productCost:j.productCost,brandingCost:j.brandingCost,shippingCost:j.shippingCost,retailPrice:j.retailPrice,profit:j.profit,profitMargin:j.profitMargin,...Z===0?{globalProfitMarginInput:Number.parseFloat(me)||50}:{}}));p(f)}},[be,p,me]);const{data:ne,loading:ee,error:nt}=Ht(Xl,{variables:{productSlug:s},skip:!s,fetchPolicy:"network-only",nextFetchPolicy:"cache-and-network"}),{data:Ue,loading:Le,error:Te}=Ht(lc,{variables:{providerId:a},skip:!a,fetchPolicy:"network-only"}),$e=r.useMemo(()=>(Ue==null?void 0:Ue.getProviderBrandingPricing)??[],[Ue]),Ke=r.useMemo(()=>!$e.length||!(C!=null&&C.length)?!1:C.some(f=>{const j=qi(f,$e);return j?ko(f,j)!==f:!1}),[C,$e]);r.useEffect(()=>{if(!$e.length||!C||C.length===0||!L)return;const f=C.map(Z=>{const oe=qi(Z,$e);return oe?ko(Z,oe):Z});f.some((Z,oe)=>Z!==C[oe])&&L(f)},[$e,C,L]);const pt=r.useMemo(()=>{var j,Z;if(!((j=ne==null?void 0:ne.getProductBySlug)!=null&&j.assignedProviders)||!a)return null;const f=ne.getProductBySlug.assignedProviders.find(oe=>oe.providerId===a);return((Z=f==null?void 0:f.priceRange)==null?void 0:Z.currency)??null},[ne,a]),{data:ot,loading:at,error:He}=Ht(Xu,{variables:{currency:pt},skip:!pt}),De=Number(((Yt=ot==null?void 0:ot.transactionFeeByCurrency)==null?void 0:Yt.feeAmount)??0)||0,[Gt]=qs(So,{client:Qr,fetchPolicy:"no-cache"});r.useEffect(()=>{if(!(!R||!n))return R({scope:"pricing",dependsOn:["design"],capture:()=>{const f=be.map(oe=>({...oe})),j=me,Z=kl(f,j);return{validate:()=>{if(Z.length===0)throw new Error("No variant prices are available to save.")},commit:async oe=>{var z;X(!0);try{const ve=(z=(await Gt({variables:{id:oe.draftId,input:{variantPricing:Z,expectedRevision:oe.expectedRevision,clientOperationId:oe.clientOperationId}}})).data)==null?void 0:z.updateDesignDraft;if(!ve)throw new Error("Pricing update returned no committed draft.");return{revision:ve.revision??oe.expectedRevision}}finally{X(!1)}},afterAccepted:oe=>{x==null||x(oe.draftId),E.current={prices:f.map(z=>({...z})),margin:j},S(!1)}}}})},[x,n,me,R,Gt,be]);const ke=r.useMemo(()=>{var f;return!((f=ne==null?void 0:ne.getProductBySlug)!=null&&f.assignedProviders)||!a?null:ne.getProductBySlug.assignedProviders.find(j=>j.providerId===a)},[ne,a]),lt=((Rt=ke==null?void 0:ke.priceRange)==null?void 0:Rt.currency)??"",Qe=({EGP:"EGP",AED:"AED",SAR:"SAR"}[lt]??lt)||"â",{data:ht,loading:rr,error:Oe}=Ht(qu,{variables:{providerId:a},skip:!a}),St=r.useMemo(()=>(ht==null?void 0:ht.getProviderShippingZones.filter(f=>f.isActive))??[],[ht]),ze=St.length>0,it=ze?0:(($=ke==null?void 0:ke.pricingConfiguration)==null?void 0:$.shippingCost)||0,Lt=K||((de=ke==null?void 0:ke.printingTechnologies)==null?void 0:de[0]);r.useEffect(()=>{var f;!K&&((f=ke==null?void 0:ke.printingTechnologies)!=null&&f[0])&&P&&P(ke.printingTechnologies[0])},[K,ke==null?void 0:ke.printingTechnologies,P]);const xt=r.useCallback(f=>{var z;const j=(z=ke==null?void 0:ke.pricingConfiguration)==null?void 0:z.printAreas;if(!j||!u)return 0;const Z=rd(u,f);let oe=0;return Z.forEach(fe=>{const ve=j.find(qe=>qe.printAreaCode.toLowerCase()===fe.toLowerCase());ve!=null&&ve.isAvailable&&(oe+=ve.additionalPrice)}),oe},[ke,u]),et=r.useMemo(()=>!C||C.length===0?0:C.filter(f=>f.enabled).reduce((f,j)=>f+(j.unitPrice||0),0),[C]),Lr=f=>({DTG:t("DTG (Direct-to-garment)"),DTF:t("DTF (Direct-to-film)"),SCREEN_PRINT:t("Screen Print"),EMBROIDERY:t("Embroidery"),SUBLIMATION:t("Sublimation")})[f]||f;r.useEffect(()=>{var oe;if(!((oe=ke==null?void 0:ke.pricingConfiguration)!=null&&oe.variantPricing)||!d||ee||Le||rr||at||Ke||nt||Te||Oe||He||w||pt&&De===0&&!ot)return;const f=ke.pricingConfiguration.variantPricing,j=[];
314if(To(d).forEach(({colorName:z,size:fe})=>{j.push({colorName:z,size:fe})}),y&&Array.isArray(y)&&y.length>0){const z=new Map;y.filter(Dp).forEach(sr=>{const nr=`${sr.colorName}|${sr.size}`;z.set(nr,sr)});const fe=j.map(({colorName:sr,size:nr})=>{const ar=`${sr}|${nr}`,Qs=z.get(ar),ft=f.find(gt=>gt.colorName===sr&>.size===nr&&(!Lt||gt.printTechnology===Lt))||f.find(gt=>gt.colorName===sr&>.size===nr);if(Qs){const gt=(ft==null?void 0:ft.price)||0,Wr=xt(sr),en=gt+Wr,qr=it,ir=en+et+qr+De;let ts=Qs.retailPrice||ir;ts<ir&&(ts=ir);const We=ts-ir,tt=ts>0?We/ts*100:0;return{colorName:sr,size:nr,printTechnology:Lt||Qs.printTechnology||(ft==null?void 0:ft.printTechnology)||"",baseProviderPrice:gt,printAreaCost:Wr,productCost:en,brandingCost:et,shippingCost:qr,retailPrice:Math.round(ts*100)/100,profit:Math.round(We*100)/100,profitMargin:Math.round(tt*10)/10,isAvailable:!!ft}}else{const gt=xt(sr),Wr=(ft==null?void 0:ft.price)||0,en=Wr+gt,qr=en+et+it+De;return{colorName:sr,size:nr,printTechnology:Lt||(ft==null?void 0:ft.printTechnology)||"",baseProviderPrice:Wr,printAreaCost:gt,productCost:en,brandingCost:et,shippingCost:it,retailPrice:Math.round(qr*100)/100,profit:0,profitMargin:0,isAvailable:!!ft}}});G(fe),M(!0);const ve=y[0],qe=ve==null?void 0:ve.globalProfitMarginInput,Ot=Op(qe,fe,kt.current);Se(Ot);const jt=kl(fe,Ot);!k&&n&&Cl(y)!==Cl(jt)&&(Y.current=n);return}const Z=j.map(({colorName:z,size:fe})=>{const ve=f.find(ar=>ar.colorName===z&&ar.size===fe&&(!Lt||ar.printTechnology===Lt))||f.find(ar=>ar.colorName===z&&ar.size===fe),qe=!!ve,Ot=xt(z),jt=(ve==null?void 0:ve.price)||0,sr=jt+Ot,nr=sr+et+it+De;return{colorName:z,size:fe,printTechnology:Lt||(ve==null?void 0:ve.printTechnology)||"",baseProviderPrice:jt,printAreaCost:Ot,productCost:sr,brandingCost:et,shippingCost:it,retailPrice:Math.round(nr*100)/100,profit:0,profitMargin:0,isAvailable:qe}});G(Z),E.current={prices:Z.map(z=>({...z})),margin:kt.current},M(!0),!k&&n&&Z.length>0&&(Y.current=n)},[ke,d,y,w,it,De,ot,pt,Lt,xt,I,et,n,k,ee,Le,rr,at,Ke,nt,Te,Oe,He]),r.useEffect(()=>{k||!n||!w||be.length===0||Y.current!==n||Me.current===n||(Y.current=null,Me.current=n,b==null||b(n),A==null||A("pricing"),_==null||_())},[n,b,w,k,A,_,be]),r.useEffect(()=>{be.length!==0&&we(f=>{const j=new Map(f.map(z=>[z.size,z.isExpanded])),Z=["XS","S","M","L","XL","2XL","3XL","4XL","5XL"];return[...new Set(be.map(z=>z.size))].sort((z,fe)=>{const ve=Z.indexOf(z),qe=Z.indexOf(fe);return ve===-1&&qe===-1?z.localeCompare(fe):ve===-1?1:qe===-1?-1:ve-qe}).map(z=>{const fe=be.filter(jt=>jt.size===z),ve=fe.map(jt=>jt.retailPrice),qe=fe.map(jt=>jt.productCost),Ot=fe.map(jt=>jt.profit);return{size:z,isExpanded:j.get(z)??!0,variants:fe,minRetailPrice:Math.min(...ve),maxRetailPrice:Math.max(...ve),minProductCost:Math.min(...qe),maxProductCost:Math.max(...qe),minProfit:Math.min(...Ot),maxProfit:Math.max(...Ot)}})})},[be]);const Dr=r.useCallback(f=>{we(j=>j.map(Z=>Z.size===f?{...Z,isExpanded:!Z.isExpanded}:Z))},[]),Dt=r.useCallback(f=>ze?f.productCost+f.brandingCost+De:f.productCost+f.brandingCost+f.shippingCost+De,[De,ze]),qt=r.useCallback((f,j,Z)=>{G(oe=>oe.map(z=>{if(z.colorName===f&&z.size===j){const fe=Dt(z),ve=Math.max(Z,fe),qe=ve-fe,Ot=ve>0?qe/ve*100:0;return{...z,retailPrice:Math.round(ve*100)/100,profit:Math.round(qe*100)/100,profitMargin:Math.round(Ot*10)/10}}return z})),he()},[Dt,he]),lr=r.useCallback((f,j)=>{G(Z=>Z.map(oe=>{if(oe.size===f){const z=Dt(oe),fe=Math.max(j,z),ve=fe-z,qe=fe>0?ve/fe*100:0;return{...oe,retailPrice:Math.round(fe*100)/100,profit:Math.round(ve*100)/100,profitMargin:Math.round(qe*10)/10}}return oe})),he()},[Dt,he]),Ct=r.useCallback(()=>{const f=Number.parseFloat(me)||0;if(f>=100){ie.error(t("Profit margin must be less than 100%"));return}G(j=>j.map(Z=>{const oe=Dt(Z),z=f>0?oe/(1-f/100):oe,fe=z-oe;return{...Z,retailPrice:Math.round(z*100)/100,profit:Math.round(fe*100)/100,profitMargin:Math.round(f*10)/10}})),he(),ie.success(`${t("Applied")} ${f}% ${t("profit margin to all variants")}`)},[Dt,he,t,me]),yr=r.useCallback(()=>{var f;if(Se("0"),ue(!1),(f=ke==null?void 0:ke.pricingConfiguration)!=null&&f.variantPricing){const j=ke.pricingConfiguration.variantPricing;G(Z=>Z.map(oe=>{const z=j.find(jt=>jt.colorName===oe.colorName&&jt.size===oe.size),fe=xt(oe.colorName),ve=(z==null?void 0:z.price)||0,qe=ve+fe,Ot=qe+et+it+De;
314return{...oe,baseProviderPrice:ve,printAreaCost:fe,productCost:qe,brandingCost:et,retailPrice:Math.round(Ot*100)/100,profit:0,profitMargin:0}}))}he(),ie.info(t(ze?"Prices reset to minimum (product cost + branding + order fee)":"Prices reset to minimum (product cost + branding + shipping + order fee)"))},[et,xt,he,t,ke,ze,it,De]),Mt=r.useCallback(async(f=!1)=>{if(!n||!O){if(ie.error(t("No draft to save")),f)throw new Error("The design draft session is not ready.");return}X(!0);try{await O("manual-save",["pricing"]),ie.success(t("Pricing saved successfully"))}catch(j){if(console.error("Failed to save pricing:",j),ie.error(t("Failed to save pricing")),f)throw j}finally{X(!1)}},[O,n,t]),At=r.useCallback(()=>{const f=E.current;if(!f){S(!1),D==null||D("pricing");return}G(f.prices.map(j=>({...j}))),Se(f.margin),S(!1),D==null||D("pricing"),ie.message(t("Discarded unsaved changes."))},[D,t]);r.useEffect(()=>{if(B)return B("prices",async()=>{if(Ye.current)return new Promise((f,j)=>{Ze.current={resolve:f,reject:j},Ae(!0)})}),()=>{B("prices",null)}},[B]);const Tt=r.useCallback(async()=>{var f,j;Ae(!1);try{await Mt(!0),(f=Ze.current)==null||f.resolve()}catch{(j=Ze.current)==null||j.reject()}finally{Ze.current=null}},[Mt]),Vt=r.useCallback(()=>{var f;Ae(!1),At(),(f=Ze.current)==null||f.resolve(),Ze.current=null},[At]),Kt=r.useCallback(()=>{var f;Ae(!1),(f=Ze.current)==null||f.reject(),Ze.current=null},[]),Xt=(f,j)=>f===j?`${f.toFixed(2)}`:`${f.toFixed(2)} - ${j.toFixed(2)}`,Nt=ze?"grid-cols-[3fr_2fr_2fr_2fr_1fr_2fr]":"grid-cols-[3fr_2fr_2fr_2fr_2fr_1fr_2fr]",Ve=St.map(f=>f.firstItemCost),N=St.map(f=>f.additionalItemCost),U=((ce=St[0])==null?void 0:ce.currency)||lt,ae=Ve.length>0?Math.min(...Ve):void 0,le=Ve.length>0?Math.max(...Ve):void 0,ct=N.length>0?Math.min(...N):void 0,Pt=N.length>0?Math.max(...N):void 0;return ee||Le||rr||at||Ke?e.jsxs("div",{className:"p-8 max-w-7xl mx-auto space-y-6",children:[e.jsx(Je,{className:"h-8 w-48"}),e.jsx(Je,{className:"h-4 w-96"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(Je,{className:"h-12 w-full"}),e.jsx(Je,{className:"h-64 w-full"})]})]}):nt||Te||Oe||He?e.jsx("div",{className:"p-8 max-w-7xl mx-auto",children:e.jsx(Er,{className:"p-8",children:e.jsxs("div",{className:"flex items-center gap-3 text-red-600",children:[e.jsx(yn,{className:"h-5 w-5"}),e.jsx("span",{children:t("Failed to load pricing data. Please try again.")})]})})}):ke?e.jsxs("div",{className:"p-8 max-w-7xl mx-auto space-y-6 overflow-y-auto h-full",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold text-gray-900",children:t("Set up prices")}),e.jsx("p",{className:"mt-1 text-sm text-gray-600",children:t("Your retail prices will always be converted and published in your store's currency.")})]}),!k&&e.jsx(pe,{variant:"link",onClick:yr,className:"text-[#15B67F] hover:text-[#12a372] p-0",children:t("Reset to default")})]}),Q&&!k&&e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-amber-50 border border-amber-200 rounded-xl",children:[e.jsx(yn,{className:"h-5 w-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium text-amber-900",children:t("You have unsaved price changes")}),e.jsx("p",{className:"text-sm text-amber-800 mt-0.5",children:t("Save them before continuing to review, or discard to revert to the last saved version.")})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs(pe,{variant:"outline",size:"sm",onClick:At,className:"border-amber-300 text-amber-900 hover:bg-amber-100",children:[e.jsx(hl,{className:"h-3.5 w-3.5 mr-1.5"}),t("Discard")]}),e.jsxs(pe,{size:"sm",onClick:()=>{Mt()},disabled:re,className:"bg-[#15B67F] hover:bg-[#12a372] text-white",children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1.5"}),t(re?"Savingâ¦":"Save")]})]})]}),k&&e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-slate-100 border border-slate-200 rounded-xl",children:[e.jsx(Zn,{className:"h-5 w-5 text-slate-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-slate-800",children:t("View Only Mode")}),e.jsx("p",{className:"text-sm text-slate-600 mt-0.5",children:t("You are viewing this design in read-only mode. Price
314s cannot be edited.")})]})]}),!ze&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zs,{id:"includeShipping",checked:I,onCheckedChange:f=>{ue(f===!0),he()},disabled:k}),e.jsx("label",{htmlFor:"includeShipping",className:"text-sm text-gray-700 cursor-pointer",children:t("Include shipping cost in profit calculation")})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 p-4 bg-white border border-gray-200 rounded-xl shadow-sm",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-semibold text-gray-900 leading-tight",children:t("Set profit margin")}),e.jsx("span",{className:"text-xs text-gray-500 mt-0.5",children:t("Apply across all variants")})]}),e.jsxs("div",{className:`inline-flex items-stretch h-10 rounded-lg border border-gray-200 bg-gray-50 overflow-hidden transition-all focus-within:border-[#15B67F] focus-within:ring-2 focus-within:ring-[#15B67F]/15 ${k?"opacity-60":""}`,children:[e.jsx("button",{type:"button",onClick:()=>{const f=Number.parseFloat(me)||0;Se(Math.max(0,f-5).toString())},disabled:k,"aria-label":t("Decrease margin by 5%"),className:"w-9 flex items-center justify-center text-gray-500 hover:bg-gray-100 hover:text-gray-900 transition-colors disabled:cursor-not-allowed text-lg leading-none",children:"â"}),e.jsx(ci,{type:"number",value:me,onChange:f=>Se(f.target.value),className:"w-16 h-full text-center text-sm font-semibold text-gray-900 bg-transparent border-0 px-0 focus-visible:ring-0 focus-visible:ring-offset-0 tabular-nums",min:"0",max:"1000",disabled:k}),e.jsx("span",{className:"px-2 flex items-center text-sm font-medium text-gray-500 border-l border-gray-200 bg-white/40",children:"%"}),e.jsx("button",{type:"button",onClick:()=>{const f=Number.parseFloat(me)||0;Se((f+5).toString())},disabled:k,"aria-label":t("Increase margin by 5%"),className:"w-9 flex items-center justify-center text-gray-500 hover:bg-gray-100 hover:text-gray-900 transition-colors disabled:cursor-not-allowed text-lg leading-none border-l border-gray-200",children:"+"})]}),e.jsx("div",{className:"hidden sm:flex items-center gap-1.5",children:["15","35","50"].map(f=>e.jsxs("button",{type:"button",onClick:()=>!k&&Se(f),disabled:k,className:`px-2.5 py-1.5 text-xs font-medium rounded-md border transition-colors disabled:opacity-50 ${me===f?"bg-[#15B67F] text-white border-[#15B67F]":"bg-white text-gray-700 border-gray-200 hover:border-[#15B67F] hover:text-[#15B67F]"}`,children:[f,"%"]},f))}),e.jsx(pe,{onClick:Ct,className:"h-10 bg-gray-900 hover:bg-gray-800 text-white text-sm font-medium px-5 rounded-lg shadow-sm",disabled:k,children:t("Update")}),Q&&!k&&e.jsx(pe,{onClick:()=>{Mt()},disabled:re,className:"h-10 bg-[#15B67F] hover:bg-[#12a372] text-white text-sm font-medium px-5 rounded-lg shadow-sm shadow-[#15B67F]/20 ml-auto",children:t(re?"Saving...":"Save Prices")})]}),e.jsxs(Er,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-gray-50 border-b",children:e.jsxs("div",{className:`grid ${Nt} gap-2 px-4 py-3 text-xs font-medium text-gray-600`,children:[e.jsx("div",{children:e.jsx("div",{className:"font-semibold text-sm text-gray-900",children:((xe=ne==null?void 0:ne.getProductBySlug)==null?void 0:xe.productName)||t("Product")})}),e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{children:[t("Retail price")," (",lt,")"]}),e.jsx("div",{className:"font-normal text-gray-500 text-[10px]",children:t("This price will be shown to your customers")})]}),e.jsx("div",{className:"text-center",children:e.jsxs("div",{children:[t("Product Provider costs")," (",lt,")"]})}),!ze&&e.jsx("div",{className:"text-center",children:e.jsxs("div",{children:[t("Shipping")," (",lt,")"]})}),e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsxs("span",{children:[t("Branding")," (",lt,")"]}),e.jsxs(ul,{children:[e.jsx(ml,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex items-center justify-center rounded-full hover:bg-gray-100 p-0.5 transition-colors",children:e.jsx(Vi,{className:"h-3.5 w-3.5 text-gray-400 hover:text-gray-600 cursor-pointer"})})}),e.jsx(pl,{side:"top",className:"w-64 p-3",children:e.jsx("p",{className:"text-xs text-gray-600",children:t("Branding cost per unit. This includes all selected branding items (hang tags, packaging inserts, etc.) for each product.")})})]})]}),e.jsx("div",{className:"font-normal text-gray-500 text-[10px]",children:t("per unit")})]}),e.jsx("div",{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsxs("span",{children:[t("Order Fee")," (",lt,")"]}),e.jsxs(ul,{children:[e.jsx(ml,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex items-center justify-center rounded-full hover:bg-gray-100 p-0.5 transition-colors",children:e.jsx(Vi,{className:"h-3.5 w-3.5 text-gray-400 hover:text-gray-600 cursor-pointer"})})}),e.jsx(pl,{side:"top",className:"w-64 p-3",children:e.jsx("p",{className:"text-xs text-gray-600",children:t("This is a fixed transaction fee charged per order based on your country/currency. It covers payment processing costs.")})})]})]})}),e.jsxs("div",{className:"text-end",children:[e.jsxs("div",{children:[t("Est. profit")," (",lt,")"]}),e.jsx("div",{className:"font-normal text-gray-500 text-[10px]",children:t("+Profit margin %")})]})]})}),e.jsxs("div",{className:"divide-y",children:[be.length>0&&e.jsxs("div",{className:`grid ${Nt} gap-2 px-4 py-3 bg-gray-50/50 items-center`,children:[e.jsx("div",{className:"font-medium text-gray-900",children:t("All Variants")}),e.jsx("div",{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx("button",{type:"button",className:"w-5 h-5 border rounded flex items-center justify-center text-gray-500 hover:bg-gray-100 text-xs",children:"-"}),e.jsx("span",{className:"text-xs min-w-[60px]",children:Xt(Math.min(...be.map(f=>f.retailPrice)),Math.max(...be.map(f=>f.retailPrice)))}),e.jsx("button",{type:"button",className:"w-5 h-5 border rounded flex items-center justify-center text-gray-500 hover:bg-gray-100 text-xs",children:"+"})]})}),e.jsx("div",{className:"text-center text-xs text-gray-600",children:Xt(Math.min(...be.map(f=>
314f.productCost)),Math.max(...be.map(f=>f.productCost)))}),!ze&&e.jsx("div",{className:"text-center text-xs text-gray-600",children:it.toFixed(2)}),e.jsx("div",{className:"text-center text-xs text-gray-600",children:et>0?e.jsxs("span",{className:"text-[#15B67F]",children:["+",et.toFixed(2)]}):e.jsx("span",{className:"text-gray-400",children:"-"})}),e.jsx("div",{className:"text-center text-xs text-gray-600",children:De.toFixed(2)}),e.jsxs("div",{className:"text-end",children:[e.jsx("span",{className:"text-[#15B67F] font-medium text-xs",children:Xt(Math.min(...be.map(f=>f.profit)),Math.max(...be.map(f=>f.profit)))}),e.jsx("span",{className:"ml-1",children:e.jsx(Xn,{className:"inline h-3 w-3 text-[#15B67F]"})})]})]}),ye.map(f=>e.jsxs(Ji.Fragment,{children:[e.jsxs("div",{role:"button",tabIndex:0,className:`grid ${Nt} gap-2 px-4 py-2 bg-white hover:bg-gray-50 cursor-pointer items-center`,onClick:()=>Dr(f.size),onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&Dr(f.size)},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[f.isExpanded?e.jsx(Bl,{className:"h-3 w-3 text-gray-500"}):e.jsx(Io,{className:"h-3 w-3 text-gray-500"}),e.jsxs("span",{className:"font-medium text-gray-900 text-sm",children:[f.size," (",f.variants.length,")"]})]}),e.jsx("div",{className:"text-center",children:(()=>{const j=f.variants.map(z=>Dt(z)),Z=Math.max(...j),oe=f.minRetailPrice<=Z;return e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(jn,{children:e.jsxs(wn,{children:[e.jsx(kn,{asChild:!0,children:e.jsx("button",{type:"button",className:`w-5 h-5 border rounded flex items-center justify-center text-xs ${oe?"text-gray-300 cursor-not-allowed border-gray-200":"text-gray-500 hover:bg-gray-100"}`,onClick:z=>{if(z.stopPropagation(),oe)ie.info(`${t("Minimum price is")} ${Qe}${Z.toFixed(2)} ${t("for this size")}`);else{const fe=Math.max(Z,f.minRetailPrice-1);lr(f.size,fe)}},disabled:oe,children:"-"})}),oe&&e.jsxs(Cn,{side:"top",className:"text-xs",children:[t("Minimum:")," ",Qe,Z.toFixed(2)]})]})}),e.jsx("span",{className:"text-xs min-w-[60px]",children:Xt(f.minRetailPrice,f.maxRetailPrice)}),e.jsx("button",{type:"button",className:"w-5 h-5 border rounded flex items-center justify-center text-gray-500 hover:bg-gray-100 text-xs",onClick:z=>{z.stopPropagation(),lr(f.size,f.maxRetailPrice+1)},children:"+"})]})})()}),e.jsx("div",{className:"text-center text-xs text-gray-600",children:Xt(f.minProductCost,f.maxProductCost)}),!ze&&e.jsx("div",{className:"text-center text-xs text-gray-600",children:it.toFixed(2)}),e.jsx("div",{className:"text-center text-xs text-gray-600",children:et>0?e.jsxs("span",{className:"text-[#15B67F]",children:["+",et.toFixed(2)]}):e.jsx("span",{className:"text-gray-400",children:"-"})}),e.jsx("div",{className:"text-center text-xs text-gray-600",children:De.toFixed(2)}),e.jsxs("div",{className:"text-end",children:[e.jsx("span",{className:"text-[#15B67F] font-medium text-xs",children:Xt(f.minProfit,f.maxProfit)}),e.jsx("span",{className:"ml-1",children:e.jsx(Xn,{className:"inline h-3 w-3 text-[#15B67F]"})})]})]}),f.isExpanded&&f.variants.map(j=>e.jsxs("div",{className:`grid ${Nt} gap-2 px-4 py-2 items-center ${j.isAvailable?"bg-gray-50/30":"bg-red-50/50"}`,children:[e.jsxs("div",{className:`ps-5 text-xs ${j.isAvailable?"text-gray-700":"text-red-600"}`,children:[j.colorName," - ",j.size," - ",Lr(j.printTechnology),!j.isAvailable&&e.jsx("div",{className:"text-[10px] text-red-500 mt-0.5",children:t("Not available from this provider")})]}),e.jsx("div",{className:"text-center",children:j.isAvailable?e.jsx("div",{className:"flex items-center justify-center gap-1",children:(()=>{const Z=Dt(j),oe=j.retailPrice<=Z;return e.jsxs(e.Fragment,{children:[e.jsx(jn,{children:e.jsxs(wn,{children:[e.jsx(kn,{asChild:!0,children:e.jsx("button",{type:"button",className:`w-5 h-5 border rounded flex items-center justify-center text-xs ${oe||k?"text-gray-300 cursor-not-allowed border-gray-200":"text-gray-500 hover:bg-gray-100"}`,onClick:()=>{if(!oe&&!k){const z=Math.max(Z,j.retailPrice-1);qt(j.colorName,j.size,z)}else oe&&ie.info(`${t("Minimum price is")} ${Qe}${Z.toFixed(2)} ${t(ze?"(cost + branding + order fee)":"(cost + branding + shipping + order fee)")}`)}
314,disabled:oe||k,children:"-"})}),oe&&e.jsxs(Cn,{side:"top",className:"text-xs",children:[t("Minimum price:")," ",Qe,Z.toFixed(2)]})]})}),e.jsx(Bp,{value:j.retailPrice,minimumPrice:Z,currencySymbol:Qe,onChange:z=>qt(j.colorName,j.size,z),disabled:k}),e.jsx("button",{type:"button",className:`w-5 h-5 border rounded flex items-center justify-center text-xs ${k?"text-gray-300 cursor-not-allowed border-gray-200":"text-gray-500 hover:bg-gray-100"}`,onClick:()=>{k||qt(j.colorName,j.size,j.retailPrice+1)},disabled:k,children:"+"})]})})()}):e.jsx("span",{className:"text-xs text-gray-400",children:"-"})}),e.jsx("div",{className:`text-center text-xs ${j.isAvailable?"text-gray-600":"text-gray-400"}`,children:j.isAvailable?j.productCost.toFixed(2):"-"}),!ze&&e.jsx("div",{className:`text-center text-xs ${j.isAvailable?"text-gray-600":"text-gray-400"}`,children:j.isAvailable?j.shippingCost.toFixed(2):"-"}),e.jsx("div",{className:`text-center text-xs ${j.isAvailable?"text-gray-600":"text-gray-400"}`,children:j.isAvailable&&et>0?e.jsxs("span",{className:"text-[#15B67F]",children:["+",et.toFixed(2)]}):e.jsx("span",{className:"text-gray-400",children:"-"})}),e.jsx("div",{className:`text-center text-xs ${j.isAvailable?"text-gray-600":"text-gray-400"}`,children:j.isAvailable?De.toFixed(2):"-"}),e.jsx("div",{className:"text-end",children:j.isAvailable?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[#15B67F] font-medium text-xs",children:j.profit.toFixed(2)}),e.jsxs("span",{className:"text-[10px] text-gray-500 ml-1",children:[j.profitMargin.toFixed(0),"%"]}),e.jsx("span",{className:"ml-1",children:e.jsx(Xn,{className:"inline h-3 w-3 text-[#15B67F]"})})]}):e.jsx("span",{className:"text-xs text-red-500",children:e.jsx(yn,{className:"inline h-3 w-3"})})})]},`${j.colorName}-${j.size}`))]},f.size))]})]}),ze&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-blue-50 border border-blue-200 rounded-xl",children:[e.jsx(yn,{className:"h-5 w-5 text-blue-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"font-medium text-blue-800 text-sm",children:t("Shipping calculated at checkout")}),e.jsxs("p",{className:"text-xs text-blue-700",children:[t("Shipping is charged separately based on your customer's location â it is")," ",e.jsx("strong",{children:t("not included")})," ",t("in the retail price above. Your customers will see the shipping cost at Shopify checkout.")]}),ae!=null&&le!=null&&e.jsxs("div",{className:"text-xs text-blue-700 bg-blue-100/50 rounded-lg p-2 space-y-0.5",children:[e.jsx("p",{className:"font-medium",children:t("Provider's shipping zones:")}),e.jsxs("p",{children:[t("First item:")," ",U," ",Number(ae).toFixed(2),ae!==le&&` â ${U} ${Number(le).toFixed(2)}`,ct!=null&&Pt!=null&&e.jsxs(e.Fragment,{children:[" ","· ",t("Additional:")," ",U," ",Number(ct).toFixed(2),ct!==Pt&&` â ${U} ${Number(Pt).toFixed(2)}`," ",t("each")]})]})]})]})]}),e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-emerald-50 border border-emerald-200 rounded-xl",children:[e.jsx(Vi,{className:"h-5 w-5 text-emerald-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"font-medium text-emerald-800 text-sm",children:t("Pricing tip")}),e.jsxs("p",{className:"text-xs text-emerald-700",children:[t("Your profit =")," ",e.jsx("strong",{children:t("Retail Price â (Product Cost + Branding + Order Fee)")}),"."," ",t("Shipping is paid by the customer at checkout and doesn't affect your margin.")]}),e.jsxs("p",{className:"text-xs text-emerald-700",children:[t("We recommend setting a profit margin of")," ",e.jsx("strong",{children:"20â50%"})," ",t('for competitive pricing. Use the "Set profit margin" button above to apply a percentage across all variants at once.')]})]})]})]}),e.jsxs("div",{className:"text-xs text-gray-500 flex items-center justify-between",children:[e.jsxs("span",{children:[t("Provider:")," ",e.jsx("strong",{children:c})," ⢠",t("Currency:")," ",lt]}),e.jsx("span",{children:t("Prices are based on provider's configuration")})]}),e.jsx(Nc,{open:Be,onOpenChange:f=>!f&&Kt(),children:e.jsxs(jc,{className:"max-w-xl rounded-[14px] sm:rou
314nded-[14px]",children:[e.jsxs(wc,{children:[e.jsx(kc,{children:t("You have unsaved price changes")}),e.jsx(Cc,{children:t("You edited variant prices but haven't saved yet. What do you want to do before continuing?")})]}),e.jsxs(Mc,{className:"flex-col-reverse gap-2 sm:flex-row sm:flex-wrap sm:justify-end sm:space-x-0",children:[e.jsx(Pc,{onClick:Kt,className:"w-full sm:w-auto",children:t("Stay on this page")}),e.jsxs(pe,{variant:"outline",onClick:Vt,className:"w-full border-amber-300 text-amber-900 hover:bg-amber-100 sm:w-auto",children:[e.jsx(hl,{className:"h-3.5 w-3.5 mr-1.5"}),t("Discard & continue")]}),e.jsxs(Ic,{onClick:Tt,disabled:re,className:"w-full bg-[#15B67F] text-white hover:bg-[#12a372] sm:w-auto",children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1.5"}),t(re?"Savingâ¦":"Save & continue")]})]})]})})]}):e.jsx("div",{className:"p-8 max-w-7xl mx-auto",children:e.jsx(Er,{className:"p-8",children:e.jsx("div",{className:"text-center text-gray-500",children:e.jsx("p",{children:t("No provider selected. Please go back and select a provider.")})})})})},uc=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),zp=t=>uc(t)&&typeof t.colorName=="string"&&typeof t.size=="string"&&typeof t.printTechnology=="string"&&typeof t.retailPrice=="number"&&typeof t.productCost=="number"&&(t.shippingCost===void 0||typeof t.shippingCost=="number")&&typeof t.profit=="number"&&typeof t.profitMargin=="number",_p=t=>uc(t)&&typeof t.colorName=="string"&&typeof t.size=="string"&&(t.price===void 0||typeof t.price=="number"),Gp=()=>{var Se,be;const t=Js(),{productSlug:s,draftId:n,providerId:a,providerName:c,selectedVariants:d,goToStep:u,listingDraft:y,variantPricing:p,isViewOnly:x}=mi(),[b,C]=r.useState([]),{data:L,loading:k}=Ht(Xl,{variables:{productSlug:s},skip:!s}),{config:K,loading:P}=ru(n),B=(K==null?void 0:K.layers)||[],R=r.useMemo(()=>{var G;return!((G=L==null?void 0:L.getProductBySlug)!=null&&G.assignedProviders)||!a?null:L.getProductBySlug.assignedProviders.find(ye=>ye.providerId===a)},[L,a]),A=((Se=R==null?void 0:R.priceRange)==null?void 0:Se.currency)??"",D=b.length>0,_=((be=R==null?void 0:R.pricingConfiguration)==null?void 0:be.shippingCost)||0,O=G=>({DTG:t("DTG (Direct-to-garment)"),DTF:t("DTF (Direct-to-film)"),SCREEN_PRINT:t("Screen Print"),EMBROIDERY:t("Embroidery"),SUBLIMATION:t("Sublimation")})[G]||G;r.useEffect(()=>{var S,w;const G=To(d),ye=new Set(G.map(({colorName:M,size:E})=>`${M}|${E}`));if(p&&Array.isArray(p)&&p.length>0){const M=p.filter(E=>zp(E)&&ye.has(`${E.colorName}|${E.size}`)).map(E=>({colorName:E.colorName,size:E.size,printTechnology:E.printTechnology,retailPrice:E.retailPrice,productCost:E.productCost,shippingCost:E.shippingCost??_,profit:E.profit,profitMargin:E.profitMargin}));C(M);return}if(!d||!((S=R==null?void 0:R.pricingConfiguration)!=null&&S.variantPricing))return;const we=R.pricingConfiguration.variantPricing.filter(_p),re=(w=R.printingTechnologies)==null?void 0:w[0],X=50,Q=[];G.forEach(({colorName:M,size:E})=>{const Me=we.find(Y=>Y.colorName===M&&Y.size===E);if(Me){const Y=Me.price||0,Ee=Y*(1+X/100),Be=Ee-Y-_,Ae=Ee>0?Be/Ee*100:0;Q.push({colorName:M,size:E,printTechnology:re,retailPrice:Ee,productCost:Y,shippingCost:_,profit:Be,profitMargin:Ae})}}),C(Q)},[p,d,R,_]);const I=r.useCallback(()=>{u&&u("prices")},[u]),ue=(y==null?void 0:y.tags)??[],me=r.useCallback(()=>{u&&u("details")},[u]);return k?e.jsxs("div",{className:"p-8 max-w-7xl mx-auto space-y-6",children:[e.jsx(Je,{className:"h-8 w-48"}),e.jsx(Je,{className:"h-4 w-96"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(Je,{className:"h-12 w-full"}),e.jsx(Je,{className:"h-64 w-full"})]})]}):e.jsxs("div",{className:"p-8 max-w-7xl mx-auto space-y-6 overflow-y-auto h-full",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h1",{className:"text-2xl font-semibold text-gray-900",children:t("Product summary")}),!x&&e.jsxs(pe,{variant:"link",onClick:I,className:"text-gray-600 hover:text-[#15B67F] p-0 flex items-center gap-1",children:[e.jsx(vo,{className:"w-4 h-4"}),t("Edit product options")]})]}),x&&e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-slate-100 border border-slate-200 rounded-xl",children:[e.jsx(Zn,{className:"h-5 w-5 text-slate-600 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-slate-800",children:t("View Only Mode")}),e.jsx("p",{className:"text-sm text-slate-600 mt-0.5",children:t("You are viewing this design in read-only mode. Publishing actions are disabled.")})]})]}),!D&&e.jsxs(Zu,{variant:"destructive",className:"mb-4",children:[e.jsx(yn,{className:"h-4 w-4"}),e.jsx(Ju,{children:t("Pricing Required")}),e.jsxs(Qu,{children:[t("Please configure pricing in the Prices step before publishing."),e.jsx(pe,{variant:"link",onClick:I,className:"text-destructive p-0 h-auto ml-1 underline",children:t("Go to Prices step")})]})]}),!P&&B.length>0&&e.jsxs(Er,{className:"overflow-hidden rounded-[14px] border-[#15B67F]/25 shadow-[0_10px_24px_rgba(0,0,0,0.06)]",children:[e.jsx("div",{className:"border-b border-[#15B67F]/15 bg-[#15B67F]/5 px-4 py-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-[14px] bg-[#15B67F]/10 text-[#0f8f65]",children:e.jsx(Ca,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-semibold text-gray-900",children:t("Personalization")}),e.jsx("p",{className:"text-xs text-gray-600",children:t("Buyers personalize before checkout · orders always held for review")})]})]}),e.jsxs(Xs,{className:"rounded-full bg-[#15B67F]/10 text-[#0f8f65] hover:bg-[#15B67F]/10",children:[B.length," ",t(B.length===1?"layer":"layers")]})]})}),e.jsx("div",{className:"divide-y divide-gray-100",children:B.map(G=>e.jsxs("div",{className:"grid grid-cols-12 items-center gap-3 px-4 py-3",children:[e.jsxs("div",{className:"col-span-5 min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium text-gray-900",children:G.label}),G.instructions&&e.jsx("div",{className:"mt-0.5 truncate text-xs text-gray-500",children:G.instructions})]}),e.jsx("div",{className:"col-span-3 text-xs font-medium uppercase text-gray-500",children:G.type}),e.jsxs("div",{className:"col-span-4 flex items-center justify-end gap-1.5 text-xs text-gray-500",children:[e.jsx(em,{className:"h-3.5 w-3.5"}),t("locked fill")]})]},G.fabricLayerId))})]}),e.jsxs(Er,{className:"overflow-hidden rounded-[14px] border-gray-200 shadow-[0_10px_24px_rgba(0,0,0,0.06)]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-gray-100 px-4 py-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-[14px] bg-[#15B67F]/10 text-[#0f8f65]",children:e.jsx(tc,{
314className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-semibold text-gray-900",children:t("Tags")}),e.jsx("p",{className:"text-xs text-gray-600",children:t("Published with your product listing")})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Xs,{className:"rounded-full bg-[#15B67F]/10 text-[#0f8f65] hover:bg-[#15B67F]/10",children:[ue.length," ",t(ue.length===1?"tag":"tags")]}),!x&&e.jsxs(pe,{variant:"link",onClick:me,className:"flex h-auto items-center gap-1 p-0 text-gray-600 hover:text-[#15B67F]",children:[e.jsx(vo,{className:"h-4 w-4"}),t("Edit")]})]})]}),e.jsx("div",{className:"px-4 py-3",children:ue.length>0?e.jsx("ul",{className:"flex flex-wrap gap-1.5",children:ue.map(G=>e.jsx("li",{className:"inline-flex h-7 items-center rounded-full border border-[#15B67F]/30 bg-[#15B67F]/10 px-2.5 text-xs font-medium text-gray-800",children:G},G.toLowerCase()))}):e.jsx("p",{className:"text-sm text-gray-500",children:t("No tags selected.")})})]}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-medium text-gray-900 mb-4",children:t("Variants to publish")}),e.jsxs(Er,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-gray-50 border-b",children:e.jsxs("div",{className:"grid grid-cols-12 gap-2 px-4 py-3 text-xs font-medium text-gray-600",children:[e.jsxs("div",{className:"col-span-4",children:[e.jsx("div",{children:t("Variant name")}
314),e.jsx("div",{className:"font-normal text-[10px] text-gray-400",children:t("shown in PrintaRex Dashboard")})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("div",{children:t("Color")}),e.jsx("div",{className:"font-normal text-[10px] text-gray-400",children:t("visible as product option")})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("div",{children:t("Size")}),e.jsx("div",{className:"font-normal text-[10px] text-gray-400",children:t("visible as product option")})]}),e.jsx("div",{className:"col-span-2 text-right",children:e.jsx("div",{children:t("Retail price")})}),e.jsx("div",{className:"col-span-2 text-right",children:e.jsx("div",{children:t("Estimated profit")})})]})}),e.jsx("div",{className:"divide-y",children:b.length===0?e.jsx("div",{className:"px-4 py-8 text-center text-gray-500",children:t("No variants selected. Please go back and select product variants.")}):b.map(G=>e.jsxs("div",{className:"grid grid-cols-12 gap-2 px-4 py-4 hover:bg-gray-50 items-center",children:[e.jsx("div",{className:"col-span-4",children:e.jsxs("div",{className:"text-sm text-gray-900",children:[G.colorName," - ",G.size," - ",O(G.printTechnology)]})}),e.jsx("div",{className:"col-span-2",children:e.jsx("div",{className:"text-sm text-gray-700",children:G.colorName})}),e.jsx("div",{className:"col-span-2",children:e.jsx("div",{className:"text-sm text-gray-700",children:G.size})}),e.jsx("div",{className:"col-span-2 text-right",children:e.jsx("div",{className:"text-sm text-gray-900",children:G.retailPrice>0?`${G.retailPrice.toFixed(2)} ${A}`:e.jsx("span",{className:"text-gray-400",children:"-"})})}),e.jsx("div",{className:"col-span-2 text-right",children:e.jsx("div",{className:`text-sm ${G.profit>0?"text-[#15B67F]":"text-gray-400"}`,children:G.profit>0?`${G.profit.toFixed(2)} ${A}`:"-"})})]},`${G.colorName}-${G.size}`))})]})]}),e.jsxs("div",{className:"text-xs text-gray-500 flex items-center justify-between",children:[e.jsxs("span",{children:[t("Provider:")," ",e.jsx("strong",{children:c||t("Not selected")})," ⢠",t("Currency:")," ",A]}),e.jsxs("span",{children:[t("Total variants:")," ",e.jsx("strong",{children:b.length})]})]})]})},bo=[{id:"designv1",label:"Design",icon:vo},{id:"mockups",label:"Mockups",icon:Ir},{id:"packing",label:"Packing",icon:wa},{id:"details",label:"Details",icon:rc},{id:"prices",label:"Prices",icon:Sc},{id:"review",label:"Review",icon:tm}],Ml=(t,s,n)=>t==="completed"?s==="ar"?` (${n("Completed")})`:" (completed)":s==="ar"?` (${n("Current")})`:" (current)",mc=({currentStep:t,completedSteps:s=[],onStepClick:n,disabled:a=!1})=>{const c=Js(),{locale:d}=Dl(),u=d==="ar"?Jl:Io,y=bo.findIndex(({id:x})=>x===t),p=Dd(t);return e.jsx("nav",{ref:p,className:"flex min-w-0 items-center gap-0.5 sm:gap-1 max-md:overflow-x-auto max-md:scrollbar-hide max-md:p-1","aria-label":d==="ar"?`${c("Step")} ${c("Current")}`:"Wizard progress",children:bo.map((x,b)=>{const C=x.id===t,L=s.includes(x.id),k=b<y,K=b===bo.length-1,P=x.icon,B=c(x.label);let R="";return L?R=Ml("completed",d,c):C&&(R=Ml("current",d,c)),e.jsxs(Ji.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>!a&&n(x.id),disabled:a,className:Sr("group relative flex shrink-0 flex-col items-center transition-all duration-200","focus:outline-none focus-visible:ring-2 focus-visible:ring-[#15B67F] focus-visible:ring-offset-2 rounded-lg","px-1.5 sm:px-2 md:px-3 py-1"),"aria-current":C?"step":void 0,"aria-label":`${B}${R}`,children:[e.jsxs("div",{className:Sr("relative flex items-center justify-center w-8 h-8 sm:w-9 sm:h-9 rounded-xl transition-all duration-200",C&&"bg-[#15B67F] text-white shadow-md shadow-[#15B67F]/25",L&&!C&&"bg-[#15B67F]/10 text-[#15B67F]",k&&!L&&!C&&"bg-gray-100 text-gray-400",!C&&!L&&!k&&"bg-gray-100 text-gray-400","group-hover:scale-105",C&&"group-hover:shadow-lg group-hover:shadow-[#15B67F]/30",!C&&"group-hover:bg-[#15B67F]/10 group-hover:text-[#15B67F]"),children:[L&&!C?e.jsx(Xn,{className:"w-4 h-4 sm:w-5 sm:h-5 stroke-[2.5]"}):e.jsx(P,{className:"w-4 h-4 sm:w-5 sm:h-5"}),C&&e.jsx("span",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 w-1 h-1 bg-[#15B67F] rounded-full"})]}),e.jsx("span",{className:Sr("hidden md:block mt-1 text-[10px] sm:text-xs font-medium transition-colors duration-200 whitespace-nowrap",C&&"text-[#15B6
3147F]",L&&!C&&"text-gray-600",!C&&!L&&"text-gray-400","group-hover:text-[#15B67F]"),children:B})]}),!K&&e.jsx("div",{className:"flex shrink-0 items-center justify-center",children:e.jsx(u,{className:Sr("w-3.5 h-3.5 sm:w-4 sm:h-4 transition-colors duration-200 flex-shrink-0",L||k?"text-[#15B67F]/40":"text-gray-300")})})]},x.id)})})},Vp=({providerName:t,onChooseProvider:s})=>{const n=Js(),a=t?`${t} ${n("has withdrawn its offer for this product, so its pricing and print areas are no longer available.")}`:n("The provider for this design is no longer available for this product.");return e.jsxs("div",{role:"alert",className:"mx-4 mt-4 flex flex-col gap-4 rounded-[14px] border border-amber-200 bg-amber-50 px-4 py-4 text-amber-900 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Fr,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-amber-600","aria-hidden":"true"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-medium",children:n("Provider no longer available")}),e.jsxs("p",{className:"text-amber-800",children:[a," ",n("Your design is saved. Choose another provider to continue to mockups and pricing.")]})]})]}),e.jsx(pe,{type:"button",size:"sm",onClick:s,className:"bg-[#15B67F] text-white hover:bg-[#12a372] md:flex-shrink-0",children:n("Choose another provider")})]})},zi=(t,s)=>s!=null&&s.reassignProvider&&s.providerId&&s.providerName&&s.configId?{providerId:s.providerId,providerName:s.providerName,configId:s.configId}:t.providerId&&t.providerName&&t.providerConfigId?{providerId:t.providerId,providerName:t.providerName,configId:t.providerConfigId}:null,Pl=t=>t.map(s=>({brandingProductType:s.brandingProductType,productId:s.productId??void 0,enabled:s.enabled??!1,designId:s.designId??null,designName:s.designName??void 0,designThumbnail:s.designThumbnail??void 0,unitPrice:s.unitPrice??0,quantity:s.quantity??1,providerId:s.providerId??void 0,providerCost:s.providerCost??void 0,providerConfigId:s.providerConfigId??void 0,basePricePerUnit:s.basePricePerUnit??void 0,currency:s.currency??void 0,selectedOptions:Object.fromEntries((s.selectedOptions??[]).map(n=>[n.optionCategory,{value:n.optionValue,additionalPrice:n.perUnitSurcharge}]))})),Kp=t=>t.map(s=>({brandingProductType:s.brandingProductType,productId:s.productId,enabled:s.enabled,designId:s.designId,designName:s.designName,designThumbnail:s.designThumbnail,unitPrice:s.unitPrice,quantity:s.quantity,providerId:s.providerId,providerCost:s.providerCost,providerConfigId:s.providerConfigId,basePricePerUnit:s.basePricePerUnit,currency:s.currency,selectedOptions:Object.entries(s.selectedOptions??{}).map(([n,a])=>({optionCategory:n,optionValue:a.value,perUnitSurcharge:a.additionalPrice}))})),Yp=t=>Object.entries(t??{}).map(([s,n])=>({optionCategory:s,optionValue:n.value,perUnitSurcharge:n.additionalPrice})),Hp=t=>{const s=t.filter(n=>n.enabled);if(s.length!==0)return s.map(n=>({brandingProductType:n.brandingProductType,productId:n.productId,designId:n.designId||void 0,designThumbnailUrl:n.designThumbnail||void 0,unitPrice:n.unitPrice,providerId:n.providerId,providerCost:n.providerCost,providerConfigId:n.providerConfigId,baseProviderCostPerUnit:n.providerCost??n.basePricePerUnit,optionInclusiveProviderPricePerUnit:n.unitPrice,selectedOptions:Yp(n.selectedOptions)}))},Il=t=>(t==null?void 0:t.trim().toUpperCase())??"",Wp=t=>{if(!t.attachCareInstructions)return!0;const s=t.careInstructions;return!(!s||typeof s.general!="string"||typeof s.wash!="string"||typeof s.dry!="string"||s.iron!==void 0&&typeof s.iron!="string"||s.bleach!==void 0&&typeof s.bleach!="string")},qp=t=>{if(t===void 0)return!0;if(!Array.isArray(t)||t.length>ka)return!1;const s=new Set;return t.every(n=>{if(typeof n!="string")return!1;const a=n.trim();return a.length>0&&a.length<=Gi&&s.add(a.toLowerCase())})},Xp=t=>{var s,n,a,c;if(!t||!((n=(s=t.productDetails)==null?void 0:s.title)!=null&&n.trim())||typeof t.productDetails.description!="string"||!qp(t.tags)||typeof t.attachSizeTable!="boolean"||typeof t.attachCareInstructions!="boolean"||!Array.isArray(t.sizeGuideImageUrls)||t.sizeGuideImageUrls.some(d=>typeof d!="string"||!/^https?:\/\//i.test(d)))return!1;if(t.attachSizeTable){const d=(c=(a=t.sizeTable)==null?void 0:a.metric)==null?void 0:c.data;if(!d||typeof d!="object"||Array.isArray(d)||Object.values(d).some(y=>!y||typeof y!="object"||Array.isArray(y)||Object.values(y).some(p=>p!==null&&typeof p!="string"&&typeof p!="number")))return!1}return Wp(t)},Zp=(t,s)=>{const n=new Set(s.map(a=>`${Il(a.color)}|${Il(a.size)}`));return t.size>0&&n.size===t.size&&s.length===n.size&&[...n].every(a=>t.has(a))&&s.every(a=>typeof a.price=="number"&&Number.isFinite(a.price)&&a.price>0)},Jp=(t,s,n)=>Xp(t)&&t.productDetails.title===s&&Uo(t)===n,_i=async(t,s,n,a)=>{var c;return await((c=t.get(s))==null?void 0:c(a)),n()},li=t=>typeof t=="string"&&t.startsWith("custom:"),Qp=(t,s,n)=>!li(s)||n==null?t:t.filter(a=>a!==n),eh=(t,s,n)=>!li(s)||n==null?t:t.filter(a=>a!==`template:${n}`),ur=t=>(t||"").trim().toUpperCase(),Sl=(t,s)=>t===s||t!==void 0&&s!==void 0&&t.length===s.length&&t.every((n,a)=>n===s[a]),Ia=t=>!!t&&typeof t=="object"&&!Array.isArray(t),th=(t,s)=>{if(!s||!Array.isArray(t))return null;const n=ur(s);return t.find(a=>
314typeof a=="string"&&ur(a)===n)||null},di=t=>{if(!Ia(t))return null;const s=t.colorName??t.color??t.name;return typeof s=="string"?s:null},Co=t=>{if(!Ia(t))return null;const s=t.size??t.sizeName;return typeof s=="string"?s:null},Mo=(t,s)=>s?Ia(t)&&(th(t.selectedColors,s)||(Array.isArray(t.variants)?di(t.variants.find(n=>ur(di(n))===ur(s))):null))||s:null,rh=t=>{try{const s=JSON.parse(t);return Ia(s)?s:null}catch(s){return console.error("[CustomizationForYourStores] Failed to parse canvas JSON before saving order copy:",s),null}},Al=(t,s,n)=>{if(!s||!Ia(t))return t;const a=Mo(t,s);if(!a)return t;const c=(n==null?void 0:n.trim())||null,d=Ia(t.selectedSizes)?t.selectedSizes:{},u=Object.entries(d).find(([b])=>ur(b)===ur(a)),y=Array.isArray(u==null?void 0:u[1])?u[1].filter(b=>typeof b=="string"):[],p=c?[c]:y,x=Array.isArray(t.variants)?t.variants.filter(b=>{const C=di(b);if(C&&ur(C)!==ur(a))return!1;const L=Co(b);return!(c&&L&&ur(L)!==ur(c))}):t.variants;return{...t,selectedColors:[a],selectedSizes:{[a]:p},variants:x}},sh=(t,s)=>!!(t&&s&&t.providerId===s.providerId&&t.providerName===s.providerName&&t.configId===s.configId),nh=new Set(["Could not verify inner-neck printing. Please retry Continue to Mockups.","This provider cannot print your saved inner-neck design. Choose a provider offering inner-neck printing, or explicitly remove that saved design before continuing."]),ah=t=>t instanceof Error&&nh.has(t.message),Ys=["designv1","mockups","packing","details","prices","review"],ih={designv1:"Design",mockups:"Mockups",packing:"Packing",details:"Details",prices:"Prices",review:"Review"},oh=(t,s)=>({initialProviderId:(t==null?void 0:t.providerId)||s.get("providerId"),initialProviderName:(t==null?void 0:t.providerName)||s.get("providerName"),initialProviderCountry:(t==null?void 0:t.providerCountry)||s.get("providerCountry"),initialPrintingTechnology:(t==null?void 0:t.printingTechnology)||s.get("printingTechnology")}),lh=(t,s,n,a)=>({isEditMode:(t==null?void 0:t.editMode)===!0||(s==null?void 0:s.editMode)===!0,editDesignId:t!=null&&t.editMode&&n==="edit"?a:null,publishedProductId:(t==null?void 0:t.publishedProductId)||(s==null?void 0:s.publishedProductId)||null,editStoreConnectionId:(t==null?void 0:t.storeConnectionId)||(s==null?void 0:s.storeConnectionId)||null,editStoreName:(t==null?void 0:t.storeName)||(s==null?void 0:s.storeName)||null,editStoreShopDomain:(t==null?void 0:t.storeShopDomain)||(s==null?void 0:s.storeShopDomain)||null}),ch=(t,s)=>{const n=(t==null?void 0:t.reviewMode)===!0||(s==null?void 0:s.reviewMode)===!0;return{isPersonalizationReviewMode:n,personalizationReviewStoreOrderId:(t==null?void 0:t.storeOrderId)||(s==null?void 0:s.storeOrderId),personalizationReviewLineItemId:(t==null?void 0:t.externalLineItemId)||(s==null?void 0:s.externalLineItemId),personalizationReviewVariantTitle:(t==null?void 0:t.reviewVariantTitle)||(s==null?void 0:s.reviewVariantTitle)||null,personalizationReviewSelectedColor:(t==null?void 0:t.selectedColor)||(s==null?void 0:s.selectedColor)||null,personalizationReviewSelectedSize:(t==null?void 0:t.selectedSize)||(s==null?void 0:s.selectedSize)||null,personalizationReviewReturnTo:n?(t==null?void 0:t.returnTo)||(s==null?void 0:s.returnTo)||"/dashboard/orders?tab=pendingApproval":"/dashboard/catalog"}},dh=(t,s)=>({initialSelectedColor:t.personalizationReviewSelectedColor||(s==null?void 0:s.selectedColor)||null,initialSelectedSize:t.personalizationReviewSelectedSize||(s==null?void 0:s.selectedSize)||null}),uh=(t,s,n,a,c)=>t?null:s||n||a||(globalThis.window===void 0?null:sessionStorage.getItem(c)),Tl=(t,s,n)=>{if(t)return n("Back to order");const a=Ys[Ys.indexOf(s)+1];return n(`Continue to ${a&&ih[a]||"Next"}`)},mh=t=>t.isPersonalizationReviewMode?{storeOrderId:t.personalizationReviewStoreOrderId,externalLineItemId:t.personalizationReviewLineItemId,selectedColor:t.personalizationReviewSelectedColor,selectedSize:t.personalizationReviewSelectedSize,variantTitle:t.personalizationReviewVariantTitle,returnTo:t.personalizationReviewReturnTo}:void 0,ph=(t,s,n,a,c)=>t||s?null:n||(a?c("Could not load your design draft. Please try again."):null),hh=({visible:t,lineItemId:s,wizardCopy:n})=>t?e.jsx("div",{className:"flex-shrink-0 border-b border-emerald-200 bg-emerald-50 px-4 py-2",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-emerald-900",children:n("Personalized order review")}),e.jsx("span",{className:"ml-2 text-emerald-800",children:n("Changes apply only to this order copy.")})]}),s&&e.jsxs("span",{className:"rounded-full bg-white px-2.5 py-1 text-xs font-medium text-emerald-800 shadow-sm",children:[n("Line")," ",s]})]})}):null,xh=({message:t,onRetry:s,wizardCopy:n})=>e.jsx("div",{className:"flex flex-1 items-center justify-center px-6",children:e.jsxs("div",{className:"max-w-md rounded-[14px] border border-red-200 bg-red-50 p-8 text-center shadow-sm",children:[e.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-red-100",children:e.jsx(yn,{className:"h-6 w-6 text-red-700","aria-hidden":"true"})}),e.jsx("h2",{className:"mb-2 text-lg font-semibold text-red-950",children:n("Design workspace unavailable")}),e.jsx("p",{className:"mb-5 text-sm text-red-800",children:t}),e.jsx(pe,{type:"button",variant:"outline",onClick:()=>s(),children:n("Try again")})]})}
314),fh=({isPersonalizationReviewMode:t,step:s,setVariantApplyNotice:n,setMockupProgress:a,setIsMockupPreparationPending:c,interactionLocked:d})=>t?e.jsx(qo,{}):e.jsxs(e.Fragment,{children:[s==="designv1"&&e.jsx(qo,{onVariantApplyNotice:n}),s==="mockups"&&e.jsx(dp,{interactionLocked:d,onPreparationStateChange:c,onProgressChange:a}),s==="packing"&&e.jsx(bp,{}),s==="details"&&e.jsx(Lp,{}),s==="prices"&&e.jsx($p,{}),s==="review"&&e.jsx(Gp,{})]}),gh=({draftLoadError:t,onRetryInitialization:s,wizardCopy:n,isPersonalizationReviewMode:a,step:c,setVariantApplyNotice:d,setIsMockupPreparationPending:u,setMockupProgress:y,isBeforeLeaveRunning:p,isStepTransitionRunning:x,isSaving:b})=>t?e.jsx(xh,{message:t,onRetry:()=>void s(),wizardCopy:n}):e.jsx("div",{className:"flex-1 min-h-0",children:e.jsx(fh,{isPersonalizationReviewMode:a,step:c,setVariantApplyNotice:d,setIsMockupPreparationPending:u,setMockupProgress:y,interactionLocked:p||x||b})}),bh=({navigateToMyDesigns:t,isStepTransitionRunning:s,isProviderAvailable:n,step:a,completedSteps:c,goToStep:d,isBeforeLeaveRunning:u,switchToEditMode:y,wizardCopy:p})=>e.jsx("header",{className:"bg-gradient-to-r from-slate-800 to-slate-900 border-b border-slate-700 flex-shrink-0 h-14",children:e.jsxs("div",{className:"h-full px-2 md:px-4 flex items-center justify-between",children:[e.jsxs(pe,{variant:"ghost",size:"sm",onClick:t,disabled:s,className:"text-white hover:text-white hover:bg-white/10 h-8 px-2 md:px-3",children:[e.jsx(Ao,{className:"w-4 h-4 md:mr-1"}),e.jsx("span",{className:"hidden md:inline",children:p("Back to Designs")})]}),e.jsx(mc,{currentStep:a,completedSteps:c,onStepClick:x=>void d(x),disabled:u||s}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-3",children:[e.jsx($l,{dismissLabel:p("Dismiss")}),e.jsxs("div",{className:"hidden md:flex items-center gap-2 px-3 py-1 bg-slate-700 rounded-full",children:[e.jsx(Zn,{className:"w-4 h-4 text-slate-300"}),e.jsx("span",{className:"text-xs text-slate-300 font-medium",children:p("View Only")})]}),n&&e.jsxs(pe,{size:"sm",onClick:y,disabled:s,className:"bg-[#15B67F] hover:bg-[#12a372] text-white h-8 px-3 md:px-4 text-xs md:text-sm",children:[e.jsx(rm,{className:"w-3.5 h-3.5 md:mr-1.5"}),e.jsx("span",{className:"hidden md:inline",children:p("Edit Design")})]})]})]})}),yh=({providerName:t,wizardCopy:s})=>{const n=t?`${t} ${s("has withdrawn its offer for this product, so its pricing and print areas are no longer available.")}`:s("The provider for this design is no longer available for this product.");return e.jsxs("div",{role:"alert",className:"mx-4 mt-4 flex items-start gap-3 rounded-[14px] border border-amber-200 bg-amber-50 px-4 py-4 text-amber-900",children:[e.jsx(Fr,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-amber-600","aria-hidden":"true"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-medium",children:s("Provider no longer available")}),e.jsxs("p",{className:"text-amber-800",children:[n," ",s("Your design is saved. Choose another provider to continue to mockups and pricing.")," ","(",s("View Only Mode"),")."]})]})]})},vh=({isEditMode:t,isProviderUnavailable:s,isSavingTemplate:n,setShowSaveTemplateModal:a,openStoreModalAfterPreflight:c,isSaving:d,isBeforeLeaveRunning:u,isStepTransitionRunning:y,canPublish:p,wizardCopy:x})=>e.jsxs(e.Fragment,{children:[!t&&e.jsxs(pe,{variant:"outline",size:"sm",onClick:()=>a(!0),disabled:n,"aria-label":x("Save as template"),className:"h-8 px-2 md:px-4 text-xs md:text-sm border-gray-300 text-gray-700 hover:bg-gray-100 transition-colors",children:[e.jsx("span",{className:"hidden md:inline",children:x("Save as template")}),e.jsx(Pa,{className:"w-4 h-4 md:hidden"})]}),t?e.jsxs(pe,{size:"sm",onClick:()=>void c("update"),"aria-label":x("Update in Stores"),disabled:d||u||y||s,className:"bg-gray-900 hover:bg-gray-800 text-white h-8 px-2 md:px-4 text-xs md:text-sm disabled:opacity-50 disabled:cursor-not-allowed",title:s?x("You can continue once a provider is selected."):p?void 0:x("Please configure pricing before updating"),children:[e.jsx(xl,{className:"w-3.5 h-3.5 md:mr-1.5"}),e.jsx("span",{className:"hidden md:inline",children:x("Update in Stores")})]}):e.jsxs(pe,{size:"sm",onClick:()=>void c("publish"),"aria-label":x("Publish to Store"),disabled:d||u||y||s,className:"bg-gray-900 hover:bg-gray-800 text-white h-8 px-2 md:px-4 text-xs md:text-sm disabled:opacity-50 disabled:cursor-not-allowed",title:s?x("You can continue once a provider is selected."):p?void 0:x("Please configure pricing in the Prices step before publishing"),children:[e.jsx(xl,{className:"w-3.5 h-3.5 md:mr-1.5"}),e.jsx("span",{className:"hidden md:inline",children:x("Publish to Store")})]})]}),Nh=({handleSaveDraft:t,draftId:s,isSaving:n,wizardCopy:a})=>{let c;return s?n?c=a("Saving..."):c=a("Save order copy"):c=a("Loading..."),e.jsxs(pe,{variant:"outline",size:"sm",onClick:t,disabled:!s||n,"data-tour":"save-button",className:"h-8 px-2 md:px-4 text-xs md:text-sm border-[#15B67F] text-[#15B6
3147F] hover:bg-[#15B67F] hover:text-white transition-colors",children:[e.jsx(Pa,{className:"w-3.5 h-3.5 md:mr-1.5"}),e.jsx("span",{className:"hidden md:inline",children:c})]})},jh=({handleSaveDraft:t,handleOpenDesignPreview:s,draftId:n,isSaving:a,isPreparingDesignPreview:c,isStepTransitionRunning:d,step:u,isMockupPreparationPending:y,wizardCopy:p})=>{let x;return n?a?x=p("Saving..."):x=p("Save"):x=p("Creating..."),e.jsxs(e.Fragment,{children:[e.jsxs(pe,{variant:"outline",size:"sm",onClick:t,disabled:!n||a||d||u==="mockups"&&y,"aria-label":x,"data-tour":"save-button",className:"h-8 shrink-0 px-2 md:px-4 text-xs md:text-sm border-[#15B67F] text-[#15B67F] hover:bg-[#15B67F] hover:text-white transition-colors",children:[e.jsx(Pa,{className:"w-3.5 h-3.5 md:mr-1.5"}),e.jsx("span",{className:"hidden md:inline",children:x})]}),u==="designv1"&&e.jsx(pe,{variant:"outline",size:"sm",onClick:s,disabled:!n||a||c||d,"aria-label":p(c?"Preparing...":"Preview"),"data-tour":"preview-button",className:"h-8 shrink-0 px-2 md:px-4 text-xs md:text-sm border-slate-300 text-slate-700 hover:border-[#15B67F] hover:bg-[#15B67F]/10 hover:text-[#0f8f65] transition-colors",children:c?e.jsxs(e.Fragment,{children:[e.jsx(mr,{className:"w-3.5 h-3.5 animate-spin md:mr-1.5"}),e.jsx("span",{className:"hidden md:inline",children:p("Preparing...")})]}):e.jsxs(e.Fragment,{children:[e.jsx(Zn,{className:"w-3.5 h-3.5 md:mr-1.5"}),e.jsx("span",{className:"hidden md:inline",children:p("Preview")})]})})]})},wh=({continueLabelFull:t,goToNextStep:s,isBeforeLeaveRunning:n,isProviderUnavailable:a,isStepTransitionRunning:c,isSaving:d,step:u,isMockupPreparationPending:y,wizardCopy:p})=>{let x;return u==="mockups"&&y?x=e.jsxs(e.Fragment,{children:[e.jsx(mr,{className:"w-3.5 h-3.5 animate-spin md:mr-1.5"}),e.jsx("span",{className:"hidden md:inline",children:p("Preparing mockups...")})]}):n||c||u==="mockups"&&d?x=e.jsxs(e.Fragment,{children:[e.jsx(mr,{className:"w-3.5 h-3.5 animate-spin md:mr-1.5"}),e.jsx("span",{className:"hidden md:inline",children:p(u==="mockups"?"Saving mockups...":"Please wait...")})]}):x=e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"hidden md:inline",children:t}),e.jsx("span",{className:"md:hidden",children:p("Next")})]}),e.jsx(pe,{size:"sm",onClick:()=>void s(),disabled:n||c||a||u==="mockups"&&(d||y),title:a?p("You can continue once a provider is selected."):void 0,className:"bg-[#15B67F] hover:bg-[#12a372] text-white h-8 shrink-0 px-2 md:px-4 text-xs md:text-sm disabled:opacity-60 disabled:cursor-not-allowed",children:x})},kh=({step:t,mockupProgress:s,isMockupPreparationPending:n,isBeforeLeaveRunning:a,isProviderUnavailable:c,isStepTransitionRunning:d,isSaving:u,isSavingTemplate:y,lastSaved:p,isPersonalizationReviewMode:x,variantApplyNotice:b,clearVariantApplyNotice:C,handleSaveDraft:L,draftId:k,isEditMode:K,setShowSaveTemplateModal:P,openStoreModalAfterPreflight:B,canPublish:R,handleOpenDesignPreview:A,isPreparingDesignPreview:D,goToNextStep:_,nextStepLabel:O,wizardCopy:I,shareActions:ue})=>{let me=null;u||y?me=e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Pa,{className:"w-3 h-3 animate-spin"}),I("Saving...")]}):p&&(me=I(x?"Order copy saved":"Progress saved in Drafts"));let Se;return x?Se=e.jsx(Nh,{handleSaveDraft:L,draftId:k,isSaving:u,wizardCopy:I}):t==="review"?Se=e.jsx(vh,{isEditMode:K,isProviderUnavailable:c,isSavingTemplate:y,setShowSaveTemplateModal:P,openStoreModalAfterPreflight:B,isSaving:u,isBeforeLeaveRunning:a,isStepTransitionRunning:d,canPublish:R,wizardCopy:I}):Se=e.jsxs(e.Fragment,{children:[e.jsx(jh,{handleSaveDraft:L,handleOpenDesignPreview:A,draftId:k,isSaving:u,isPreparingDesignPreview:D,isStepTransitionRunning:d,step:t,isMockupPreparationPending:n,wizardCopy:I}),t==="mockups"&&ue,e.jsx(wh,{continueLabelFull:O,goToNextStep:_,isProviderUnavailable:c,isBeforeLeaveRunning:a,isStepTransitionRunning:d,isSaving:u,step:t,isMockupPreparationPending:n,wizardCopy:I})]}),e.jsxs("div",{className:"flex min-w-0 items-center gap-1 md:gap-3",children:[e.jsx("div",{id:"customer-studio-header-actions",className:"hidden md:flex items-center gap-2"}),t==="mockups"&&s&&(n||a||d||u)&&e.jsx(Wd,{progress:s,preparingLabel:I("Preparing mockups"),savingLabel:I("Saving mockups...")}),e.jsx("span",{className:"text-xs text-gray-500 hidden md:inline shrink-0",children:me}
314),e.jsx($l,{dismissLabel:I("Dismiss")}),t==="designv1"&&!x&&e.jsx(fd,{notice:b,dismissLabel:I("Dismiss"),onDismiss:C}),e.jsx(gd,{children:Se})]})},Ch=({returnToCatalog:t,isStepTransitionRunning:s,isProviderUnavailable:n,isPersonalizationReviewMode:a,wizardCopy:c,step:d,completedSteps:u,goToStep:y,isBeforeLeaveRunning:p,isMockupPreparationPending:x,mockupProgress:b,isSaving:C,isSavingTemplate:L,lastSaved:k,variantApplyNotice:K,clearVariantApplyNotice:P,handleSaveDraft:B,draftId:R,isEditMode:A,setShowSaveTemplateModal:D,openStoreModalAfterPreflight:_,canPublish:O,handleOpenDesignPreview:I,isPreparingDesignPreview:ue,goToNextStep:me,nextStepLabel:Se,shareActions:be})=>e.jsx("header",{className:"bg-white border-b border-gray-200 flex-shrink-0 h-14",children:e.jsxs("div",{className:"h-full px-2 md:px-4 flex items-center justify-between",children:[e.jsxs(pe,{variant:"ghost",size:"sm",onClick:t,disabled:s,className:"text-sm text-gray-600 hover:text-[#15B67F] h-8 px-2 md:px-3",children:[e.jsx(Ao,{className:"w-4 h-4 md:mr-1"}),e.jsx("span",{className:"hidden md:inline",children:c(a?"Back to order":"Return to catalog")})]}),a?e.jsxs("div",{className:"hidden md:flex items-center gap-2 rounded-full border border-emerald-200 bg-emerald-50 px-3 py-1 text-xs font-semibold text-emerald-800",children:[e.jsx(Ca,{className:"h-3.5 w-3.5"}),c("Order copy review")]}):e.jsx(mc,{currentStep:d,completedSteps:u,onStepClick:G=>void y(G),disabled:p||s||n||d==="mockups"&&x}),e.jsx(kh,{step:d,mockupProgress:b,isMockupPreparationPending:x,isBeforeLeaveRunning:p,isProviderUnavailable:n,isStepTransitionRunning:s,isSaving:C,isSavingTemplate:L,lastSaved:k,isPersonalizationReviewMode:a,variantApplyNotice:K,clearVariantApplyNotice:P,handleSaveDraft:B,draftId:R,isEditMode:A,setShowSaveTemplateModal:D,openStoreModalAfterPreflight:_,canPublish:O,handleOpenDesignPreview:I,isPreparingDesignPreview:ue,goToNextStep:me,nextStepLabel:Se,wizardCopy:c,shareActions:be})]})}),Mh=({showSaveTemplateModal:t,setShowSaveTemplateModal:s,templateName:n,setTemplateName:a,isSavingTemplate:c,handleSaveAsTemplate:d,wizardCopy:u})=>e.jsx(Xi,{open:t,onOpenChange:s,children:e.jsx(Zi,{className:"sm:max-w-md p-0 overflow-hidden rounded-[28px] border-0 bg-transparent shadow-none",children:e.jsxs("div",{className:"bg-white rounded-[28px] shadow-[0_10px_24px_rgba(0,0,0,0.08)] overflow-hidden",children:[e.jsxs("div",{className:"relative h-24 bg-gradient-to-br from-emerald-50 via-teal-50 to-green-50 overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-30",style:{backgroundImage:`url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%2315B67F' fill-opacity='0.15'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`}}),e.jsx("div",{className:"absolute bottom-0 left-1/2 -translate-x-1/2 translate-y-1/2",children:e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-gradient-to-br from-[#15B67F] to-[#12A072] shadow-lg flex items-center justify-center",children:e.jsx("svg",{className:"w-7 h-7 text-white",fill:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{d:"M9.153 5.408C10.42 3.136 11.053 2 12 2c.947 0 1.58 1.136 2.847 3.408l.328.588c.36.646.54.969.82 1.182.28.213.63.292 1.33.45l.636.144c2.46.557 3.689.835 3.982 1.776.292.94-.546 1.921-2.223 3.882l-.434.507c-.476.557-.715.836-.822 1.18-.107.345-.071.717.001 1.46l.066.677c.253 2.617.38 3.925-.386 4.506-.766.582-1.918.051-4.22-1.009l-.597-.274c-.654-.302-.981-.452-1.328-.452-.347 0-.674.15-1.328.452l-.596.274c-2.303 1.06-3.455 1.59-4.22 1.01-.767-.582-.64-1.89-.387-4.507l.066-.676c.072-.744.108-1.116.001-1.46-.107-.345-.346-.624-.821-1.18l-.434-.508c-1.677-1.96-2.515-2.941-2.223-3.882.293-.941 1.523-1.22 3.983-1.776l.636-.144c.699-.158 1.048-.237 1.329-.45.28-.213.46-.536.82-1.182l.328-.588z"})})})})]}),e.jsxs("div",{className:"px-8 pt-12 pb-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:u("Save as Template")}),e.jsx("p",{className:"text-sm text-gray-600",children:u("Give your design a memorable name to find and reuse it later")})]}),e.jsxs("div",{className:"space-y-2 mb-8",children:[e.jsx("label",{htmlFor:"template-name",className:"block text-sm font-medium text-gray-700 mb-2",children:u("Template Name")}
314),e.jsxs("div",{className:"relative",children:[e.jsx(ci,{id:"template-name",type:"text",value:n,onChange:y=>a(y.target.value),onKeyDown:y=>{y.key==="Enter"&&n.trim()?d():y.key==="Escape"&&s(!1)},maxLength:50,placeholder:u("e.g., Summer Collection Design"),className:"w-full px-4 py-3.5 bg-gray-50 border-2 border-gray-200 rounded-[14px] text-gray-900 placeholder-gray-400 transition-all duration-200 focus:outline-none focus:bg-white focus:border-[#15B67F] focus:ring-4 focus:ring-[#15B67F]/10"}),e.jsx("div",{className:`absolute right-3 bottom-3.5 text-xs font-medium transition-colors ${50-n.length<10?"text-orange-500":"text-gray-400"}`,children:50-n.length})]}),e.jsxs("p",{className:"text-xs text-gray-500 flex items-center gap-1.5",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-gray-400"}),u("Press Enter to save, Esc to cancel")]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Uc,{asChild:!0,children:e.jsx(pe,{disabled:c,className:"flex-1 px-6 py-3.5 bg-gray-100 text-gray-700 font-semibold rounded-[14px] hover:bg-gray-200 active:scale-[0.98] transition-all duration-150 disabled:opacity-50 disabled:cursor-not-allowed",children:u("Cancel")})}),e.jsxs(pe,{onClick:d,disabled:!n.trim()||c,className:"flex-1 px-6 py-3.5 bg-gradient-to-r from-[#15B67F] to-[#12A072] text-white font-semibold rounded-[14px] hover:shadow-lg hover:shadow-[#15B67F]/25 active:scale-[0.98] transition-all duration-150 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:shadow-none relative overflow-hidden group",children:[e.jsx("span",{className:"absolute inset-0 w-full h-full bg-gradient-to-r from-transparent via-white/20 to-transparent -translate-x-full group-hover:translate-x-full transition-transform duration-700"}),e.jsx("span",{className:"relative flex items-center justify-center gap-2",children:c?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"}),u("Saving...")]}):u("Save Template")})]})]})]})]})})}),Ph=({showStoreSelectionModal:t,setShowStoreSelectionModal:s,showUpdateStoreModal:n,setShowUpdateStoreModal:a,draftId:c,draftRevision:d,designIdFromState:u,productDetails:y,productName:p,productDescriptionHtml:x,tags:b,variantPricesForPublish:C,providerId:L,selectedProvider:k,printingTechnology:K,brandingItemsForPublish:P,selectedVariantColorsForPublish:B,selectedVariantSizesForPublish:R,locationState:A,handlePublishSuccess:D,productSlug:_,navigate:O})=>{var I;return e.jsxs(e.Fragment,{children:[e.jsx(hm,{open:t,onOpenChange:s,designId:c||"",designRevision:d,sourceDesignId:u&&u===c?void 0:u||void 0,productTitle:(y==null?void 0:y.title)||p||"Untitled Product",productDescription:x,productType:"Apparel",tags:b,variantPrices:C,providerId:L||"",providerConfigId:(k==null?void 0:k.configId)||"",providerName:k==null?void 0:k.providerName,printingTechnology:K||void 0,brandingItems:P,selectedColors:B,selectedSizes:R,initialSelectedStoreIds:A==null?void 0:A.retryStoreConnectionIds,initialSelectionKey:(I=A==null?void 0:A.retryStoreConnectionIds)==null?void 0:I.join("|"),onSuccess:D}),e.jsx(gm,{open:n,onOpenChange:a,designId:c||"",productTitle:(y==null?void 0:y.title)||p||"Untitled Product",productDescription:x,tags:b,variantPrices:C,brandingItems:P,selectedColors:B,selectedSizes:R,onSuccess:()=>{_&&sessionStorage.removeItem(`printarex_edit_${_}`),O("/dashboard/catalog/my-products",{state:{refreshDesigns:!0,trackedDesignId:c}})}})]})},Ih=()=>{var W,se,q,J,Ne,je,Fe,wt,ge,Jr;const{productSlug:t,step:s}=Ac(),n=t||"",a=s||"designv1",[c]=Tc(),d=Ll(),u=Fl(),{user:y,isAuthenticated:p}=Ol(),x=Js(),[b,C]=r.useState(null),[L,k]=r.useState(null),[K,P]=r.useState(null),[B]=r.useState([]),[R,A]=r.useState(!1),[D,_]=r.useState(null),[O,I]=r.useState(!1),[ue,me]=r.useState(null),[Se,be]=r.useState(null),G=r.useCallback(()=>be(null),[]);r.useEffect(()=>{a!=="designv1"&&be(null)},[a]);const[ye,we]=r.useState(null),re=r.useRef(null),[X,Q]=r.useState(null),[S,w]=r.useState(!1),[M,E]=r.useState(!1),[Me,Y]=r.useState(!1),[Ee,Be]=r.useState(null),[Ae,Ze]=r.useState(!1),[Ye,kt]=r.useState("resolving_identity"),[he,ne]=r.useState(0),ee=r.useRef(!1),nt=r.useRef(null),Ue=r.useRef(null),Le=r.useRef(null),Te=r.useRef(!1),$e=r.useRef(null),Ke=r.useRef(!1),pt=r.useRef(!1),ot=r.useRef(null),at=r.useRef(null),He=r.useRef(null),[De,Gt]=r.useState(null),[es,ke]=r.useState(null),[lt,Wt]=r.useState(null),Qe=r.useCallback(()=>{Te.current=!0,$e.current&&clearTimeout($e.current),$e.current=setTimeout(()=>{Te.current=!1,$e.current=null},0)},[]),[ht,rr]=r.useState(null),[Oe,St]=r.useState(!0),[ze,it]=r.useState(null),[Lt,xt]=r.useState([]),[et,Lr]=r.useState(!0),[Dr,Dt]=r.useState(null),[qt,lr]=r.useState(null),Ct=r.useCallback(o=>{const m=sd(o);lr(m.listingDraft),rr(m.productDetails),St(m.attachSizeTable),it(m.sizeTableData),xt(m.sizeGuideImageUrls),Lr(m.attachCareInstructions),Dt(m.careInstructionsData)},[]),[yr,Mt]=r.useState(void 0),[At,Tt]=r.useState(void 0),[Vt,Kt]=r.useState(null),[Xt,Nt]=r.useState(null),[Ve,N]=r.useState(!1),[U,ae]=r.useState("rgb"),[le,ct]=r.useState(null),[Pt,Yt]=r.useState(null),Rt=r.useRef(null),$=r.useCallback(o=>{var V;const m=(V=Rt.current)==null?void 0:V.objectUrl;m!==(o==null?void 0:o.objectUrl)&&Gl(o==null?void 0:o.objectUrl),Rt.current=o,Yt(o),m!==(o==null?void 0:o.objectUrl)&&oi(m)},[]);r.useEffect(()=>()=>{var o;oi((o=Rt.current)==null?void 0:o.objectUrl)},[]);const de=r.useRef(void 0),ce=r.useRef(void 0),xe=r.useRef(null),f=r.useRef(null),j=r.useRef(null),Z=r.useRef("rgb"),{customerNeckLabel:oe,restoreCustomerNeckLabel:z,capturePendingCustomerNeckLabelChange:fe,acknowledgeCustomerNeckLabel:ve,stageCustomerNeckLabel:qe,customerNeckLabelDefaultPending:Ot,markNe
314wDraftForCustomerNeckLabelDefault:jt,settleCustomerNeckLabelDefault:sr}=Od(),nr=r.useCallback(o=>{const m=o.primaryMockupKey,V=o.primaryMockupTemplateId,te=o.selectedMockupTemplateIds?Qp(o.selectedMockupTemplateIds,m,V):void 0,Ie=o.selectedMockupKeys?eh(o.selectedMockupKeys,m,V):te==null?void 0:te.map(vt=>`template:${vt}`),_e=li(m)?null:V,zt=m||(V!=null?`template:${V}`:null);de.current=te?[...te]:void 0,ce.current=Ie?[...Ie]:void 0,xe.current=_e,f.current=zt,j.current=o.primaryVariantColor,Mt(de.current),Tt(ce.current),Kt(_e),Nt(zt),ct(o.primaryVariantColor),z(o),N(!0)},[z]);r.useEffect(()=>{de.current=yr},[yr]),r.useEffect(()=>{ce.current=At},[At]),r.useEffect(()=>{xe.current=Vt},[Vt]),r.useEffect(()=>{f.current=Xt},[Xt]),r.useEffect(()=>{j.current=le},[le]),r.useEffect(()=>{Z.current=U},[U]);const[ar,Qs]=r.useState([]),ft=r.useRef([]);r.useEffect(()=>{ft.current=ar},[ar]);const gt=r.useCallback(o=>{typeof o=="function"?Qs(m=>{const V=o(m);return ft.current=V,V}):(ft.current=o,Qs(o))},[]),Wr=r.useMemo(()=>ar.filter(o=>o.enabled).reduce((o,m)=>o+m.unitPrice*m.quantity,0),[ar]),[en,qr]=r.useState(!1),[ir,ts]=r.useState(""),[We,tt]=r.useState(!1),[vr,Jn]=r.useState(!1),[Xe,Sa]=r.useState(!1),[Aa,Mn]=r.useState(!1),[Ta,Qn]=r.useState(null),[ea,Ls]=r.useState(!1),[Ra,Ds]=r.useState(!1),Fa=r.useRef(null),F=d.state,{initialProviderId:ds,initialProviderName:pi,initialProviderCountry:Ea,initialPrintingTechnology:ta}=oh(F,c),tn=(F==null?void 0:F.newDesign)===!0,dt=(F==null?void 0:F.viewOnly)===!0,cr=c.get("draftId"),hi=r.useMemo(()=>!(F!=null&&F.providerId)||!F.providerName||!F.configId?null:{providerId:F.providerId,providerName:F.providerName,configId:F.configId},[F==null?void 0:F.configId,F==null?void 0:F.providerId,F==null?void 0:F.providerName]),ra=!!(cr&&!(F!=null&&F.reassignProvider)&&ot.current===cr),ks=r.useCallback(o=>!ra||sh(o,hi),[hi,ra]),Ft=r.useCallback((o,m=b,V=n)=>{const te=new URLSearchParams(c),Ie=m||cr;Ie&&te.set("draftId",Ie);const _e=te.toString(),zt=_e?`?${_e}`:"";return`/customization-for-your-stores/${V}/${o}${zt}`},[b,cr,n,c]),rn=`printarex_edit_${n}`,pr=r.useMemo(()=>{if(globalThis.window===void 0)return null;const o=sessionStorage.getItem(rn);if(o)try{return JSON.parse(o)}catch(m){return console.error("Failed to parse edit session data:",m),null}return null},[rn]),Ua=r.useMemo(()=>pr?cr?pr.designId===cr?pr:null:pr:null,[cr,pr]);r.useEffect(()=>{globalThis.window!==void 0&&(!cr||!(pr!=null&&pr.reviewMode)||pr.designId===cr||sessionStorage.removeItem(rn))},[cr,pr==null?void 0:pr.designId,pr==null?void 0:pr.reviewMode,rn]);const sn=lh(F,Ua,a,n),{isEditMode:Cs,editDesignId:xi}=sn,[nn]=r.useState(sn.publishedProductId),[an]=r.useState(sn.editStoreConnectionId),[Ms]=r.useState(sn.editStoreName),[sa]=r.useState(sn.editStoreShopDomain),dr=ch(F,Ua),{isPersonalizationReviewMode:Re,personalizationReviewStoreOrderId:na,personalizationReviewLineItemId:on,personalizationReviewVariantTitle:La,personalizationReviewSelectedColor:hr,personalizationReviewSelectedSize:ln,personalizationReviewReturnTo:Ps}=dr,{initialSelectedColor:fi,initialSelectedSize:Da}=dh(dr,F),Is=`printarex_template_${n}`,Bt=uh(tn,cr,xi,F==null?void 0:F.designId,Is),Pn=a==="edit"?null:n,Oa=Bt?"direct-id":tn?"new-design":"product-slug",bt=r.useMemo(()=>({flow:"store",routeMode:Oa,requestedDraftId:Bt,requestedProductSlug:Pn}),[Bt,Oa,Pn]),Pe=r.useMemo(()=>new nd(bt),[bt]),Or=r.useRef(null),Br=r.useRef(null),ut=r.useCallback(()=>{kt(Pe.getState().status)},[Pe]);r.useEffect(()=>{Br.current&&(clearTimeout(Br.current),Br.current=null);const o=Or.current;return o&&o!==Pe&&(o.dispose(),N(!1)),Or.current=Pe,Pe.getState().status==="resolving_identity"&&(Pe.beginLoading(),bt.routeMode==="new-design"&&Pe.confirmAbsent()),ut(),()=>{Br.current=setTimeout(()=>{Or.current===Pe&&(Pe.dispose(),Or.current=null)},0)}},[Pe,bt.routeMode,ut]),r.useEffect(()=>{if(tn&&n)sessionStorage.removeItem(Is);else if((cr||F!=null&&F.designId)&&n){const o=cr||(F==null?void 0:F.designId);o&&sessionStorage.setItem(Is,o)}},[cr,F==null?void 0:F.designId,n,Is,tn]),r.useEffect(()=>{Bt&&Bt!==nt.current&&(C(null),Ze(!1),ot.current=null,Be(null),ee.current=!1,Y(!1),Q(null),ns.current=null,_r(new Map),kr.current=ne
314w Map,An(new Map),As(new Map),$t.current=new Map,Zt.current=new Map,nt.current=Bt,pt.current=!1,Ue.current=null,Le.current=null,re.current=null,we(null),lr(null),rr(null),St(!0),it(null),xt([]),Lr(!0),Dt(null),Gt(null),ke(null),N(!1))},[Bt]);const[us,cn]=r.useState(ds),[Ss,In]=r.useState(pi),[Os,Ba]=r.useState(Ea),[Ar,Nr]=r.useState(ta),gi=F!=null&&F.providerId&&(F!=null&&F.providerName)?{providerId:F.providerId,providerName:F.providerName,configId:F.configId||""}:null,[Ce,rs]=r.useState(gi),{data:ms,loading:Qi,error:jr}=Ht(Bd,{variables:{configId:Ce==null?void 0:Ce.configId},skip:!(Ce!=null&&Ce.configId),fetchPolicy:"network-only",context:{suppressGlobalErrorToast:!0}}),Sn=$d({configId:Ce==null?void 0:Ce.configId,loading:Qi,error:jr,resolvedConfigId:ms===void 0?void 0:((W=ms.getPricingConfiguration)==null?void 0:W.configId)??null,dataReceived:ms!==void 0}),fr=Sn==="unavailable",dn=Sn==="available"&&!Qi,[$r,zr]=r.useState(null),[wr,_r]=r.useState(new Map),[ss,An]=r.useState(new Map),[Tn,As]=r.useState(new Map),ns=r.useRef(null),Tr=r.useRef(null),kr=r.useRef(new Map),$t=r.useRef(new Map),Zt=r.useRef(new Map),Gr=r.useRef(new Map),un=r.useCallback((o,m)=>[...m].sort((V,te)=>te.length-V.length).find(V=>o.startsWith(`${V}-`)),[]),ps=r.useCallback(o=>{const m=new Set(o),V=new Map(Array.from(kr.current.entries()).filter(([_e])=>!!un(_e,o)));kr.current=V,_r(V);const te=new Map(Array.from($t.current.entries()).filter(([_e])=>_e.includes("::")?m.has(_e.split("::")[0]):!0));$t.current=te,An(te);const Ie=new Map(Array.from(Zt.current.entries()).filter(([_e])=>m.has(_e)));Zt.current=Ie,As(Ie)},[un]),Ts=r.useRef(null),Vr=r.useRef(null),mn=r.useRef(null);r.useEffect(()=>{ns.current=X},[X]),r.useEffect(()=>{Tr.current=$r},[$r]),r.useEffect(()=>{kr.current=wr},[wr]),r.useEffect(()=>{$t.current=ss},[ss]),r.useEffect(()=>{Zt.current=Tn},[Tn]);const Rs=r.useCallback(o=>{const m=mo(o);ns.current=m,Array.isArray(m==null?void 0:m.selectedColors)&&ps(m.selectedColors),Q(m)},[ps]),It=r.useCallback(o=>{const m=new Map(o);$t.current=m,An(m)},[]),Fs=r.useCallback((o,m,V)=>{const te=ad(V),Ie=Wo($t.current,o,te.printAreaUrls),_e=Wo(Zt.current,m,te.variantUrls);Ie!==$t.current&&It(Ie),_e!==Zt.current&&(Zt.current=_e,As(_e))},[It]),hs=r.useCallback((o,m)=>{As(V=>{const te=new Map(V);return te.set(o,m),Zt.current=te,te})},[]);r.useEffect(()=>{p||u("/login")},[p,u]);const[aa]=qs(Jd,{client:Qr}),[Cr]=qs(So,{client:Qr,context:{suppressGlobalErrorMonitoring:!0},fetchPolicy:"no-cache"}),[xs]=qs(su,{client:Qr}),{saveEdits:Jt}=nu(),{data:yt,loading:Rn,error:Fn,refetch:fs}=Ht(Qd,{variables:{id:Bt},skip:!Bt,client:Qr,fetchPolicy:"no-cache"}),En=((se=yt==null?void 0:yt.getDesignById)==null?void 0:se.productSlug)||null,$a=En||(a==="edit"?null:n),{data:Et}=Ht(Rc,{variables:{productSlug:$a||""},skip:!$a||!!Bt&&Rn}),Bs=((q=yt==null?void 0:yt.getDesignById)==null?void 0:q.productId)||null,{data:Mr}=Ht(Fc,{variables:{productId:Bs},skip:!Bs}),as=(J=Et==null?void 0:Et.getProductBySlug)==null?void 0:J.productId,pn=(Ne=Et==null?void 0:Et.getProductBySlug)==null?void 0:Ne.productName,Xr=(je=Et==null?void 0:Et.getProductBySlug)==null?void 0:je.productSlug,bi=(Fe=yt==null?void 0:yt.getDesignById)==null?void 0:Fe.productId,ia=(wt=Mr==null?void 0:Mr.getProductById)==null?void 0:wt.productId,oa=(ge=Mr==null?void 0:Mr.getProductById)==null?void 0:ge.productName,Qt=((Jr=Mr==null?void 0:Mr.getProductById)==null?void 0:Jr.productSlug)||Xr,la=Qt||En||n||"";r.useEffect(()=>{const o=ia||bi||as;o&&k(o);const m=oa||pn;m&&P(m)},[ia,bi,as,oa,pn]),r.useEffect(()=>{if(Bt&&n&&Qt&&Qt!==n&&a!=="edit"){const o=c.toString(),m=o?`?${o}`:"";u(`/customization-for-your-stores/${Qt}/${a}${m}`,{state:F,replace:!0})}},[Bt,n,Qt,a,c,u,F]);const{data:is,loading:os,error:gr,refetch:za}=Ht(eu,{variables:{userId:y==null?void 0:y.id,productSlug:n},skip:!n||!(y!=null&&y.id)||!!Bt||tn,client:Qr,fetchPolicy:"no-cache",notifyOnNetworkStatusChange:!1}),er=(is==null?void 0:is.getDesignDraft)??null,_a=er?`${er.id??""}:${er.revision??"legacy"}`:null,Kr=(er==null?void 0:er.id)??null,Ga=(er==null?void 0:er.providerId)??null,Un=(er==null?void 0:er.providerName)??null,gs=(er==null?void 0:er.providerConfigId)??null;r.useEffect(()=>{const o=er;if(!o||!_a)return;let m;try{m=co(o,{flow:"store",routeMode:"product-slug",requestedProductSlug:n})}catch(st){console.error("[CustomizationForYourStores] Draft restoration failed:",st),Pe.fail(st),ut(),Be(x("Could not restore your design draft. Please try again."));return}const V=m.id,te=m.revision,Ie=Pe.accept(m);if(ut(),Ie==="ignored")return;if(Ie==="conflict"){ie.error(x("This design changed in another session. Your unsaved changes were preserved."));return}Qe(),V===Ue.current&&(ee.current=!1),V&&(Ue.current=V,Le.current=te),re.current=te,we(te),Ct(m.listingDraft),Z.current=m.mockupColorMode,ae(m.mockupColorMode),Gt(m.variantPricing.length>0?[...m.variantPricing]:null),ke(m.variantPricing.length>0?m.id:null),el(at.current,V,te),o.id&&C(o.id);const _e=zi({providerId:o.providerId,providerName:o.providerName,providerConfigId:o.providerConfigId},F),zt=ks(_e);
314if(zt&&!(F!=null&&F.reassignProvider)&&(o.providerId&&cn(o.providerId),o.providerName&&In(o.providerName),o.printingTechnology&&Nr(o.printingTechnology),o.providerCountry&&Ba(o.providerCountry)),zt&&_e&&rs(_e),Ze(!0),ee.current)return;if(o.selectedVariants){const st=o.selectedVariants;let tr=st;if(typeof st=="string")try{tr=JSON.parse(st)}catch(ya){console.error("[CustomizationForYourStores] Failed to parse variants JSON:",ya)}const br=Re?Al(tr,hr,ln):tr;Rs(br),ee.current=!0,Y(!0)}else ee.current=!0,Y(!0);const _t=(Re?Mo(ns.current,hr):null)||(Re?hr:null)||o.activeVariantColor;if(_t&&(Tr.current=_t,zr(_t)),o.variantCanvases&&Array.isArray(o.variantCanvases)){const st=new Map;o.variantCanvases.forEach(tr=>{const br=`${tr.colorName}-${tr.printArea}`;st.set(br,tr.canvasJson)}),kr.current=st,_r(st)}if(o.printAreaThumbnails&&Array.isArray(o.printAreaThumbnails)){const st=new Map,tr=new Map;o.printAreaThumbnails.forEach(br=>{br.printArea.endsWith("-main")?tr.set(br.printArea.replace("-main",""),br.thumbnailUrl):st.set(br.printArea,br.thumbnailUrl)}),It(st),Zt.current=tr,As(tr)}o.brandingItems&&o.brandingItems.length>0&>(Pl(o.brandingItems)),nr(m)},[Ct,er,_a,F,Re,hr,ln,gt,It,nr,Rs,De==null?void 0:De.length,n,x,Pe,ut,Qe,ks]),r.useEffect(()=>{const o=Bt?Fn:gr;o&&(console.error("[CustomizationForYourStores] Draft query error:",o),Pe.fail(o),ut(),Be(x("Could not load your design draft. Please try again.")))},[Fn,Bt,gr,Pe,ut,x]),r.useEffect(()=>{if(bt.routeMode==="new-design")return;const o=bt.routeMode==="direct-id"?Rn:os,m=bt.routeMode==="direct-id"?Fn:gr,V=bt.routeMode==="direct-id"?yt==null?void 0:yt.getDesignById:is==null?void 0:is.getDesignDraft;o||m||V||Pe.getState().status!=="loading"||(Pe.confirmAbsent(),ut(),bt.routeMode==="direct-id"&&Be(x("Could not find this design draft.")))},[yt==null?void 0:yt.getDesignById,Fn,is==null?void 0:is.getDesignDraft,gr,Pe,bt.routeMode,Ye,Rn,os,ut,x]);const eo=r.useCallback(async()=>{Be(null);const o=Pe.getState().status;if((o==="failed"||o==="conflict")&&(Pe.retry(),ut()),Bt){try{await fs()}catch(m){console.error("[CustomizationForYourStores] Failed to retry direct draft query:",m),Pe.fail(m),ut(),Be(x("Could not load your design draft. Please try again."))}return}if(gr){try{await za()}catch(m){console.error("[CustomizationForYourStores] Failed to retry draft query:",m),Pe.fail(m),ut(),Be(x("Could not load your design draft. Please try again."))}return}ne(m=>m+1)},[Bt,gr,Pe,fs,za,ut,x]),{data:Ln,refetch:mt}=Ht(tu,{variables:{designId:b},skip:!b,client:Qr,fetchPolicy:"cache-and-network"}),Dn=id(b),[ca,On]=r.useState(!1),da=qd((Ln==null?void 0:Ln.getSavedMockups)??[],{selectedMockupKeys:At,selectedMockupTemplateIds:yr}),$s=Xd(da,{selectedMockupKeys:At,selectedMockupTemplateIds:yr}),{data:Bn}=Ht(gu,{variables:{designId:b||""},skip:!b,fetchPolicy:"network-only"});r.useEffect(()=>{if(pt.current||ye===null)return;const{resumableJobs:o}=pu((Bn==null?void 0:Bn.publishingJobsForDesign)??[]);o.length!==0&&(pt.current=!0,Jn(!0))},[ye,Bn]);const $n=r.useCallback(async()=>{b&&await od(()=>mt({designId:b}),o=>{console.error("[CustomizationForYourStores] Failed to refresh saved mockups:",o),ie.error(x("Could not refresh saved mockups. Please try again."))})},[b,mt,x]),Es=r.useMemo(()=>nl(X),[X]),to=r.useMemo(()=>Nu(X),[X]),zn=r.useMemo(()=>new Set(To(X).map(o=>`${ur(o.colorName)}|${ur(o.size)}`)),[X]);r.useEffect(()=>{if(!le||Es.length===0)return;Es.some(m=>ur(m)===ur(le))||ct(Es[0])},[le,Es]),r.useEffect(()=>{const o=zi({providerId:Ga,providerName:Un,providerConfigId:gs},F);o&&ks(o)&&rs(o)},[Ga,Un,gs,F,ks]),r.useEffect(()=>{const o=yt==null?void 0:yt.getDesignById;if(!(o!=null&&o.providerId)||!o.providerName||!o.providerConfigId)return;const m=zi({providerId:o.providerId,providerName:o.providerName,providerConfigId:o.providerConfigId},F);m&&ks(m)&&rs(m)},[yt,F,ks]);const ua=Rn||os,zs=Me&&!ua&&!!b&&(!(tn&&!!(fi||Da))||Es.length>0),Ut=r.useCallback(o=>{ld({draftId:b,error:o,workflowType:"CUSTOMIZE_FOR_YOUR_STORE"})},[b]),H=r.useMemo(()=>b?new zd({draftId:b,initialRevision:re.current,autosaveDelayMs:3e4,onAutosaveError(o){console.error("[CustomizationForYourStores] Autosave failed:",o),Ut(o),ie.error("Failed to save draft - please try again")},onAcceptanceProjectionError(o,m){console.error("[CustomizationForYourStores] Failed to project accepted save:",m.scope,o)},onStateChange(o){A(o.status==="saving"),w(o.dirtyScopes.length>0),we(o.revision);const m=Pe.getState();o.dirtyScopes.length>0&&m.status!=="disposed"?(Pe.markDirty(),ut()):o.status==="saved"&&m.acceptedDraftId===b&&m.status!=="disposed"&&(Pe.acknowledgeLocalCommit(o.revision),ut(),_(new Date))}}):null,[b,Pe,Ut,ut]),ma=r.useRef(null);r.useEffect(()=>(ma.current&&(clearTimeout(ma.current),ma.current=null),at.current&&at.current!==H&&at.current.dispose(),at.current=H,()=>{ma.current=setTimeout(()=>{at.current===H&&(H==null||H.dispose(),at.current=null)},0)}),[H]);const vi=r.useCallback(o=>
314{if(!H)throw new Error("The design draft session is not ready.");return H.registerScope(o)},[H]),bs=r.useCallback(o=>{H==null||H.markDirty(o)},[H]),Ni=r.useCallback(o=>{H==null||H.discardDirty(o)},[H]),Yr=r.useCallback(async(o,m=[])=>{if(!H)throw new Error("The design draft session is not ready.");return _i(Gr.current,"designv1",()=>H.commit(o,m))},[H]),ys=r.useCallback(async(o,m=[],V=Gr.current,te)=>{if(!H)throw new Error("The design draft session is not ready.");return _i(V,"designv1",()=>H.flushBeforeLeave(o,m),te)},[H]),Va=r.useCallback(async()=>{await ys("share",["mockups"]),await mt()},[ys,mt]);r.useEffect(()=>{if(!(yt!=null&&yt.getDesignById))return;const o=yt.getDesignById;let m;try{m=co(o,{flow:"store",routeMode:"direct-id",requestedDraftId:Bt,requestedProductSlug:o.productSlug||void 0})}catch(vt){console.error("[CustomizationForYourStores] Direct draft restoration failed:",vt),Pe.fail(vt),ut(),Be(x("Could not restore your design draft. Please try again."));return}const V=Pe.accept(m);if(ut(),V==="ignored")return;if(V==="conflict"){ie.error(x("This design changed in another session. Your unsaved changes were preserved."));return}if(Qe(),m.id===Ue.current&&(ee.current=!1),re.current=m.revision,Ue.current=m.id,Le.current=m.revision,we(m.revision),Ct(m.listingDraft),Z.current=m.mockupColorMode,ae(m.mockupColorMode),Gt(m.variantPricing.length>0?[...m.variantPricing]:null),ke(m.variantPricing.length>0?m.id:null),el(H,m.id,m.revision),Cs&&o.productSlug&&a==="edit"){sessionStorage.setItem(`printarex_edit_${o.productSlug}`,JSON.stringify({designId:o.id,publishedProductId:nn,storeConnectionId:an,storeName:Ms,storeShopDomain:sa,editMode:!0,reviewMode:Re,storeOrderId:na,externalLineItemId:on,selectedColor:hr,selectedSize:ln,reviewVariantTitle:La,returnTo:Ps})),u(Ft("designv1",o.id,o.productSlug),{state:{...F||{},designId:o.id,editMode:!0,publishedProductId:nn,storeConnectionId:an,storeName:Ms,storeShopDomain:sa,reviewMode:Re,storeOrderId:na,externalLineItemId:on,selectedColor:hr||void 0,selectedSize:ln||void 0,reviewVariantTitle:La||void 0,returnTo:Ps},replace:!0});return}if(o.productId&&k(o.productId),C(o.id),o.selectedVariants){let vt=o.selectedVariants;if(typeof vt=="string")try{vt=JSON.parse(vt)}catch(st){console.error("[CustomizationForYourStores] Failed to parse variants JSON:",st)}const _t=Re?Al(vt,hr,ln):vt;Rs(_t),ee.current=!0,Y(!0)}else ee.current=!0,Y(!0);const Ie=(Re?Mo(ns.current,hr):null)||(Re?hr:null)||o.activeVariantColor;if(Ie&&(Tr.current=Ie,zr(Ie)),o.variantCanvases&&Array.isArray(o.variantCanvases)){const vt=new Map;o.variantCanvases.forEach(_t=>{const st=`${_t.colorName}-${_t.printArea}`;vt.set(st,_t.canvasJson)}),kr.current=vt,_r(vt)}if(o.printAreaThumbnails&&Array.isArray(o.printAreaThumbnails)){const vt=new Map,_t=new Map;o.printAreaThumbnails.forEach(st=>{st.printArea.endsWith("-main")?_t.set(st.printArea.replace("-main",""),st.thumbnailUrl):vt.set(st.printArea,st.thumbnailUrl)}),It(vt),Zt.current=_t,As(_t)}const _e=zi({providerId:o.providerId,providerName:o.providerName,providerConfigId:o.providerConfigId},F),zt=ks(_e);zt&&!(F!=null&&F.reassignProvider)&&(o.providerId&&cn(o.providerId),o.providerName&&In(o.providerName),o.printingTechnology&&Nr(o.printingTechnology),o.providerCountry&&Ba(o.providerCountry)),zt&&_e&&rs(_e),o.brandingItems&&o.brandingItems.length>0&>(Pl(o.brandingItems)),nr(m),Ze(!0)},[Ct,yt,Cs,a,u,nn,an,Ms,sa,Re,na,on,hr,ln,La,Ps,F,gt,It,nr,Rs,Ft,Bt,H,Pe,ut,Qe,ks,x]),r.useEffect(()=>{(async()=>{if(!(y!=null&&y.id)||!n||!L||bt.routeMode==="direct-id"||b||Ye!=="absent"&&Ye!=="creating")return;const m=async()=>{var Ie;if(bt.routeMode==="product-slug")try{await Hd.deleteProjectByProductSlug(n,y.id)}catch(_e){console.error("[CustomizationForYourStores] Failed to clean IndexedDB:",_e)}const V=n.split("-").map(_e=>_e.charAt(0).toUpperCase()+_e.slice(1)).join(" "),{data:te}=await aa({variables:{input:{userId:y.id,productId:L,productSlug:n,catalogName:(F==null?void 0:F.catalogName)||void 0,categoryName:(F==null?void 0:F.categoryName)||void 0,subcategoryName:(F==null?void 0:F.subcategoryName)||void 0,name:`${V} - Stores`,wizardStep:a,providerId:us||void 0,providerName:Ss||void 0,providerCountry:Os||void 0,providerConfigId:(Ce==null?void 0:Ce.configId)||void 0,printingTechnology:Ar||void 0}}});if(!((Ie=te==null?void 0:te.createDesignDraft)!=null&&Ie.id))throw new Error("Draft creation returned no design.");return co(te.createDesignDraft,bt)};try{const V=Pe.createAfterConfirmedAbsence(m);ut();const te=await V;ut(),re.current=te.revision,Ue.current=te.id,Le.current=te.revision,we(te.revision),C(te.
314id),nr(te),jt(),ee.current=!0,Y(!0),u(Ft(a==="edit"?"designv1":a,te.id),{state:F,replace:!0})}catch(V){if(Pe.getState().status==="disposed")return;console.error("[CustomizationForYourStores] Failed to create draft:",V),ut(),Be(x("Could not create your design draft. Please try again."))}})()},[y==null?void 0:y.id,L,n,b,a,us,Ss,Os,Ce==null?void 0:Ce.configId,Ar,aa,Ft,u,F,he,Pe,bt,Ye,ut,nr,jt,x]);const ji=r.useCallback(()=>{var _e,zt;const o=((_e=Vr.current)==null?void 0:_e.call(Vr))??null,m=new Map(kr.current),V=new Map($t.current),te=new Map(Zt.current);o!=null&&o.colorName&&o.printArea&&o.canvasJson&&(m.set(`${o.colorName}-${o.printArea}`,o.canvasJson),o.thumbnailUrl&&(V.set(`${o.colorName}::${o.printArea}`,o.thumbnailUrl),o.printArea==="front"&&(V.set("front",o.thumbnailUrl),te.set(o.colorName,o.thumbnailUrl))));let Ie=null;try{Ie=((zt=Ts.current)==null?void 0:zt.call(Ts))??null}catch(vt){console.error("[CustomizationForYourStores] Failed to generate thumbnail:",vt)}return{canvas:o,selectedVariants:structuredClone(mo(ns.current)),activeVariantColor:Tr.current,variantCanvases:m,printAreaThumbnails:V,variantThumbnails:te,thumbnailUrl:Ie,brandingItems:structuredClone(ft.current),selectedMockupIds:de.current?[...de.current]:de.current,selectedMockupKeys:ce.current?[...ce.current]:ce.current,primaryMockupId:xe.current,primaryMockupKey:f.current,primaryVariantColor:j.current,mockupColorMode:Z.current,templateMetadata:He.current,customerNeckLabelChange:fe()}},[fe]),wi=r.useCallback(async(o,m)=>{var Bo,$o,zo,_o;if(!b)throw new Error("The design draft is not ready.");const V=m.canvas,te=m.selectedVariants,Ie=m.activeVariantColor,_e=m.variantCanvases,zt=m.printAreaThumbnails,vt=m.variantThumbnails,_t=nl(te),st=hr?_t.find(Ge=>Ge.toUpperCase()===hr.toUpperCase())||hr:null,tr=Re&&st?[st]:_t;if(Re){const Ge=V||((Bo=Vr.current)==null?void 0:Bo.call(Vr)),Vs=Ge!=null&&Ge.canvasJson?rh(Ge.canvasJson):null,js=(Ge==null?void 0:Ge.printArea)||null,ti=(Ge==null?void 0:Ge.colorName)||st||Ie||hr||tr[0]||null;if(!Vs||!js)throw console.error("[CustomizationForYourStores] Failed to save personalized order copy: missing active canvas snapshot",{hasCanvasJson:!!(Ge!=null&&Ge.canvasJson),printArea:Ge==null?void 0:Ge.printArea,colorName:Ge==null?void 0:Ge.colorName,draftId:b}),new Error("The active personalized canvas could not be captured.");A(!0);try{if(!await Jt(b,Vs,{printAreaId:js,colorName:ti}))throw console.error("[CustomizationForYourStores] Personalized order copy save failed: mutation returned false",{draftId:b,printAreaId:js,colorName:ti}),new Error("The personalized order copy could not be saved.");return _(new Date),w(!1),{revision:o.expectedRevision}}catch(Wn){throw console.error("[CustomizationForYourStores] Failed to save personalized order copy:",Wn),Wn}finally{A(!1)}}const br=Array.from(_e.entries()).map(([Ge,Vs])=>{const js=un(Ge,tr),ti=js?Ge.slice(js.length+1):"";return{colorName:js||"",printArea:ti,canvasJson:Vs}}).filter(Ge=>tr.includes(Ge.colorName)&&Ge.printArea),ya=m.thumbnailUrl,Lo=m.brandingItems,pc=Lo.length>0?Kp(Lo):void 0,Do=m.selectedMockupIds,Oo=m.selectedMockupKeys,hc=m.primaryMockupId,oo=m.primaryMockupKey,xc=(()=>{const Ge=m.primaryVariantColor;return Ge&&_t.some(js=>ur(js)===ur(Ge))?Ge:_t[0]||null})(),fc=li(oo)?null:hc;A(!0);try{const Ge=new Set(tr),Vs=await _d({designId:b,clientOperationId:o.clientOperationId,thumbnailUrl:ya,printAreaThumbnails:new Map(Array.from(zt).filter(([va])=>!va.includes("::")||Ge.has(va.split("::")[0]))),variantThumbnails:new Map(Array.from(vt).filter(([va])=>Ge.has(va)))}),js=Re?{activeVariantColor:Ie,variantCanvases:a==="designv1"&&br.length>0?br:void 0,printAreaThumbnails:Vs.printAreaThumbnails,expectedRevision:o.expectedRevision,clientOperationId:o.clientOperationId}:{wizardStep:a,selectedVariants:te,activeVariantColor:Ie,variantCanvases:a==="designv1"&&br.length>0?br:void 0,printAreaThumbnails:Vs.printAreaThumbnails,providerId:us||void 0,providerName:Ss||void 0,providerCountry:Os||void 0,providerConfigId:(Ce==null?void 0:Ce.configId)||void 0,printingTechnology:Ar||void 0,brandingItems:pc,selectedMockupTemplateIds:Do,selectedMockupKeys:Oo,primaryMockupTemplateId:Do!==void 0||li(oo)?fc:void 0,primaryMockupKey:Oo!==void 0?oo:void 0,primaryVariantColor:xc||void 0,mockupColorMode:m.mockupColorMode,name:($o=m.templateMetadata)==null?void 0:$o.name,isTemplate:(zo=m.templateMetadata)==null?void 0:zo.isTemplate,...Gd(m.customerNeckLabelChange),expectedRevision:o.expectedRevision,clientOperationId:o.clientOperationId},Wn=(_o=(await Cr({variables:{id:b,input:js}})).data)==null?void 0:_o.updateDesignDraft;if(!Wn)throw new Error("Design update returned no committed draft.");return Vd(b,o.clientOperationId),Fs(zt,vt,Array.from(Vs.storageUrlsByPrintArea,([va,gc])=>({printArea:va,thumbnailUrl:gc}))),He.current===m.templateMetadata&&(He.current=null),Re||ve(m.customerNeckLabelChange,Wn.customerNeckLabel),{revision:Wn.revision??o.expectedRevision}}catch(Ge){throw console.error("[CustomizationForYourStores] Failed to save draft:",Ge),Ge}finally{A(!1)}},[b,a,Cr,Jt,us,Ss,Os,Ce,Ar,un,Re,hr,Fs,ve]);r.useEffect(()=>{if(H)return H.registerScope({scope:"design",capture:()=>{const o=ji();return{commit:m=>wi(m,o)}}})},[ji,H,wi]);const ki=r.useCallback(()=>{var V;const o=(V=mn.current)==null?void 0:V.call(mn);if(!(o!=null&&o.dirty))throw new Error("Personalization changed but no dirty configuration snapshot is available.");if(!b||o.input.designId!==b)throw new Error("Personalization configuration does not match the active design draft.");const m=tl(o.input);return{commit:async te=>{var vt,_t;if(te.expectedRevision===null)throw new Error("The design revision is not ready for a personalization update.");const Ie=tl({...m,expectedRevision:te.expectedRevision,clientOperationId:te.clientOperationId}),zt=(vt=(await xs({variables:{input:Ie},update(st,{data:tr}){var ya;const br=(ya=tr==null?void 0:tr.savePersonalizationConfig)==null?void 0:ya.personalizationConfig;br&&st.writeQuery({query:au,variables:{designId:Ie.designId},data:{personalizationConfig:br}})}})).data)==null?void 0:vt.savePersonalizationConfig;if(!(zt!=null&&zt.personalizationConfig)||!Number.isSafeInteger(zt.committedRevision))throw new Error("Personalization update returned no committed acknowledgement.");return(_t=o.markClean)==null||_t.call(o),{revision:zt.committedRevision}}}},[b,xs]);r.useEffect(()=>{if(!(!H||Re))return H.registerScope({scope:"personalization",dependsOn:["design"],capture:ki})},[ki,H,Re]);const Ci=r.useCallback(async()=>H?(await Yr("manual-save",["design"]),!0):!1,[Yr,H]),pa=r.useCallback(()=>{!zs||!H||Te.current||H.scheduleAutosave()},[zs,H]),rt=r.useCallback(()=>{!H||Te.current||(H.markDirty("design"),!Re&&zs&&H.scheduleAutosave())},[zs,H,Re]);r.useEffect(()=>{!zs||!H||Te.current||H.getState().dirtyScopes.length>0&&H.scheduleAutosave()},[zs,H]);const ha=r.useCallback(o=>{const m=mo(o);uo(ns.current,m)||(Rs(m),rt())},[rt,Rs]),_s=r.useCallback(o=>{Ar!==o&&(Nr(o),rt())},[rt,Ar]),Mi=r.useCallback(o=>
314{if(Sl(de.current,o))return;const m=o?[...o]:void 0;de.current=m,Mt(m),Ve&&!dt&&rt()},[dt,rt,Ve]),Ka=r.useCallback(o=>{if(Sl(ce.current,o))return;const m=o?[...o]:void 0;ce.current=m,Tt(m),Ve&&!dt&&rt()},[dt,rt,Ve]),Pi=r.useCallback(o=>{xe.current!==o&&(xe.current=o,Kt(o),Ve&&!dt&&rt())},[dt,rt,Ve]),hn=r.useCallback(o=>{f.current!==o&&(f.current=o,Nt(o),Ve&&!dt&&rt())},[dt,rt,Ve]),_n=r.useCallback(()=>Yr("internal-save",["design"]),[Yr]),Ya=Kd({stageCustomerNeckLabel:qe,selectedMockupKeysRef:ce,primaryMockupKeyRef:f,setSelectedMockupKeys:Ka,setPrimaryMockupKey:hn,markDesignDirty:rt,commitDesign:_n}),Ii=r.useCallback(o=>{j.current!==o&&(j.current=o,ct(o),Ve&&!dt&&rt())},[dt,rt,Ve]),vs=r.useCallback(o=>{Z.current!==o&&(Z.current=o,ae(o),rt())},[rt]),Gn=r.useCallback(o=>{const m=ft.current,V=typeof o=="function"?o(m):o;uo(m,V)||(gt(V),V.some(te=>te.enabled||te.designId)&&rt())},[rt,gt]),Vn=r.useCallback((o,m)=>{const V=ft.current,te=V.map(Ie=>Ie.brandingProductType===o?{...Ie,...m}:Ie);uo(V,te)||(gt(te),rt())},[rt,gt]),Ha=r.useCallback(o=>{Ts.current=o},[]),Si=r.useCallback(o=>{Vr.current=o},[]),Ai=r.useCallback(o=>{mn.current=o},[]),Ti=r.useCallback(()=>{Re||(H==null||H.markDirty("personalization"),pa())},[H,Re,pa]),Kn=r.useCallback(()=>{Re||H==null||H.discardDirty("personalization")},[H,Re]),Ns=r.useCallback((o,m,V="front")=>{const te=`${o}-${V}`;if(Yd(kr.current.get(te),m))return;const Ie=new Map(kr.current);Ie.set(te,m),kr.current=Ie,_r(Ie),rt()},[rt]),Yn=r.useCallback(o=>{const m=cd({currentVariantCanvases:kr.current,currentPrintAreaThumbnails:$t.current,currentVariantThumbnails:Zt.current},o);return m.changed&&(kr.current=m.variantCanvases,$t.current=m.printAreaThumbnails,Zt.current=m.variantThumbnails,_r(m.variantCanvases),An(m.printAreaThumbnails),As(m.variantThumbnails),rt()),m},[rt]),Gs=r.useCallback(()=>{var m;const o=(m=Vr.current)==null?void 0:m.call(Vr);!(o!=null&&o.colorName)||!o.printArea||!o.canvasJson||Ns(o.colorName,o.canvasJson,o.printArea)},[Ns]),Wa=r.useCallback((o,m)=>{m?Gr.current.set(o,m):Gr.current.delete(o)},[]),[ls,Ri]=r.useState(!1),[qa,xn]=r.useState(!1),cs=r.useRef(!1),Xa=r.useCallback(async()=>{const o=a,m=Gr.current.get(o);if(!m)return!0;Ri(!0);try{return await m(),!0}catch{return!1}finally{Ri(!1)}},[a]),Fi=r.useCallback(async()=>{const o=new Map(Gr.current),m={suppressWithdrawnProviderCapabilityToast:!0},V=o.get("designv1");V&&fr&&o.set("designv1",async te=>{try{await V(te)}catch(Ie){if(!ah(Ie))throw Ie}}),a!=="designv1"&&await _i(o,a,async()=>{},m),await ys("save-and-exit",["design"],o,m)},[ys,fr,a]),Ei=r.useCallback(async()=>{if(!(!b||dt||cs.current)){cs.current=!0,xn(!0);try{Gs(),await Fi(),u(`/products/${n}`,{state:{reselectForDraftId:b}})}catch(o){console.error("[CustomizationForYourStores] Provider reselection save failed:",o),Ut(o),ie.error(x("Could not save your changes. Please try again."))}finally{cs.current=!1,xn(!1)}}},[Gs,b,Fi,dt,u,n,Ut,x]),Za=r.useCallback((o,m)=>{const V={...F||{}};delete V.forceMockupRegenerationAt;const te=m===void 0?V:{...V,forceMockupRegenerationAt:m};u(Ft(o),{state:te})},[Ft,F,u]),Zr=r.useCallback(async o=>{const m=Ys.indexOf(o);if(dt)return Za(o),!0;if(fr&&m>Ys.indexOf("designv1"))return ie.error(x("You can continue once a provider is selected.")),!1;if(ls||cs.current||a==="mockups"&&O||Re)return!1;const V=a==="designv1"&&o==="mockups";cs.current=!0,xn(!0);try{if(!await Xa())return!1;if(V&&Gs(),!H)throw new Error("The design draft session is not ready.");const Ie=V&&H.getState().dirtyScopes.includes("design");return await H.flushBeforeLeave("step-navigation",V?["design"]:[]),Za(o,Ie?Date.now():void 0),!0}catch(te){return console.error("[CustomizationForYourStores] Save before navigation failed:",te),Ut(te),ie.error(x(V?"Save your design before continuing to mockups":"Could not save your changes. Please try again.")),!1}finally{cs.current=!1,xn(!1)}},[Gs,H,ls,O,Re,fr,dt,Za,Ut,Xa,a,x]),Hn=r.useCallback(async()=>{const o=Ys.indexOf(a);if(o<Ys.length-1){const m=Ys[o+1];return Zr(m)}return!1},[Zr,a]),Ja=r.useCallback(()=>{const o=Ys.indexOf(a);if(o>0){const m=Ys[o-1];Zr(m)}},[Zr,a]),Qa=r.useCallback(async()=>
314{if(cs.current)return;if(Re){try{if(!H)throw new Error("The design draft session is not ready.");await ys("save-and-exit",["design"]),u(Ps)}catch(m){console.error("[CustomizationForYourStores] Order review save failed:",m),Ut(m),ie.error(x("Save the personalized order copy before returning to the order."))}return}cs.current=!0,xn(!0);try{await _i(Gr.current,"designv1",async()=>{})}catch(m){console.error("[CustomizationForYourStores] Pending design operation failed:",m),ie.error(x("Could not finish applying your design. Please try again."));return}finally{cs.current=!1,xn(!1)}S||!!(H!=null&&H.getState().dirtyScopes.length)||!!(H!=null&&H.hasDeferredWork("save-and-exit"))?E(!0):u(Ps)},[H,ys,S,Re,u,Ps,Ut,x]),xa=async()=>{try{if(!H)throw new Error("The design draft session is not ready.");await ys("save-and-exit",["design"]),E(!1),u(Ps)}catch(o){console.error("[CustomizationForYourStores] Save and exit failed:",o),Ut(o),ie.error(x("Failed to save draft - please try again"))}},so=()=>{E(!1),u(Ps)},no=r.useCallback(async()=>{if(!b){ie.info(x(Re?"Order review copy is loading, please wait...":"Draft is being created, please wait..."));return}if(!H)return;const o=Yr("manual-save",["design"]);ie.promise(o,{loading:x(Re?"Saving order review copy...":"Saving draft..."),success:x(Re?"Order review copy saved":"Progress saved as draft"),error:x(Re?"Failed to save order review copy - please try again":"Failed to save draft - please try again")});try{await o}catch(m){console.error("[CustomizationForYourStores] Manual save failed:",m),Ut(m)}},[Yr,b,H,Re,Ut,x]);r.useEffect(()=>{!Ae||!cr||!(F!=null&&F.reassignProvider)||!b||!(Ce!=null&&Ce.configId)||ot.current===b||!H||(ot.current=b,H.markDirty("design"),_n().then(()=>{u(`${d.pathname}${d.search}`,{replace:!0,state:{...F,reassignProvider:!1}})}).catch(o=>{ot.current=null,console.error("[CustomizationForYourStores] Provider reassignment save failed:",o),Ut(o),ie.error(x("Failed to save draft - please try again"))}))},[_n,Ae,b,cr,H,d.pathname,d.search,F,u,Ut,Ce==null?void 0:Ce.configId,x]);const ao=r.useCallback(async()=>{if(!b){ie.info(x("Draft is being created, please wait..."));return}if(!(R||ea||cs.current)){Ls(!0);try{if(Gs(),!H)throw new Error("The design draft session is not ready.");const o=H.getState().dirtyScopes.includes("design");
314await Yr("preview",["design"]),Qn(o?Date.now():null),Mn(!0)}catch(o){console.error("[CustomizationForYourStores] Preview save failed:",o),Ut(o),ie.error(x("Please save your design before previewing mockups"))}finally{Ls(!1)}}},[Gs,Yr,b,H,ea,R,Ut,x]),Ui=r.useCallback(async()=>{var o;if(fr){ie.error(x("You can continue once a provider is selected."));return}Ds(!0);try{await((o=Fa.current)==null?void 0:o.call(Fa)),await Hn()&&Mn(!1)}catch{return}finally{Ds(!1)}},[Hn,fr,x]),fn=r.useCallback(o=>{Fa.current=o},[]);r.useEffect(()=>{K&&ts(K)},[K]);const io=r.useCallback(async()=>{if(!b||!ir.trim()){ie.error(x("Please enter a template name"));return}tt(!0);try{if(!H)throw new Error("The design draft session is not ready.");He.current=Object.freeze({name:ir.trim(),isTemplate:!0}),H.markDirty("design"),await Yr("manual-save",["design"]),qr(!1),ie.success(x("Design saved as template"))}catch(o){console.error("Failed to save template:",o),Ut(o),ie.error(x("Failed to save template"))}finally{tt(!1)}},[Yr,b,H,Ut,ir,x]),ei=r.useMemo(()=>De&&Array.isArray(De)&&De.length>0?zn.size===0?[]:De.filter(o=>{const m=di(o),V=Co(o);return!m||!V?!1:zn.has(`${ur(m)}|${ur(V)}`)}).map(o=>({color:di(o)||o.colorName,size:Co(o)||o.size,price:o.retailPrice,baseProviderPrice:o.baseProviderPrice,printAreaCost:o.printAreaCost,profitMargin:o.profitMargin})):[],[De,zn]),fa=r.useMemo(()=>Zp(zn,ei),[zn,ei]),Li=r.useMemo(()=>Hp(ar),[ar]),ga=r.useMemo(()=>Uo({productDetails:ht??{title:"",description:""},attachSizeTable:Oe,sizeTable:ze,sizeGuideImageUrls:Lt,attachCareInstructions:et,careInstructions:Dr}),[ht,Oe,ze,Lt,et,Dr]),ba=r.useCallback(async o=>{if(!b){ie.error(x("No design to publish"));return}if(fr){ie.error(x("You can continue once a provider is selected."));return}if(!Jp(qt,(ht==null?void 0:ht.title)??"",ga)){ie.error(x("Please review and save your product details before publishing.")),await Zr("details");return}if(es!==b||!fa){ie.error(x("Please review and save your prices before publishing.")),await Zr("prices");return}if(!us||!(Ce!=null&&Ce.configId)){ie.error(x("Provider information is missing. Please select a provider before publishing."));return}try{if(!H)throw new Error("The design draft session is not ready.");const m=await ys("publish",["design"]);we(m.revision),o==="update"?Sa(!0):Jn(!0)}catch(m){console.error("[CustomizationForYourStores] Publish preflight save failed:",m),Ut(m),ie.error(x("Could not save your latest changes before publishing."))}},[b,fr,qt,es,fa,us,Ce==null?void 0:Ce.configId,H,x,Zr,ht==null?void 0:ht.title,ga,ys,Ut]);r.useEffect(()=>{!(F!=null&&F.openPublishModal)||!b||Ke.current||(Ke.current=!0,ba(Cs?"update":"publish"))},[b,Cs,F==null?void 0:F.openPublishModal,ba]);const Di=r.useCallback(()=>{sessionStorage.removeItem(Is),u("/dashboard/catalog/my-products",{state:{refreshDesigns:!0,trackedDesignId:b}})},[b,u,Is]),i=r.useCallback(o=>{var V;const m=(V=at.current)==null?void 0:V.getState();o===b&&(m==null?void 0:m.draftId)===o&&ke(o)},[b]),l=r.useCallback(o=>{var V;const m=(V=at.current)==null?void 0:V.getState();o===b&&(m==null?void 0:m.draftId)===o&&ke(null)},[b]),h=r.useMemo(()=>({productSlug:la,productId:L,productName:K,currentStep:a,draftId:b,completedSteps:B,isLoading:ua,isSaving:R,lastSaved:D,selectedVariants:X,variantsLoaded:Me,activeVariantColor:$r,variantCanvases:wr,printAreaThumbnails:ss,setPrintAreaThumbnails:It,variantThumbnails:Tn,setVariantThumbnail:hs,setSelectedVariants:ha,setActiveVariantColor:zr,updateVariantCanvas:Ns,applyVariantDesignBatch:Yn,setCanvasThumbnailGenerator:Ha,setCanvasStateSnapshotter:Si,setPersonalizationConfigSnapshotter:Ai,markPersonalizationConfigDirty:Ti,markPersonalizationConfigClean:Kn,registerDraftScope:vi,markDraftScopeDirty:bs,discardDraftScope:Ni,scheduleDraftAutosave:pa,commitDraft:Yr,designRevision:ye,providerId:us,providerName:Ss,selectedProvider:Ce,setProviderId:cn,setProviderName:In,setSelectedProvider:rs,printingTechnology:Ar,setPrintingTechnology:_s,initialSelectedColor:fi,initialSelectedSize:Da,isPersonalizationReviewMode:Re,personalizationReview:mh(dr),goToStep:Zr,goToNextStep:Hn,goToPreviousStep:Ja,nextStepLabel:Tl(Re,a,x),saveDraft:Ci,returnToCatalog:Qa,isEditMode:Cs,publishedProductId:nn,editStoreConnectionId:an,editStoreName:Ms,isViewOnl
314y:dt,variantPricing:De,setVariantPricing:Gt,globalProfitMargin:lt,setGlobalProfitMargin:Wt,productDetails:ht,setProductDetails:rr,attachSizeTable:Oe,setAttachSizeTable:St,sizeTableData:ze,setSizeTableData:it,sizeGuideImageUrls:Lt,setSizeGuideImageUrls:xt,attachCareInstructions:et,setAttachCareInstructions:Lr,careInstructionsData:Dr,setCareInstructionsData:Dt,listingDraft:qt,setListingDraft:lr,acknowledgeVariantPricingPersisted:i,invalidateVariantPricingPersistence:l,selectedMockupIds:yr,setSelectedMockupIds:Mi,mockupSelectionHydrated:Ve,selectedMockupKeys:At,setSelectedMockupKeys:Ka,primaryMockupId:Vt,setPrimaryMockupId:Pi,primaryMockupKey:Xt,setPrimaryMockupKey:hn,customerNeckLabel:oe,applyCustomerNeckLabel:Re?void 0:Ya,customerNeckLabelDefaultPending:Ot,settleCustomerNeckLabelDefault:sr,mockupColorMode:U,setMockupColorMode:vs,primaryVariantColor:le,setPrimaryVariantColor:Ii,primaryMockupPreview:Pt,setPrimaryMockupPreview:$,brandingItems:ar,setBrandingItems:Gn,updateBrandingItem:Vn,brandingTotalCost:Wr,registerBeforeLeave:Wa,isBeforeLeaveRunning:ls,refreshSavedMockups:$n}),[i,$r,Yn,et,Oe,ar,Wr,Dr,Yr,B,Ni,b,ye,an,Ms,la,lt,Hn,Ja,Zr,fi,Da,l,ls,Cs,ua,Re,R,dt,D,qt,bs,Kn,Ti,U,Ve,Vt,Xt,Pt,oe,Ya,Ot,sr,le,ss,Ar,ht,L,K,us,Ss,nn,$n,Wa,vi,Qa,Ci,pa,yr,At,Ce,X,zr,Lr,St,Gn,Si,Ha,Dt,Wt,lr,Ai,$,It,_s,rr,cn,In,rs,ha,xt,it,Gt,hs,Lt,ze,a,dr,vs,Pi,hn,Ii,Mi,Ka,Vn,Ns,wr,De,Tn,Me,x]),v=()=>{u("/dashboard/my-designs")},g=()=>{u(globalThis.location.pathname+globalThis.location.search,{state:{designId:b,editExisting:!0,viewOnly:!1},replace:!0}),globalThis.location.reload()},T=ph(b,Kr,Ee,gr,x);return!T&&(ua||!b)?e.jsx(Ec,{}):e.jsx(dd.Provider,{value:h,children:e.jsxs("div",{className:"h-screen bg-white flex flex-col",children:[dt?e.jsx(bh,{navigateToMyDesigns:v,isStepTransitionRunning:qa,isProviderAvailable:dn,step:a,completedSteps:B,goToStep:Zr,isBeforeLeaveRunning:ls,switchToEditMode:g,wizardCopy:x}):e.jsx(Ch,{returnToCatalog:Qa,isStepTransitionRunning:qa,isProviderUnavailable:fr,isPersonalizationReviewMode:Re,wizardCopy:x,step:a,completedSteps:B,goToStep:Zr,isBeforeLeaveRunning:ls,isMockupPreparationPending:O,mockupProgress:ue,isSaving:R,isSavingTemplate:We,lastSaved:D,variantApplyNotice:Se,clearVariantApplyNotice:G,handleSaveDraft:no,draftId:b,isEditMode:Cs,setShowSaveTemplateModal:qr,openStoreModalAfterPreflight:ba,canPublish:fa,handleOpenDesignPreview:ao,isPreparingDesignPreview:ea,goToNextStep:Hn,nextStepLabel:Tl(Re,a,x),shareActions:e.jsx(ud,{shareLinks:Dn,isPreparationPending:O||ls||R,eligibility:$s,onOpenShareDialog:()=>On(!0)})}),e.jsx(md,{open:ca,onOpenChange:On,shareLinks:Dn,linkLifetimeDays:Zd,selectedMockupCount:da.count,selectedColorNames:da.colorNames,isPreparationPending:O||ls||R,prepareMockupsForShare:Va}),fr&&dt&&e.jsx(yh,{providerName:Ss??(Ce==null?void 0:Ce.providerName),wizardCopy:x}),fr&&!dt&&e.jsx(Vp,{providerName:Ss??(Ce==null?void 0:Ce.providerName),onChooseProvider:Ei}),e.jsxs("main",{className:`flex-1 min-h-0 overflow-hidden flex flex-col ${dt||Re||a==="designv1"?"":pd}`,children:[e.jsx(hh,{visible:Re,lineItemId:on,wizardCopy:x}),e.jsx(gh,{draftLoadError:T,onRetryInitialization:eo,wizardCopy:x,isPersonalizationReviewMode:Re,step:a,setVariantApplyNotice:be,setIsMockupPreparationPending:I,setMockupProgress:me,isBeforeLeaveRunning:ls,isStepTransitionRunning:qa,isSaving:R})]}),e.jsx(hd,{open:Aa,onOpenChange:Mn,onContinue:Ui,forceMockupRegenerationAt:Ta,isContinuing:Ra,registerBeforeContinue:fn}),e.jsx(xd,{open:M,onOpenChange:E,onSaveAndExit:xa,onDiscardAndExit:so,isSaving:R}),e.jsx(Mh,{showSaveTemplateModal:en,setShowSaveTemplateModal:qr,templateName:ir,setTemplateName:ts,isSavingTemplate:We,handleSaveAsTemplate:io,wizardCopy:x}),e.jsx(Ph,{showStoreSelectionModal:vr,setShowStoreSelectionModal:Jn,showUpdateStoreModal:Xe,setShowUpdateStoreModal:Sa,draftId:b,draftRevision:ye,designIdFromState:Bt,productDetails:ht,productName:K,productDescriptionHtml:ga,tags:qt==null?void 0:qt.tags,variantPricesForPublish:ei,providerId:us,selectedProvider:Ce,printingTechnology:Ar,brandingItemsForPublish:Li,selectedVariantColorsForPublish:Es,selectedVariantSizesForPublish:to,locationState:F,handlePublishSuccess:Di,productSlug:n,navigate:u})]})})},wf=()=>e.jsxs(Lc,{children:[e.jsx(Go,{path:":productSlug/:step",element:e.jsx(Ih,{})}),e.jsx(Go,{path:":productSlug",element:e.jsx(Dc,{to:"designv1",replace:!0})})]});
314export{wf as CustomizationForYourStores};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.