1import{j as e,a7 as h,C as vt,ab as A,a6 as Xe,T as p,o as _e,aP as Bt,I as te,aA as qt,at as Se,n as J,ar as Q,ac as V,X as wt,ai as St,Z as Ct,aq as Nt,O as Ht,N as pe,a9 as ne,a2 as me,Q as Ce,az as Wt,R as Ee,as as ve,G as Vt,ao as k,H as oe,S as Ut}from"./mui-CRsYZxVY.js";import{r as S,b as ue}from"./vendor-Dwao9eNC.js";import{b as xe,r as Gt,q as Xt,ax as Re,fU as Ze,iN as Zt,bS as Qt,b3 as Ue,ed as Z,hw as Kt,aA as Yt,aF as Jt,aw as Te,dt as eo,u as Et,m as to,w as G,t as Qe,l as Ke,eC as oo,dO as no,bY as ro,dz as io,bQ as so,bR as Ye,b8 as ao,bT as lo,bU as co,_ as It,bP as Je,iO as uo,d as Pt,N as ho,cc as et,ce as po,iP as mo,iQ as xo,cf as go,Y as fo,aN as bo,T as kt,fG as jo,e as Rt,bX as yo,bd as _o,c0 as vo,J as wo,p as So,x as Co,ew as Eo,iR as Io,v as Po,K as ko,eD as Ro,fV as To,bB as Lo,iS as Ao,eo as Oo}from"./index-TALscxEc.js";import{u as Do}from"./useProduct-BltDnkHr.js";import{v as $o,a as Mo,V as Fo,t as Le,f as zo}from"./useUploadProductVideo-BWu3vmGD.js";import{Z as Bo}from"./index-DK05pnC7.js";import{y as Ae}from"./yarlDarkStyles-BLdNgtCT.js";import{aO as qo,aP as No,O as Ho,V as Tt,aQ as tt,b as He,M as Wo,C as Vo,e as ot,d as Lt,aR as Oe,aS as Uo,aT as Go,aU as Xo,E as Zo}from"./icons-D8aatgQ4.js";import{d as Qo}from"./Edit-BiqqVQWD.js";import{u as Ko}from"./useDeleteProducts-iKMbBu96.js";import{a as Yo,b as Jo,u as en}from"./query-8ViTdhdk.js";import{P as tn}from"./ProductAvatar-BTM6y7KS.js";import{S as on}from"./StatusDotLine-CR-EBrxL.js";import{u as nn}from"./useComboDefinitions-DJhxSNVU.js";import{t as rn,l as sn,m as an}from"./comboCart-DscpHqAi.js";import{u as ln}from"./useProductVariations-zMUBu_ll.js";import{S as cn}from"./StockChip-B81FVTrG.js";import{u as dn}from"./useEditProduct-D1wHpcZy.js";import{S as un}from"./StockControlDialog-ni4AuJhT.js";import{u as hn}from"./useEditVariation-CPM2Wx9Q.js";import{a as nt,S as pn}from"./StarRating-DwFdQkkj.js";import{u as mn}from"./useProductSales-B8pUQ5_J.js";import{d as xn}from"./ExpandLess-C1pgA_h3.js";import{u as At,P as Ot}from"./PriceTableOverrideDialog-Ctk-3Sdd.js";import{u as gn}from"./useProductDigitalAsset-Xa_TOtN3.js";import"./datePickers-BIJXYOKG.js";import"./lab-DSem1Osk.js";(function(){try{var o=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};o.SENTRY_RELEASE={id:"2ad85febf9735404429b0670d4acf56a0af5a0a2"}}catch{}})();try{(function(){var o=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new o.Error().stack;t&&(o._sentryDebugIds=o._sentryDebugIds||{},o._sentryDebugIds[t]="b3c90515-34b9-4b62-923c-2be1ed055755",o._sentryDebugIdIdentifier="sentry-dbid-b3c90515-34b9-4b62-923c-2be1ed055755")})()}catch{}const Dt="#f8f8f8",fn=300,De={xs:64,md:72},bn={container:{backgroundColor:"transparent","--yarl__button_filter":"none","--yarl__color_button":"#c4c4c4","--yarl__color_button_active":"#8f8f8f","--yarl__color_button_disabled":"transparent"}},jn={...Ae,navigationPrev:{...Ae.navigationPrev,width:"60px",height:"60px",fontSize:"24px"},navigationNext:{...Ae.navigationNext,width:"60px",height:"60px",fontSize:"24px"}},$t=S.memo(({src:o,placeholder:t,alt:r,onClick:s})=>{const[u,c]=S.useState(!1),[i,d]=S.useState(!1),[a,l]=S.useState(!1),[n,y]=S.useState(!1);return e.jsxs(h,{onClick:s,sx:{position:"relative",width:"100%",height:"100%",backgroundColor:Dt,cursor:s?"zoom-in":"default"},children:[t&&!i&&e.jsx(h,{component:"img",src:t,alt:"","aria-hidden":!0,draggable:!1,onLoad:()=>c(!0),onError:()=>d(!0),sx:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"contain",opacity:u?1:0,transition:"opacity 150ms ease"}}),!n&&e.jsx(h,{component:"img",src:o,alt:r,draggable:!1,onLoad:()=>l(!0),onError:()=>y(!0),sx:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"contain",opacity:a?1:0,transition:"opacity 250ms ease"}})]})});$t.displayName="LQIPSlide";const yn=({images:o,video:t,productName:r,userPlan:s,getPlanUpgradeText:u})=>{const c=vt(),i=xe(),{triggerPaywall:d}=Gt(),[a,l]=S.useState(0),[n,y]=S.useState(!1),[w,m]=S.useState(!1),b=S.useRef(null),E=S.useRef(null),R=Xt[s].imagesPerProduct,j=t??null,D=(j==null?void 0:j.status)==="processing",C=(j==null?void 0:j.status)==="error",I=j&&!D&&!C?j:null,_=j?$o(j):null,B=!!j,g=I?Mo(I):null,[$,H]=S.useState("16 / 9"),z=!!I;S.useEffect(()=>{if(!_||!z)return;const f=new Image;return f.onload=()=>
1{f.naturalWidth>0&&f.naturalHeight>0&&H(`${f.naturalWidth} / ${f.naturalHeight}`)},f.src=_,()=>{f.onload=null}},[_,z]);const F=S.useMemo(()=>R===1/0?o:o.slice(0,R),[o,R]),U=o.length-F.length,v=S.useMemo(()=>{const f=M=>({type:"image",original:Te(M,{width:2560,height:2560}),thumbnail:Te(M,{width:200,height:200}),placeholder:Te(M,{width:400,height:400})}),P=[];F.length>0&&P.push(f(F[0])),B&&P.push({type:"video",original:_??"",thumbnail:_??""});for(let M=1;M<F.length;M++)P.push(f(F[M]));return P},[F,B,_]),O=v.length>1,T=Math.min(a,Math.max(0,v.length-1)),W=v[T],Ie=(W==null?void 0:W.type)==="video";S.useEffect(()=>{a>0&&a>=v.length&&l(Math.max(0,v.length-1))},[a,v.length]);const re=S.useMemo(()=>v.map(f=>({src:f.original,placeholder:f.placeholder,isVideo:f.type==="video"})),[v]),{modalSlides:ie,toModalIndex:se,toInlineIndex:Pe}=S.useMemo(()=>{const f=[],P={},M={};return v.forEach((x,L)=>{x.type==="image"&&(P[L]=f.length,M[f.length]=L,f.push({src:x.original}))}),{modalSlides:f,toModalIndex:P,toInlineIndex:M}},[v]);S.useEffect(()=>{n&&se[T]===void 0&&y(!1)},[n,se,T]);const ge=S.useRef(!1);if(S.useEffect(()=>{var P;if(!ge.current){ge.current=!0;return}if(!O||n)return;const f=(P=b.current)==null?void 0:P.children[T];f==null||f.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})},[T,O,n]),v.length===0)return e.jsx("img",{src:Re,alt:r,style:{width:"100%",height:"auto",maxHeight:"300px",objectFit:"contain",borderRadius:"8px"}});const ke=e.jsxs(h,{onPointerDownCapture:f=>{E.current={x:f.clientX,y:f.clientY}},onClickCapture:f=>{var M,x;const P=E.current;E.current=null,!((x=(M=f.target).closest)!=null&&x.call(M,".yarl__button"))&&P&&Math.hypot(f.clientX-P.x,f.clientY-P.y)>10&&f.stopPropagation()},sx:{position:"relative",borderRadius:"8px",overflow:"hidden",bgcolor:"background.paper"},children:[e.jsx(Ze,{plugins:[Zt],slides:re,index:T,on:{view:({index:f})=>{f!==T&&l(f)}},carousel:{imageFit:"contain",finite:!0,spacing:0,padding:0},inline:{style:{width:"100%",height:fn,margin:0,cursor:Ie?I?"pointer":"default":"zoom-in"}},render:{buttonPrev:O?void 0:()=>null,buttonNext:O?void 0:()=>null,slide:({slide:f,offset:P})=>{const M=f,x=P===0;return M.isVideo?e.jsxs(h,{onClick:x&&I?()=>m(!0):void 0,sx:{position:"relative",width:"100%",height:"100%",bgcolor:"common.black",cursor:I?"pointer":"default","&:hover .ppi-play-button":{backgroundColor:"rgba(0, 0, 0, 0.8)"}},children:[!!f.src&&e.jsx(h,{component:"img",src:f.src,alt:"",draggable:!1,onError:L=>{L.currentTarget.style.visibility="hidden"},sx:{width:"100%",height:"100%",objectFit:"contain",opacity:I?1:.45}}),I?e.jsx(h,{className:"ppi-play-button",sx:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",backgroundColor:"rgba(0, 0, 0, 0.6)",borderRadius:"50%",width:72,height:72,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none",transition:"background-color 0.2s ease-in-out"},children:e.jsx(qo,{sx:{color:"white",fontSize:44}})}):e.jsxs(A,{spacing:1,alignItems:"center",sx:{position:"absolute",inset:0,justifyContent:"center",px:3,textAlign:"center",color:"common.white",pointerEvents:"none"},children:[D&&e.jsx(Xe,{size:28,sx:{color:"common.white"}}),e.jsx(p,{variant:"body2",fontWeight:600,children:D?"Processando vÃdeo":"Não foi possÃvel processar o vÃdeo"}),e.jsx(p,{variant:"caption",sx:{opacity:.85},children:D?"Ele aparece na sua loja assim que ficar pronto":"Edite o produto para enviar outro"})]})]}):e.jsx($t,{src:f.src,placeholder:M.placeholder,alt:r,onClick:x?()=>y(!0):void 0},f.src)}},styles:bn}),O&&e.jsxs(h,{sx:{position:"absolute",top:12,left:12,backgroundColor:"rgba(0, 0, 0, 0.6)",color:"white",borderRadius:"6px",padding:"4px 8px",fontSize:13,fontWeight:500,lineHeight:1.2,zIndex:2,pointerEvents:"none"},children:[T+1,"/",v.length]})]}),fe=O?e.jsx(h,{ref:b,sx:{display:"flex",flexDirection:"row",gap:1,p:"3px",width:"fit-content",maxWidth:"100%",mx:"auto",overflowX:"auto",scrollbarWidth:"none","&::-webkit-scrollbar":{display:"none"}},children:v.map((f,P)=>{const M=P===T,x=v.slice(0,P+1).filter(L=>L.type==="image").length;return e.jsxs(h,{onClick:()=>l(P),role:"button",tabIndex:0,"aria-label":f.type==="video"?"VÃdeo do produto":`Imagem ${x} de ${r}`,"aria-current":M,onKeyDown:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),l(P))}
1,sx:{position:"relative",width:De,height:De,minWidth:De,flexShrink:0,borderRadius:`${Qt}px`,overflow:"hidden",cursor:"pointer",backgroundColor:Dt,outlineStyle:"solid",outlineWidth:"2px",outlineOffset:0,outlineColor:M?c.palette.primary.main:"transparent",transition:"outline-color .18s ease","&:hover":{outlineColor:M?c.palette.primary.main:_e(c.palette.primary.main,.4)}},children:[e.jsx(h,{component:"img",src:f.thumbnail||Re,alt:"",draggable:!1,loading:"lazy",onError:L=>{L.currentTarget.src=Re},sx:{width:"100%",height:"100%",objectFit:"cover"}}),f.type==="video"&&e.jsx(h,{sx:{position:"absolute",inset:0,backgroundColor:"rgba(255, 255, 255, 0.5)",display:"flex",alignItems:"center",justifyContent:"center"},children:D?e.jsx(Xe,{size:20,sx:{color:"primary.main"}}):e.jsx(No,{sx:{color:"primary.main",fontSize:28}})})]},`${f.thumbnail}-${P}`)})}):null;return e.jsxs(h,{children:[e.jsxs(h,{sx:{display:"flex",flexDirection:"column",gap:1.5},children:[e.jsx(h,{sx:{width:"100%",minWidth:0},children:ke}),fe&&e.jsx(h,{sx:{width:"100%",minWidth:0},children:fe})]}),U>0&&e.jsxs(Ue,{severity:"warning",sx:{mt:1.5},onClick:()=>d("product_images_view",{pageAction:()=>i("/profile/paywall"),source:"product_page"}),children:[Z(U)," ",U===1?"imagem oculta":"imagens ocultas"," devido à limitação do seu plano atual (",Z(R)," ","imagens por produto). ",u()]}),e.jsx(Fo,{open:w,onClose:()=>m(!1),embedUrl:g,aspect:$}),e.jsx(Ze,{open:n,close:()=>y(!1),index:se[T]??0,slides:ie,plugins:[Bo],noScroll:{disabled:!0},carousel:{finite:!0},zoom:{maxZoomPixelRatio:3,doubleClickMaxStops:1},on:{view:({index:f})=>{const P=Pe[f];P!==void 0&&P!==a&&l(P)}},controller:{closeOnBackdropClick:!0,closeOnPullDown:!0,closeOnPullUp:!0},render:{iconClose:()=>e.jsx(Kt,{size:24}),iconPrev:()=>e.jsx(Yt,{size:28}),iconNext:()=>e.jsx(Jt,{size:28})},styles:jn})]})};var Ge={},_n=Bt;Object.defineProperty(Ge,"__esModule",{value:!0});var Mt=Ge.default=void 0,vn=_n(eo()),wn=e;Mt=Ge.default=(0,vn.default)((0,wn.jsx)("path",{d:"M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12zm-1 4 6 6v10c0 1.1-.9 2-2 2H7.99C6.89 23 6 22.1 6 21l.01-14c0-1.1.89-2 1.99-2zm-1 7h5.5L14 6.5z"}),"FileCopy");const Sn=async(o,t,r)=>{const{data:s,error:u}=await G.from("produto_personalizacao_campo").select("id").eq("produto_id",t).eq("user_id",r).is("deletado_em",null).limit(1);if(u)throw u;if(s&&s.length>0)return;const{data:c,error:i}=await G.from("produto_personalizacao_campo").select("label, tipo, obrigatorio, max_caracteres, helper_text, opcoes, ordem").eq("produto_id",o).eq("user_id",r).is("deletado_em",null).order("ordem",{ascending:!0});if(i)throw i;if(!c||c.length===0)return;const d=c.map(l=>({produto_id:t,user_id:r,label:l.label,tipo:l.tipo,obrigatorio:l.obrigatorio,max_caracteres:l.max_caracteres,helper_text:l.helper_text,opcoes:l.opcoes,ordem:l.ordem})),{error:a}=await G.from("produto_personalizacao_campo").insert(d);if(a)throw a},Cn=async(o,t,r)=>{const{data:s,error:u}=await G.from("produto").select("combo, combo_nf_modo").eq("id",o).single();if(u)throw u;if(!(s!=null&&s.combo))return;const{data:c,error:i}=await G.from("produto_combo_item").select("id").eq("combo_produto_id",t).limit(1);if(i)throw i;const{error:d}=await G.from("produto").update({combo:!0,controlar_estoque:!1,combo_nf_modo:s.combo_nf_modo??"detalhado"}).eq("id",t).eq("user_id",r);if(d)throw d;if(c&&c.length>0)return;const{data:a,error:l}=await G.from("produto_combo_item").select("produto_id, produto_variacao_id, quantidade, ordem").eq("combo_produto_id",o).order("ordem",{ascending:!0}).order("id",{ascending:!0});if(l)throw l;if(!a||a.length===0)return;const{error:n}=await G.from("produto_combo_item").insert(a.map(y=>({combo_produto_id:t,user_id:r,produto_id:y.produto_id,produto_variacao_id:y.produto_variacao_id,quantidade:y.quantidade,ordem:y.ordem})));if(n)throw n},En=()=>{const o=Yo(),{user:t}=Et(),{triggerRevalidation:r}=to();return Jo({mutationFn:async s=>{const{data:u,error:c}=await G.rpc("duplicate_product",{product_id_param:s});if(c)throw c;const i=u;if(t!=null&&t.id&&(i!=null&&i.new_product_id)){try{await Cn(s,i.new_product_id,t.id)}catch(d){console.error("Failed to copy combo definition on duplicate:",d),Qe(Ke.PRODUCT.DUPLICATE_COMBO_COPY_ERROR,{source_product_id:s,new_product_id:i==null?void 0:i.new_product_id,error:d instanceof Error?d.message:String(d)})}try{await Sn(s,i.new_product_id,t.id)}catch(d){console.error("Failed to copy personalization fields on product duplicate:",d),Qe(Ke.PRODUCT.DUPLICATE_PERSONALIZATION_COPY_ERROR,{source_product_id:s,new_product_id:i==null?void 0:i.new_product_id,error:d instanceof Error?d.message:String(d)})}}return i},onSuccess:()=>{o.invalidateQueries({queryKey:["products"]}),o.invalidateQueries({queryKey:["combo-definitions"]}),r()}})},In=({productId:o,variationCount:t=0})=>{const r=xe(),[s,u]=S.useState(null),c=!!s,[i,d]=S.useState(!1),[a,l]=S.useState(null),{mutateAsync:n,isPending:y}=Ko(),{mutateAsync:w,isPending:m}=En(),b=I=>{u(I.currentTarget)},E=()=>{u(null)},R=()=>{r("edit",{replace:!0})},j=()=>{d(!0)},D=async()=>{try{await n({ids:[parseInt(o)]},{onSuccess:()=>{r("/products")}})}
1catch(I){l((I==null?void 0:I.message)||"Erro ao excluir o produto")}d(!1)},C=async()=>{const I=await w(parseInt(o));r(`/products/${I.new_product_id}/`),E()};return e.jsxs(e.Fragment,{children:[e.jsx(te,{color:"inherit",onClick:b,children:e.jsx(oo,{})}),e.jsx(qt,{open:!!a,autoHideDuration:6e3,onClose:()=>l(null),anchorOrigin:{vertical:"bottom",horizontal:"center"},children:e.jsx(h,{children:e.jsx(Ue,{severity:"warning",onClose:()=>l(null),children:a})})}),e.jsxs(Se,{id:"product-options-menu",anchorEl:s,open:c,onClose:E,MenuListProps:{"aria-labelledby":"basic-button"},children:[e.jsxs(J,{disabled:m,onClick:C,children:[e.jsx(Q,{children:e.jsx(Mt,{})}),e.jsx(V,{primary:"Duplicar"})]}),e.jsxs(J,{disabled:y,onClick:()=>{R(),E()},children:[e.jsx(Q,{children:e.jsx(Qo,{})}),e.jsx(V,{primary:"Editar"})]}),null,e.jsxs(J,{disabled:y,onClick:()=>{j(),E()},children:[e.jsx(Q,{children:e.jsx(no,{})}),e.jsx(V,{primary:"Excluir"})]})]}),e.jsxs(wt,{open:i,onClose:()=>d(!1),"aria-labelledby":"alert-dialog-title","aria-describedby":"alert-dialog-description",children:[e.jsx(St,{id:"alert-dialog-title",children:"Confirmar exclusão?"}),e.jsx(Ct,{children:e.jsx(Nt,{id:"alert-dialog-description",children:"Tem certeza de que deseja excluir este produto? Esta ação não pode ser desfeita."})}),e.jsxs(Ht,{children:[e.jsx(pe,{onClick:()=>d(!1),color:"primary",children:"Cancelar"}),e.jsx(pe,{onClick:D,color:"primary",autoFocus:!0,children:"Confirmar"})]})]})]})};function Pn({comboProductId:o,sx:t}){const r=xe(),{data:s,isLoading:u}=nn(),{data:c=[],isLoading:i}=ro(),d=u||i,a=(s==null?void 0:s.get(o))??[],l=S.useMemo(()=>{const w=new Map;return c.forEach(m=>w.set(m.id,rn(m))),w},[c]),n=S.useMemo(()=>{const w=new Map;return c.forEach(m=>w.set(m.id,m)),w},[c]),y=sn(a,l);return e.jsxs(ne,{sx:t,children:[e.jsxs(h,{sx:{p:2,pb:1},children:[e.jsxs(A,{direction:"row",justifyContent:"space-between",alignItems:"center",children:[e.jsx(p,{variant:"subtitle1",fontWeight:500,children:"Produtos do combo"}),e.jsx(pe,{size:"small",onClick:()=>r(`/products/${o}/edit-combo`),children:"Editar combo"})]}),d?e.jsx(p,{variant:"caption",color:"text.secondary",children:"Carregando..."}):e.jsx(on,{tone:y.summary.tone,label:y.summary.label,detail:y.summary.detail})]}),e.jsx(me,{}),e.jsx(Ce,{disablePadding:!0,children:a.map(w=>{var B,g;const m=l.get(w.produto_id),b=n.get(w.produto_id),E=y.stateByItemId.get(w.id),R=an(E),j=io(w,m),D=j==="fixed_variation"?(B=m==null?void 0:m.variacoes.find($=>$.id===w.produto_variacao_id))==null?void 0:B.nome:null,C=j==="choice"?"Cliente escolhe a variação":D??null,I=E==="deleted",_=e.jsxs(e.Fragment,{children:[e.jsx(Wt,{sx:{minWidth:so(Ye)},children:e.jsx(tn,{imageUrl:(g=b==null?void 0:b.image_url)==null?void 0:g[0],size:Ye,alt:m==null?void 0:m.nome})}),e.jsx(V,{disableTypography:!0,sx:{my:0,minWidth:0},primary:e.jsxs(p,{component:"div",sx:{...ao,...lo(co)},children:[w.quantidade,"x"," ",(m==null?void 0:m.nome)??"Produto indisponÃvel"]}),secondary:C?e.jsx(p,{variant:"caption",color:"text.secondary",noWrap:!0,component:"div",children:C}):null}),R&&e.jsx(It,{label:R.label,tint:R.tint,sx:{ml:1,flexShrink:0}})]});return e.jsx(Ee,{disablePadding:!0,children:I?e.jsx(h,{sx:{display:"flex",alignItems:"center",width:"100%",minHeight:Je,p:"12px 16px",opacity:.6},children:_}):e.jsx(ve,{onClick:()=>r(`/products/${w.produto_id}`),sx:{minHeight:Je},children:_})},w.id)})})]})}function kn(o,t){const r=uo(t);return r?`/produto/${o}-${r}`:`/produto/${o}`}const Rn="#8865FE",Ft="Plus Jakarta Sans Variable";function Tn(o){var r,s,u,c;if(!(o!=null&&o.length))return[];const t=new Map;for(const i of o)if(!i.oculto)for(const d of i.valores||[]){const a=(s=(r=d.atributo)==null?void 0:r.nome)==null?void 0:s.trim(),l=(c=(u=d.atributo_valor)==null?void 0:u.valor)==null?void 0:c.trim();if(!a||!l)continue;let n=t.get(a);n||(n={values:[],seen:new Set},t.set(a,n)),n.seen.has(l)||(n.seen.add(l),n.values.push(l))}return Array.from(t.entries()).map(([i,d])=>({label:i,values:d.values}))}const X=1080,N=72,K=X-N*2,ce=1080,rt=48,$e=56,Ln=56,An=40,it=30,be=28,je=48,st=56,Me=66,On=2,at=30,lt=42,ct=36,ee=70,Fe=36,dt=30,ye=36,We=31,ze=44,Dn=5,ut=36,$n=26,ht=36,de=54,Ve=27,zt=22,we=12,pt=18,Mn=2,Fn=56,mt="#041E42",Y="#8A8F98",zn="#5F6368",xt="#ECECEC",Bn="#3A3F47",gt=o=>
1o.toLocaleString("pt-BR",{style:"currency",currency:"BRL"});function qn(o){if(!o)return"";try{return(new DOMParser().parseFromString(o,"text/html").body.textContent||"").replace(/\s+/g," ").trim()}catch{return o.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim()}}function ft(o){let t=o.trim().replace(/^#/,"");return t.length===3&&(t=t.split("").map(r=>r+r).join("")),/^[0-9a-fA-F]{6}$/.test(t)?{r:parseInt(t.slice(0,2),16),g:parseInt(t.slice(2,4),16),b:parseInt(t.slice(4,6),16)}:null}function Nn({r:o,g:t,b:r}){const s=u=>{const c=u/255;return c<=.03928?c/12.92:((c+.055)/1.055)**2.4};return .2126*s(o)+.7152*s(t)+.0722*s(r)}function bt({r:o,g:t,b:r},s=1){return s>=1?`rgb(${o}, ${t}, ${r})`:`rgba(${o}, ${t}, ${r}, ${s})`}function Hn(o){let t={...o},r=0;for(;1.05/(Nn(t)+.05)<3&&r<14;)t={r:Math.round(t.r*.85),g:Math.round(t.g*.85),b:Math.round(t.b*.85)},r+=1;return t}function jt(o){return new Promise(t=>{if(!o)return t(null);const r=new Image;r.crossOrigin="anonymous";let s=!1;const u=c=>{s||(s=!0,t(c))};r.onload=()=>u(r),r.onerror=()=>u(null),r.src=o,setTimeout(()=>u(null),8e3)})}async function Wn(o){const t=document.fonts;if(t!=null&&t.load)try{await Promise.race([Promise.all([t.load(`400 ${We}px "${o}"`),t.load(`500 ${Ve}px "${o}"`),t.load(`700 ${ee}px "${o}"`)]),new Promise(r=>setTimeout(r,2500))])}catch{}}function q(o,t,r){return`${o} ${t}px "${r}", "${Ft}", sans-serif`}function he(o,t,r){if(o.measureText(t).width<=r)return t;const s="â¦";let u=0,c=t.length;for(;u<c;){const i=Math.ceil((u+c)/2);o.measureText(t.slice(0,i)+s).width<=r?u=i:c=i-1}return t.slice(0,u).trimEnd()+s}function yt(o,t,r,s){const u=t.split(/\s+/).filter(Boolean),c=[];let i="";for(const l of u){const n=i?`${i} ${l}`:l;o.measureText(n).width<=r||!i?i=n:(c.push(i),i=l)}if(i&&c.push(i),c.length<=s)return c;const d=c.slice(0,s),a=c.slice(s-1).join(" ");return d[s-1]=he(o,a,r),d}function Vn(o,t,r){const s=d=>Math.round(o.measureText(d).width)+zt*2,u=[];let c=0,i=0;for(;i<t.length;i+=1){const d=s(t[i]),a=u.length?we+d:d;if(c+a>r)break;u.push({label:t[i],width:d}),c+=a}if(i<t.length){let d=t.length-u.length;const a=()=>`+${d}`;let l=s(a());for(;u.length&&c+we+l>r;){const n=u.pop();c-=we+n.width,d+=1,l=s(a())}u.push({label:a(),width:l,overflow:!0})}return u}function Un(o,t,r,s,u,c){const i=Math.min(c,s/2,u/2);o.beginPath(),o.moveTo(t+i,r),o.arcTo(t+s,r,t+s,r+u,i),o.arcTo(t+s,r+u,t,r+u,i),o.arcTo(t,r+u,t,r,i),o.arcTo(t,r,t+s,r,i),o.closePath()}function Gn(o,t,r,s,u,c,i){const d=t.width/t.height,a=u/c;if(i==="cover"){let l=t.width,n=t.height;d>a?l=t.height*a:n=t.width/a;const y=(t.width-l)/2,w=(t.height-n)/2;o.drawImage(t,y,w,l,n,r,s,u,c)}else{let l=u,n=c;d>a?n=u/d:l=c*d,o.drawImage(t,r+(u-l)/2,s+(c-n)/2,l,n)}}async function Xn(o,t){var U;const r=t.fontFamily||Ft,s=ft(t.brandColor)||ft(Rn)||{r:136,g:101,b:254},u=bt(Hn(s)),c=bt(s,.1),i=t.imageFit||"contain";await Wn(r);const[d,a]=await Promise.all([jt(o.imageUrl),jt(t.logoUrl)]),l=document.createElement("canvas");l.width=X,l.height=10;const n=l.getContext("2d");if(!n)throw new Error("Canvas 2D context unavailable");n.font=q(700,st,r);const y=yt(n,o.nome||"",K,On);let w="";o.categoria&&(n.font=q(500,at,r),w=he(n,o.categoria,K));const m=qn(o.descricao);let b=[];m&&(n.font=q(400,We,r),b=yt(n,m,K,Dn));const E=(o.variationGroups||[]).slice(0,Mn),R=[];n.font=q(500,Ve,r);for(const v of E)v.values.length&&R.push({label:v.label,chips:Vn(n,v.values,K)});const j=typeof o.precoCheio=="number"&&o.precoCheio>o.preco,D=!!d;let C=rt+$e+be+1;if(C+=D?be+ce+je:je,C+=y.length*Me,w&&(C+=8+lt),C+=ct+ee,b.length&&(C+=ye+b.length*ze),R.length){C+=b.length?ut:ye;for(let v=0;v<R.length;v+=1)v>0&&(C+=pt),C+=ht+4+de}C+=Fn;const I=Math.round(C);l.height=I,n.textBaseline="top",n.fillStyle="#FFFFFF",n.fillRect(0,0,X,I);let _=rt;const B=_+$e/2;let g=0;const $=(U=t.storeUrlDisplay)==null?void 0:U.trim();$&&(n.font=q(500,it,r),g=Math.min(Math.ceil(n.measureText($).width)+2,Math.round(K*.5)));const H=K-(g?g+32:0);if(n.textBaseline="middle",a){const v=a.width/a.height;let O=Ln,T=O*v;T>H&&(T=H,O=T/v),n.drawImage(a,N,B-O/2,T,O)}else n.fillStyle=mt,n.font=q(700,An,r),n.fillText(he(n,t.storeName||"",H),N,B+1);if($&&(n.fillStyle=Y,n.font=q(500,it,r),n.textAlign="right",n.fillText(he(n,$,g),X-N,B+1),n.textAlign="left"),n.textBaseline="top",_+=$e+be,n.fillStyle=xt,n.fillRect(N,_,K,1),_+=1,d){_+=be;const v=_;n.fillStyle="#FFFFFF",n.fillRect(0,v,X,ce),Gn(n,d,0,v,X,ce,i),n.fillStyle=xt,n.fillRect(0,v+ce-1,X,1),_=v+ce+je}else _+=je;
1n.fillStyle=mt,n.font=q(700,st,r),y.forEach((v,O)=>{n.fillText(v,N,_+O*Me)}),_+=y.length*Me,w&&(_+=8,n.fillStyle=Y,n.font=q(500,at,r),n.fillText(w,N,_),_+=lt),_+=ct,n.fillStyle=u,n.font=q(700,ee,r);const z=gt(o.preco);n.fillText(z,N,_);let F=N+Math.round(n.measureText(z).width)+24;if(j&&typeof o.precoCheio=="number"){const v=_+(ee-Fe)-6;n.fillStyle=Y,n.font=q(500,Fe,r);const O=gt(o.precoCheio),T=Math.round(n.measureText(O).width);n.fillText(O,F,v);const W=v+Fe*.55;n.strokeStyle=Y,n.lineWidth=3,n.beginPath(),n.moveTo(F,W),n.lineTo(F+T,W),n.stroke(),F+=T+24}if(o.sku){n.fillStyle=Y,n.font=q(500,dt,r);const v=X-N-F-16;if(v>80){const O=he(n,`COD. ${String(o.sku).toUpperCase()}`,v);n.textAlign="right",n.fillText(O,X-N,_+(ee-dt)-6),n.textAlign="left"}}return _+=ee,b.length&&(_+=ye,n.fillStyle=zn,n.font=q(400,We,r),b.forEach((v,O)=>{n.fillText(v,N,_+O*ze)}),_+=b.length*ze),R.length&&(_+=b.length?ut:ye,R.forEach((v,O)=>{O>0&&(_+=pt),n.fillStyle=Y,n.font=q(500,$n,r),n.fillText(v.label,N,_),_+=ht+4;let T=N;v.chips.forEach(W=>{n.fillStyle=c,Un(n,T,_,W.width,de,de/2),n.fill(),n.fillStyle=W.overflow?Y:Bn,n.font=q(500,Ve,r),n.textBaseline="middle",n.fillText(W.label,T+zt,_+de/2+1),n.textBaseline="top",T+=W.width+we}),_+=de})),l.toDataURL("image/png")}const Zn=o=>o.replace(/^https?:\/\//i,"").replace(/\/+$/,""),Be={py:1.5,transition:"background-color 0.1s ease","&:active":{bgcolor:"action.selected"}},qe={minWidth:44,color:"primary.main"},Qn=({product:o,variations:t})=>{const{data:r}=Pt(),{storeUrl:s}=ho(),{isSharing:u,runShare:c}=et(),{isSharing:i,runShare:d}=et(),a=S.useMemo(()=>s?`${s}${kn(o.id,o.nome)}`:"",[s,o.id,o.nome]),l=S.useMemo(()=>{var b,E;return{nome:o.nome||"",descricao:o.descricao,preco:o.preco,precoCheio:o.preco_cheio??null,sku:o.sku??null,imageUrl:((b=o.image_url)==null?void 0:b[0])??null,categoria:((E=o.categoria)==null?void 0:E.nome)??null,variationGroups:Tn(t)}},[o,t]),n=S.useMemo(()=>r?{storeName:r.nome_loja,storeUrlDisplay:Zn(s||""),brandColor:r.cor_principal||"#8865FE",fontFamily:r.fonte||"Plus Jakarta Sans Variable",logoUrl:r.logo_url??null,imageFit:r.imagem_produto_fit||"contain"}:null,[r,s]),y=()=>{a&&window.open(a,"_blank")},w=()=>d(async()=>{let b=null;if(n)try{b=await Xn(l,n)}catch(E){console.error("Error generating product share image:",E)}await xo({dataUrl:b,fileName:`produto-${Date.now()}.png`,text:o.nome?`${o.nome} 2${a}`:a,url:a,title:"Compartilhar produto"})}),m=()=>c(()=>go({url:a,title:"Compartilhar produto"}));return r?e.jsxs(ne,{children:[e.jsxs(ve,{onClick:y,sx:Be,children:[e.jsx(Q,{sx:qe,children:e.jsx(Ho,{fontSize:"small"})}),e.jsx(V,{primary:"Ver na loja",primaryTypographyProps:{fontWeight:500}})]}),e.jsx(me,{}),e.jsxs(ve,{onClick:m,disabled:u,sx:Be,children:[e.jsx(Q,{sx:qe,children:e.jsx(po,{size:20})}),e.jsx(V,{primary:"Compartilhar",primaryTypographyProps:{fontWeight:500}})]}),e.jsx(me,{}),e.jsxs(ve,{onClick:w,disabled:i,sx:Be,children:[e.jsx(Q,{sx:qe,children:e.jsx(mo,{size:20})}),e.jsx(V,{primary:"Compartilhar como imagem",primaryTypographyProps:{fontWeight:500}})]})]}):null};function Kn(o){return fo({tag:"svg",attr:{viewBox:"0 0 1024 1024"},child:[{tag:"path",attr:{d:"M120 160H72c-4.4 0-8 3.6-8 8v688c0 4.4 3.6 8 8 8h48c4.4 0 8-3.6 8-8V168c0-4.4-3.6-8-8-8zm833 0h-48c-4.4 0-8 3.6-8 8v688c0 4.4 3.6 8 8 8h48c4.4 0 8-3.6 8-8V168c0-4.4-3.6-8-8-8zM200 736h112c4.4 0 8-3.6 8-8V168c0-4.4-3.6-8-8-8H200c-4.4 0-8 3.6-8 8v560c0 4.4 3.6 8 8 8zm321 0h48c4.4 0 8-3.6 8-8V168c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v560c0 4.4 3.6 8 8 8zm126 0h178c4.4 0 8-3.6 8-8V168c0-4.4-3.6-8-8-8H647c-4.4 0-8 3.6-8 8v560c0 4.4 3.6 8 8 8zm-255 0h48c4.4 0 8-3.6 8-8V168c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v560c0 4.4 3.6 8 8 8zm-79 64H201c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8h112c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8zm257 0h-48c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8h48c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8zm256 0H648c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8h178c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8zm-385 0h-48c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8h48c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8z"},child:[]}]})(o)}const Ne=({variation:o,stockAmount:t,productStockEnabled:r,onStockClick:s,onEditClick:u})=>{const c=vt(),i=Vt(c.breakpoints.up("sm")),[d,a]=ue.useState(null),l=!!d,n=j=>{j.stopPropagation(),a(j.currentTarget)},y=()=>{a(null)},w=j=>{j&&j.stopPropagation(),y(),s(o)},m=j=>{j&&j.stopPropagation(),y(),u(o)},b=j=>bo(j.valores),E=(j,D,C=0)=>D?{text:"Estoque ilimitado",color:"text.secondary"}:!j||j<=0?{text:"Sem estoque",color:"error.main"}:j<=C?{text:`Estoque baixo (${j})`,color:"warning.main"}:{text:`Estoque: ${j}`,color:"text.secondary"},R=(j,D,C=0,I)=>{const _=E(j,D,C);return e.jsxs(A,{spacing:.25,children:[e.jsx(p,{variant:"caption",sx:{color:_.color,fontSize:"0.75rem",fontWeight:500},children:_.text}),I!=null&&e.jsxs(p,{variant:"caption",sx:{color:"text.secondary"}
2,children:["Custo médio:"," ",I.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})]})]})};return e.jsxs(Ee,{children:[o.image_url&&e.jsx(h,{sx:{width:48,height:48,mr:2,borderRadius:1,overflow:"hidden",flexShrink:0,border:1,borderColor:"grey.300"},children:e.jsx(h,{component:"img",src:o.image_url,alt:b(o),sx:{width:"100%",height:"100%",objectFit:"cover"}})}),e.jsx(V,{primary:e.jsxs(A,{direction:"row",spacing:1,alignItems:"center",sx:{color:o.oculto?"text.disabled":"text.primary"},children:[e.jsx(p,{variant:"body2",sx:{fontSize:"1rem",fontWeight:500},children:b(o)}),o.oculto&&e.jsx(Tt,{sx:{fontSize:16}})]}),secondary:e.jsxs(A,{spacing:.75,sx:{mt:.5},children:[o.preco_cheio?e.jsxs(A,{direction:"row",spacing:1,alignItems:"center",children:[e.jsx(p,{variant:"body2",sx:{color:o.oculto?"text.disabled":"text.secondary",textDecoration:"line-through",fontSize:"0.9rem"},children:o.preco_cheio.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})}),e.jsx(p,{variant:"body2",sx:{color:o.oculto?"text.disabled":"success.main",fontWeight:600},children:o.preco.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})}),!o.oculto&&e.jsx(It,{tint:"success",label:`${Math.round((o.preco_cheio-o.preco)/o.preco_cheio*100)}% OFF`})]}):e.jsx(p,{variant:"body2",sx:{fontWeight:500},color:"text.secondary",children:o.preco.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})}),!o.oculto&&R(t,!r||!o.controlar_estoque,o.estoque_minimo,r&&o.controlar_estoque?o.custo_medio_atual:void 0),(o.codigo_produto||o.codigo_de_barras)&&e.jsxs(h,{sx:{color:"text.disabled",fontSize:"0.75rem",fontFamily:"monospace",display:"flex",alignItems:"center",gap:.5,flexWrap:"wrap"},children:[o.codigo_produto&&e.jsxs(p,{component:"span",sx:{fontSize:"inherit",fontFamily:"inherit"},children:["CÃD: ",o.codigo_produto]}),o.codigo_produto&&o.codigo_de_barras&&e.jsx(p,{component:"span",sx:{fontSize:"inherit",fontFamily:"inherit"},children:"â¢"}),o.codigo_de_barras&&e.jsxs(h,{component:"span",sx:{display:"inline-flex",alignItems:"center",gap:.25},children:[e.jsx(Kn,{style:{fontSize:"0.75rem",flexShrink:0}}),e.jsx(p,{component:"span",sx:{fontSize:"inherit",fontFamily:"inherit",lineHeight:1},children:o.codigo_de_barras})]})]}),o.moq&&o.moq>1?e.jsxs(p,{variant:"caption",sx:{color:"text.secondary"},children:["Pedido mÃn: ",o.moq," un."]}):null]})}),i?e.jsxs(A,{direction:"row",spacing:1,children:[e.jsx(te,{onClick:w,sx:{color:"action.active"},title:"Editar estoque",children:e.jsx(tt,{})}),e.jsx(te,{onClick:m,sx:{color:"action.active"},title:"Editar variação",children:e.jsx(He,{})})]}):e.jsxs(e.Fragment,{children:[e.jsx(te,{onClick:j=>{j.stopPropagation(),n(j)},sx:{color:"action.active"},children:e.jsx(Wo,{})}),e.jsxs(Se,{anchorEl:d,open:l,onClose:y,anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[e.jsxs(J,{onClick:w,children:[e.jsx(Q,{children:e.jsx(tt,{fontSize:"small"})}),e.jsx(V,{children:"Gerenciar estoque"})]}),e.jsxs(J,{onClick:m,children:[e.jsx(Q,{children:e.jsx(He,{fontSize:"small"})}),e.jsx(V,{children:"Editar variação"})]})]})]})]})},Yn=(o,t,r,s)=>{const u={minimumFractionDigits:0,maximumFractionDigits:1},c={minimumFractionDigits:0,maximumFractionDigits:3},i=o.toLocaleString("pt-BR",u),d=t.toLocaleString("pt-BR",u),a=r.toLocaleString("pt-BR",u),l=s.toLocaleString("pt-BR",c);return`${i}cm x ${d}cm x ${a}cm x ${l}kg`},Jn=()=>e.jsxs(h,{sx:{position:"relative",padding:2},children:[e.jsx(kt,{navigateBack:!0,title:"Detalhes do produto",children:e.jsx(k,{variant:"circular",width:40,height:40})}),e.jsxs(A,{spacing:2,children:[e.jsx(k,{variant:"rectangular",width:"100%",height:300,sx:{borderRadius:"8px"}}),e.jsx(ne,{sx:{p:2},children:e.jsxs(A,{spacing:2,children:[e.jsxs(A,{spacing:1,children:[e.jsx(k,{variant:"text",width:"60%",height:32})," ",e.jsx(k,{variant:"text",width:"40%",height:20})," ",e.jsx(k,{variant:"text",width:"30%",height:40})," "]}),e.jsxs(A,{direction:"row",justifyContent:"space-between",alignItems:"center",children:[e.jsxs(h,{flex:1,children:[e.jsx(k,{variant:"text",width:"50%",height:20}),e.jsx(k,{variant:"text",width:"30%",height:20})]}),e.jsx(k,{variant:"circular",width:24,height:24})," "]}),e.jsxs(h,{children:[e.jsx(k,{variant:"text",width:"30%",height:16}),e.jsx(k,{variant:"text",width:"70%",height:20})]}),e.jsxs(h,{children:[e.jsx(k,{variant:"text",width:"40%",height:16}),e.jsx(k,{variant:"text",width:"50%",height:20})]}),e.jsxs(h,{children:[e.jsx(k,{variant:"text",width:"35%",height:16}),e.jsx(k,{variant:"text",width:"100%",height:20}),e.jsx(k,{variant:"text",width:"100%",height:20}),e.jsx(k,{variant:"text",width:"80%",height:20})]}),e.jsxs(h,{children:[e.jsx(k,{variant:"text",width:"30%",height:16}),e.jsx(k,{variant:"text",width:"60%",height:20})]})]})}),e.jsxs(oe,{elevation:1,sx:{p:1.5,display:"flex",justifyContent:"space-between",alignItems:"center",mt:2},children:[e.jsxs(h,{sx:{display:"flex",alignItems:"center",gap:1.5},children:[e.jsx(k,{variant:"rounded",width:32,height:32}),e.jsxs(h,{children:[e.jsx(k,{variant:"text",width:180,height:24}),e.jsx(k,{variant:"text",width:150,height:20})]})]}),e.jsx(k,{variant:"circular",width:24,height:24})," "]}),e.jsxs(ne,{sx:{mt:2},children:[e.jsx(h,{sx:{p:2,pb:1},children:e.jsxs(A,{direction:"row",justifyContent:"space-between",alignItems:"center",children:[e.jsx(k,{variant:"text",width:"40%",height:28})," ",e.jsx(k,{variant:"rectangular",width:120,height:36})," "]})}),e.jsx(me,{}),e.jsx(Ce,{disablePadding:!0,children:[1,2].map(o=>e.jsxs(Ee,{sx:{p:2,borderBottom:"1px solid rgba(0, 0, 0, 0.12)"},children:[e.jsxs(A,{spacing:1,flexGrow:1,children:[e.jsx(k,{variant:"text",width:"50%"}),e.jsx(k,{variant:"text",width:"30%"})]}),e.jsx(k,{variant:"circular",width:24,height:24})," "]},o))})]}),e.jsx(k,{variant:"rectangular",width:"100%",height:56,sx:{mt:2}})]})]}),er=({description:o,sanitizeHTML:t,expanded:r,onToggle:s})=>{const[u,c]=ue.useState(!1),i=r!==void 0?r:u,[d,a]=ue.useState(!1),l=ue.useRef(null),n=192,y=128;return ue.useLayoutEffect(()=>{if(l.current){const w=l.current.scrollHeight;a(w>n)}},[o,i]),e.jsx(h,{children:e.jsxs(h,{sx:{position:"relative",mt:.5},children:[e.jsxs(h,{ref:l,sx:{maxHeight:!i&&d?`${y}px`:"none",overflow:!i&&d?"hidden":"visible",position:"relative",transition:"max-height 0.3s"},children:[e.jsx(p,{variant:"body2",sx:{whiteSpace:"pre-wrap",wordBreak:"break-word",pb:d&&!i?4:0},dangerouslySetInnerHTML:{__html:t(o)}}),!i&&d&&e.jsx(h,{sx:{pointerEvents:"none",position:"absolute",left:0,right:0,bottom:0,height:48,background:"linear-gradient(180deg, rgba(255,255,255,0) 0%, #fff 100%)"}})]}),d&&e.jsx(h,{children:e.jsxs(pe,{size:"small",variant:"text",onClick:()=>{const w=!i;s?s(w):c(w)},sx:{minWidth:0,fontWeight:500,color:"primary.main",textTransform:"none",display:"inline-flex",alignItems:"center",gap:.5},children:[i?"Ler menos":"Ler tudo",i?e.jsx(xn,{fontSize:"small"}):e.jsx(jo,{fontSize:"small"})]})})]})})},tr=async(o,t)=>{if(!o)throw new Error("Usuário não autenticado");const{data:r,error:s}=await G.from("tabela_preco").select("id, nome, ativo").eq("user_id",o).eq("ativo",!0).is("deletado_em",null).order("nome",{ascending:!0});if(s)throw new Error(s.message);if(!r||r.length===0)return[];const u=r.map(a=>a.id),{data:c,error:i}=await G.from("tabela_preco_item").select("id, tabela_preco_id, produto_id, produto_variacao_id, preco_override").in("tabela_preco_id",u).eq("produto_id",t);if(i)throw new Error(i.message);const d=[];for(const a of r){const l=(c||[]).filter(n=>n.tabela_preco_id===a.id).map(n=>({id:n.id,produto_id:n.produto_id,produto_variacao_id:n.produto_variacao_id,preco_override:n.preco_override}));l.length>0&&d.push({table_id:a.id,table_name:a.nome,ativo:a.ativo,overrides:l})}return d},or=o=>{const{user:t}=Et(),r=t==null?void 0:t.id;return en({queryKey:["price-tables-by-product",o],queryFn:()=>tr(r,o),enabled:!!r&&!!o})},_t=o=>
2o.toLocaleString("pt-BR",{style:"currency",currency:"BRL"}),nr=({open:o,onClose:t,tableId:r,tableName:s,productId:u,productName:c,variations:i,overrides:d})=>{const[a,l]=S.useState(null),n=At(),y=m=>{const b=d.find(E=>E.produto_variacao_id===m.id);l({variationId:m.id,variationName:m.nome,basePrice:m.preco,currentOverride:b==null?void 0:b.preco_override,overrideId:b==null?void 0:b.id})},w=async m=>{if(a)try{await n.mutateAsync({id:a.overrideId,tabela_preco_id:r,produto_id:u,produto_variacao_id:a.variationId,preco_override:m}),l(null)}catch{}};return e.jsxs(e.Fragment,{children:[e.jsxs(wt,{open:o,onClose:t,maxWidth:"sm",fullWidth:!0,children:[e.jsxs(St,{children:[e.jsxs(A,{direction:"row",justifyContent:"space-between",alignItems:"center",children:[e.jsx(p,{variant:"h6",fontWeight:600,children:s}),e.jsx(te,{onClick:t,size:"small",children:e.jsx(Vo,{})})]}),e.jsx(p,{variant:"body2",color:"text.secondary",children:c})]}),e.jsx(Ct,{children:e.jsx(Ce,{disablePadding:!0,children:i.map(m=>{const b=d.find(R=>R.produto_variacao_id===m.id),E=!!b;return e.jsx(Ee,{disableGutters:!0,onClick:()=>y(m),sx:{cursor:"pointer",borderRadius:1.5,px:1.5,py:1,"&:active":{bgcolor:"action.hover"}},children:e.jsx(V,{primary:e.jsx(p,{variant:"body2",fontWeight:600,children:m.nome}),secondary:e.jsxs(A,{direction:"row",spacing:1,alignItems:"center",children:[e.jsxs(p,{variant:"body2",color:"text.secondary",children:["Base: ",_t(m.preco)]}),E&&e.jsxs(e.Fragment,{children:[e.jsx(p,{variant:"body2",color:"text.secondary",children:"â"}),e.jsx(p,{variant:"body2",fontWeight:600,color:"primary",children:_t(b.preco_override)})]})]})})},m.id)})})})]}),e.jsx(Ot,{open:!!a,onClose:()=>l(null),onConfirm:w,productName:c,variationName:a==null?void 0:a.variationName,basePrice:(a==null?void 0:a.basePrice)??0,currentOverride:a==null?void 0:a.currentOverride,isSubmitting:n.isPending})]})},rr=o=>o.toLocaleString("pt-BR",{style:"currency",currency:"BRL"}),ir=({productId:o,productName:t,productPrice:r,variations:s})=>{const u=xe(),{data:c}=Rt(),{data:i}=or(o),{data:d=[]}=yo(),a=At(),l=s.length>0,[n,y]=S.useState(null),[w,m]=S.useState(null),[b,E]=S.useState(null);if(!_o(c))return null;const R=d.filter(g=>g.ativo),j=new Set((i||[]).map(g=>g.table_id)),D=R.filter(g=>!j.has(g.id)),C=w&&(i==null?void 0:i.find(g=>g.table_id===w))||null,I=g=>{if(l)m(g.table_id);else{const $=g.overrides.find(H=>H.produto_variacao_id===null);y({tableId:g.table_id,tableName:g.table_name,currentOverride:$==null?void 0:$.preco_override,overrideId:$==null?void 0:$.id})}},_=async g=>{if(n)try{await a.mutateAsync({id:n.overrideId,tabela_preco_id:n.tableId,produto_id:o,produto_variacao_id:null,preco_override:g}),y(null)}catch{}},B=async g=>{E(null),u(`/price-tables/${g}/prices`)};return!i||i.length===0?D.length===0?null:e.jsxs(oe,{elevation:0,sx:{p:1.5,bgcolor:"white",mt:2,cursor:"pointer"},onClick:g=>E(g.currentTarget),children:[e.jsxs(A,{direction:"row",alignItems:"center",spacing:1,children:[e.jsx(ot,{sx:{color:"primary.main",fontSize:20}}),e.jsx(p,{variant:"subtitle2",fontWeight:600,color:"primary",children:"Adicionar a tabela de preço"})]}),e.jsx(Se,{anchorEl:b,open:!!b,onClose:()=>E(null),children:D.map(g=>e.jsx(J,{onClick:()=>B(g.id),children:e.jsx(V,{children:g.nome})},g.id))})]}):e.jsxs(e.Fragment,{children:[e.jsxs(oe,{elevation:0,sx:{p:1.5,bgcolor:"white",mt:2},children:[e.jsxs(A,{direction:"row",alignItems:"center",justifyContent:"space-between",sx:{mb:1},children:[e.jsxs(h,{sx:{display:"flex",alignItems:"center",gap:1},children:[e.jsx(vo,{size:20,color:"var(--mui-palette-primary-main)"}),e.jsxs(p,{variant:"subtitle2",fontWeight:600,children:["Tabelas de preço (",i.length,")"]})]}),D.length>0&&e.jsx(te,{size:"small",onClick:g=>E(g.currentTarget),children:e.jsx(ot,{fontSize:"small"})})]}),i.map(g=>{const $=g.overrides.find(z=>z.produto_variacao_id===null),H=g.overrides.length;return e.jsxs(h,{onClick:()=>I(g),sx:{display:"flex",justifyContent:"space-between",alignItems:"center",py:.75,cursor:"pointer"},children:[e.jsx(p,{variant:"body2",fontWeight:500,children:g.table_name}),e.jsxs(A,{direction:"row",spacing:.5,alignItems:"center",children:[e.jsx(p,{variant:"body2",color:"primary",fontWeight:500,children:l?`${H} preço${H!==1?"s":""}`:$?rr($.preco_override):""}),l?e.jsx(Lt,{sx:{fontSize:18,color:"text.secondary"}}):e.jsx(He,{sx:{fontSize:16,color:"text.secondary"}})]})]},g.table_id)}
2),e.jsx(Se,{anchorEl:b,open:!!b,onClose:()=>E(null),children:D.map(g=>e.jsx(J,{onClick:()=>B(g.id),children:e.jsx(V,{children:g.nome})},g.id))})]}),e.jsx(Ot,{open:!!n,onClose:()=>y(null),onConfirm:_,productName:t,basePrice:r,currentOverride:n==null?void 0:n.currentOverride,isSubmitting:a.isPending}),C&&e.jsx(nr,{open:!0,onClose:()=>m(null),tableId:C.table_id,tableName:C.table_name,productId:o,productName:t,variations:s,overrides:C.overrides})]})};function sr(o){return o<1024?`${o} B`:o<1024*1024?`${(o/1024).toFixed(0)} KB`:`${(o/1024/1024).toFixed(1)} MB`}const Or=()=>{var f,P,M;const{productId:o}=wo(),{data:t,isLoading:r,isError:s,refetch:u}=Do(o),c=((f=Le(t==null?void 0:t.produto_video))==null?void 0:f.status)==="processing"?(P=Le(t==null?void 0:t.produto_video))==null?void 0:P.assetId:null;S.useEffect(()=>{if(!c)return;let x=!1;const L=async()=>{try{const le=await zo(c);!x&&le!=="processing"&&u()}catch{}};L();const ae=setInterval(L,5e3);return()=>{x=!0,clearInterval(ae)}},[c,u]);const{data:i=[]}=ln(o),d=!!(t!=null&&t.digital),a=!!(t!=null&&t.combo),{data:l}=gn(d?t==null?void 0:t.id:void 0),n=(l==null?void 0:l.base)??null,y=((M=l==null?void 0:l.overrides)==null?void 0:M.length)??0,{data:w}=Rt(),{data:m}=mn(o,a,!!t),b=So(w),E=Co(w),{data:R}=Pt(),j=(R==null?void 0:R.avaliacoes_habilitadas)??!1,D=o&&Number.isFinite(Number(o))?Number(o):null,{data:C}=Eo(j?D:null),{data:I}=Io(j?D:null),_=dn(),B=hn(),g=xe(),[$,H]=Po(),[z,F]=S.useState({open:!1,isActivating:!1,productName:"",variationId:null,variationName:""}),U=$.get("showAllVariations")==="true",v=$.get("descriptionExpanded")==="true",O=x=>x.valores.map(L=>L.atributo_valor.valor).join(" / "),T=i.length>0,W=(x,L,ae=0,le)=>e.jsxs(A,{spacing:.5,children:[e.jsxs(h,{sx:{display:"flex",alignItems:"center"},children:[e.jsx(p,{variant:"body2",color:"text.secondary",children:"Estoque:"}),e.jsx(h,{sx:{ml:1},children:e.jsx(cn,{amount:x||0,isInfinite:L,minStock:ae})})]}),le!=null&&e.jsxs(p,{variant:"body2",color:"text.secondary",children:["Custo médio:"," ",le.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})]})]}),Ie=async()=>{if(t){if(!(t!=null&&t.controlar_estoque)){F({open:!0,isActivating:!1,productName:t==null?void 0:t.nome,variationId:null,variationName:""});return}g(`/stock/products/${t.id}`)}},re=async x=>{if(t){if(!(t!=null&&t.controlar_estoque)){F({open:!0,isActivating:!1,productName:t.nome,variationId:x.id,variationName:""});return}if(!x.controlar_estoque){F({open:!0,isActivating:!1,productName:t.nome,variationId:x.id,variationName:O(x)});return}g(`/stock/products/${t.id}/variation/${x.id}`)}},ie=x=>{t&&g(`/products/${t.id}/variations/${x.id}/edit`)},se=async()=>{F(x=>({...x,isActivating:!0}));try{if(!t)return;t!=null&&t.controlar_estoque?z.variationId&&(await B.mutateAsync({id:z.variationId,controlar_estoque:!0,estoque_minimo:0}),g(`/stock/products/${t.id}/variation/${z.variationId}`)):(await _.mutateAsync({id:Number(t.id),controlar_estoque:!0,estoque_minimo:0}),await Promise.all(i.map(x=>B.mutateAsync({id:x.id,controlar_estoque:!0,estoque_minimo:0}))),z.variationId?g(`/stock/products/${t.id}/variation/${z.variationId}`):g(`/stock/products/${t.id}`))}catch(x){console.error("Error enabling stock control:",x)}finally{F(x=>({...x,open:!1,isActivating:!1}))}};if(r)return e.jsx(Jn,{});if(s||!t)return e.jsx(ko,{primaryText:"Erro ao carregar o produto",secondaryText:"Por favor, tente novamente mais tarde."});const Pe=()=>b==="free"?`Faça upgrade para o plano LITE para mostrar até ${Z(5)} imagens, PRO para mostrar até ${Z(10)} imagens, ou BLACK para mostrar até ${Z(20)} imagens.`:b==="lite"?`Faça upgrade para o plano PRO para mostrar até ${Z(10)} imagens ou BLACK para mostrar até ${Z(20)} imagens.`:b==="pro"?`Faça upgrade para o plano BLACK para mostrar até ${Z(20)} imagens.`:"Você já está no plano mais alto disponÃvel.",ge="XX.X%",ke={filter:"blur(3px)",userSelect:"none",display:"inline-block"},fe={position:"relative",display:"inline-block",margin:"3px"};return e.jsxs(h,{sx:{position:"relative",padding:2},children:[e.jsx(kt,{navigateBack:!0,title:"Detalhes do produto",children:e.jsx(In,{variationCount:(i==null?void 0:i.length)||0,productId:o})}),e.jsxs(A,{spacing:2,children:[t.oculto&&e.jsx(Ue,{icon:e.jsx(Tt,{sx:{fontSize:20}}),severity:"warning",children:"Este produto não está visÃvel para os seus clientes"}),e.jsx(yn,{images:(t==null?void 0:t.image_url)||[],video:Le(t==null?void 0:t.produto_video,t==null?void 0:t.video_url),productName:t.nome,userPlan:b,getPlanUpgradeText:Pe},t.id),e.jsx(ne,{sx:{p:2},children:e.jsxs(A,{spacing:2,children:[e.jsxs(A,{spacing:1,children:[e.jsx(A,{direction:"row",spacing:1,alignItems:"center",children:e.jsx(p,{variant:"h6",fontWeight:600,gutterBottom:!0,children:t.nome})}),!t.preco_sob_consulta&&t.preco_cheio&&t.preco_cheio>t.preco&&e.jsxs(h,{sx:{display:"flex",alignItems:"center",gap:1,mt:.5,mb:1},children:[e.jsx(p,{variant:"body2",sx:{textDecoration:"line-through",color:"text.secondary"}
2,children:t.preco_cheio.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})}),e.jsxs(h,{sx:{bgcolor:"success.main",color:"success.contrastText",px:1,borderRadius:1,fontSize:"0.75rem",fontWeight:500},children:[Math.round((t.preco_cheio-t.preco)/t.preco_cheio*100),"% OFF"]})]}),t.preco_sob_consulta?e.jsx(p,{variant:"h4",color:"primary",fontSize:24,fontWeight:700,gutterBottom:!0,children:"Sob consulta"}):e.jsx(p,{variant:"h4",color:"primary",fontSize:24,fontWeight:700,gutterBottom:!0,children:t.preco.toLocaleString("pt-BR",{style:"currency",currency:"BRL"})})]}),!T&&!a&&e.jsx(h,{onClick:Ie,sx:{cursor:"pointer"},children:e.jsxs(A,{direction:"row",justifyContent:"space-between",alignItems:"center",children:[e.jsx(h,{flex:1,children:W(t.estoque_atual,!t.controlar_estoque,t.estoque_minimo||0,t.controlar_estoque?t.custo_medio_atual:void 0)}),e.jsx(Lt,{color:"action",sx:{transition:"transform 0.2s"}})]})}),t.categoria&&e.jsxs(h,{children:[e.jsx(p,{variant:"caption",color:"text.secondary",children:"Categoria"}),e.jsx(p,{variant:"body2",children:t.categoria.nome})]}),t.sku&&e.jsxs(h,{children:[e.jsx(p,{variant:"caption",color:"text.secondary",children:"Código do item"}),e.jsx(p,{variant:"body2",children:t.sku})]}),t.codigo_de_barras&&!T&&e.jsxs(h,{children:[e.jsx(p,{variant:"caption",color:"text.secondary",children:"Código de barras"}),e.jsx(p,{variant:"body2",children:t.codigo_de_barras})]}),t.descricao&&e.jsxs(h,{children:[e.jsx(p,{variant:"caption",color:"text.secondary",children:"Descrição"}),e.jsx(er,{description:t.descricao,sanitizeHTML:Ro,expanded:v,onToggle:x=>{const L=new URLSearchParams($);x?L.set("descriptionExpanded","true"):L.delete("descriptionExpanded"),H(L,{replace:!0,preventScrollReset:!0})}})]}),t.moq!=null&&t.moq>1&&e.jsxs(h,{children:[e.jsx(p,{variant:"caption",color:"text.secondary",children:"Pedido mÃnimo (MOQ)"}),e.jsxs(p,{variant:"body2",children:[t.moq," ",t.moq===1?"unidade":"unidades"]})]}),t.comprimento!=null&&t.largura!=null&&t.altura!=null&&t.peso!=null&&e.jsxs(h,{children:[e.jsx(p,{variant:"caption",color:"text.secondary",children:"Dimensões"}),e.jsx(p,{variant:"body2",children:Yn(t.comprimento,t.largura,t.altura,t.peso)})]})]})}),d&&e.jsxs(oe,{elevation:1,sx:{p:1.5,bgcolor:"white",cursor:"pointer",display:"flex",alignItems:"center",gap:1.5,mt:2},onClick:()=>g(`/products/${o}/digital-delivery`),children:[e.jsx(h,{sx:{width:32,height:32,borderRadius:1,bgcolor:n?_e("#8865FE",.12):_e("#F59E0B",.15),color:n?"primary.main":"warning.dark",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:n?n.fonte==="arquivo"?e.jsx(To,{size:18}):e.jsx(Lo,{size:18}):e.jsx(Ao,{size:18})}),e.jsxs(h,{sx:{flex:1,minWidth:0},children:[e.jsx(p,{variant:"subtitle1",fontWeight:"medium",children:"Entrega digital"}),(n==null?void 0:n.fonte)==="arquivo"&&e.jsxs(p,{variant:"body2",color:"text.secondary",sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[n.nome_arquivo||"Arquivo enviado",n.tamanho_bytes?` · ${sr(n.tamanho_bytes)}`:"",y>0?` · ${y} variaç${y===1?"ão":"ões"} com arquivo próprio`:""]}),(n==null?void 0:n.fonte)==="link"&&e.jsxs(p,{variant:"body2",color:"text.secondary",sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[n.link_url||"Link externo",y>0?` · ${y} variaç${y===1?"ão":"ões"} com link próprio`:""]}),!n&&e.jsx(p,{variant:"body2",color:"warning.dark",children:"Nenhum arquivo ou link configurado"})]}),e.jsx(Oe,{color:"action"})]}),m&&e.jsxs(oe,{elevation:1,sx:{p:1.5,bgcolor:"white",cursor:"pointer",display:"flex",justifyContent:"space-between",alignItems:"center",mt:2},onClick:()=>g(`/products/${o}/profitability`),children:[e.jsxs(h,{sx:{display:"flex",alignItems:"center",gap:1.5},children:[e.jsx(h,{sx:{bgcolor:"#E8F5E9",color:"success.main",width:32,height:32,borderRadius:1,display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(Uo,{})}),e.jsxs(h,{children:[e.jsx(p,{variant:"subtitle1",fontWeight:"medium",children:"Análise de lucratividade"}),m.numberOfSales===0?e.jsx(p,{variant:"body2",color:"text.secondary",children:m.comboUnitsSold>0?`${m.comboUnitsSold} Un. vendidas em combos`:"Nenhuma venda registrada."}):E?e.jsxs(p,{variant:"body2",color:"text.secondary",children:[`${m.totalQuantitySold} Un. Vendidas (${Oo(m.averageProfitMargin,1)}% margem)`,m.comboUnitsSold>0?` · +${m.comboUnitsSold} em combos`:""]}):e.jsxs(p,{variant:"body2",color:"text.secondary",children:[`${m.totalQuantitySold} Un. Vendidas `,e.jsx(h,{component:"span",sx:fe,children:e.jsx(p,{component:"span",variant:"body2",color:"text.secondary",sx:ke,children:`(${ge} margem)`})})]})]})]}),e.jsx(Oe,{color:"action"})]}),j&&e.jsxs(oe,{elevation:0,sx:{p:1.5,bgcolor:"white",cursor:"pointer",display:"flex",justifyContent:"space-between",alignItems:"center",mt:2},onClick:()=>g(`/products/${o}/reviews`),children:[e.jsxs(h,{sx:{display:"flex",alignItems:"center",gap:1.5,minWidth:0,flex:1},children:[e.jsx(h,{sx:{bgcolor:_e(nt,.16),color:nt,width:32,height:32,borderRadius:1,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:e.jsx(Go,{})}),e.jsxs(h,{sx:{minWidth:0,flex:1},children:[e.jsxs(h,{sx:{display:"flex",alignItems:"center",gap:.75,flexWrap:"wrap",rowGap:.5},children:[e.jsx(p,{variant:"subtitle1",fontWeight:"medium",children:"Avaliações"}),(I??0)>0&&e.jsx(Ut,{size:"small",label:`${I} pendente${I===1?"":"s"}`,sx:{height:20,bgcolor:"#FEF3C7",color:"#92400E",border:"none","& .MuiChip-label":{px:1,fontSize:"0.65rem",fontWeight:600,lineHeight:1}}})]}),!C||C.total===0?e.jsx(p,{variant:"body2",color:"text.secondary",children:"Nenhuma avaliação aprovada ainda."}):e.jsxs(h,{sx:{display:"flex",alignItems:"center",gap:1,flexWrap:"wrap",rowGap:.25},children:[e.jsx(p,{variant:"body2",fontWeight:600,sx:{minWidth:28}
2,children:C.media.toLocaleString("pt-BR",{minimumFractionDigits:1,maximumFractionDigits:1})}),e.jsx(pn,{value:C.media,readOnly:!0,size:14}),e.jsxs(p,{variant:"caption",color:"text.secondary",children:["· ",C.total," ",C.total===1?"avaliação":"avaliações"]})]})]})]}),e.jsx(Oe,{color:"action",sx:{flexShrink:0,ml:1}})]}),e.jsx(ir,{productId:Number(o),productName:t.nome,productPrice:t.preco,variations:i.map(x=>{var L;return{id:x.id,nome:x.nome||((L=x.valores)==null?void 0:L.map(ae=>ae.atributo_valor.valor).join(" / "))||`Variação ${x.id}`,preco:x.preco??t.preco}})}),a&&e.jsx(Pn,{comboProductId:Number(o),sx:{mt:m?2:0}}),T&&e.jsxs(ne,{sx:{mt:m?2:0},children:[" ",e.jsx(h,{sx:{p:2,pb:1},children:e.jsx(A,{direction:"row",justifyContent:"space-between",alignItems:"center",children:e.jsx(p,{variant:"subtitle1",fontWeight:500,children:"Variações"})})}),e.jsx(me,{}),e.jsxs(Ce,{disablePadding:!0,children:[i.length>6&&!U?i.slice(0,3).map(x=>e.jsx(Ne,{variation:x,stockAmount:x.estoque_atual,productStockEnabled:!!t.controlar_estoque,onStockClick:re,onEditClick:ie},x.id)):i.map(x=>e.jsx(Ne,{variation:x,stockAmount:x.estoque_atual,productStockEnabled:!!t.controlar_estoque,onStockClick:re,onEditClick:ie},x.id)),i.length>6&&!U&&e.jsx(h,{sx:{height:"40px",overflow:"hidden",position:"relative",cursor:"pointer","&::after":{content:'""',position:"absolute",bottom:0,left:0,right:0,height:"40px",background:"linear-gradient(transparent, rgba(255,255,255,0.9))",pointerEvents:"none"}},children:e.jsx(Ne,{variation:i[3],stockAmount:i[3].estoque_atual,productStockEnabled:!!t.controlar_estoque,onStockClick:re,onEditClick:ie},`partial-${i[3].id}`)}),i.length>6&&e.jsx(h,{sx:{p:1.5,textAlign:"center"},children:e.jsx(pe,{size:"small",onClick:()=>{const x=new URLSearchParams($);U?x.delete("showAllVariations"):x.set("showAllVariations","true"),H(x,{replace:!0,preventScrollReset:!0})},startIcon:U?e.jsx(Xo,{}):e.jsx(Zo,{}),children:U?"Mostrar menos":`Ver todas (${i.length})`})})]})]}),e.jsx(Qn,{product:t,variations:i})]}),e.jsx(un,{open:z.open,onClose:()=>F(x=>({...x,open:!1,isActivating:!1})),onActivate:se,productName:z.productName,variationName:z.variationName,isActivating:z.isActivating})]})};export{Or as default};
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.