1import{k as ke,J as Bt,r as i,K as et,N as Ws,j as e,P as Ae,O as ye,Q as hn,R as be,n as Ee,V as Ys,a as C,W as pn,X as St,Y as gn,Z as Ge,h as he,_ as ee,$ as Be,I as E,a0 as tt,a1 as bt,g as ss,a2 as He,a3 as H,a4 as Ve,a5 as ae,a6 as X,a7 as Je,a8 as rt,a9 as Js,aa as Zs,ab as Xs,ac as ea,ad as at,ae as jn,af as ta,ag as fn,ah as qt,ai as yn,aj as vn,ak as bn,al as Nn,am as wn,an as sa,ao as Cn,ap as Sn,aq as kn,ar as Pn,as as An,at as En,au as aa,av as In,aw as Dn,ax as Fn,ay as Mn,az as ra,aA as $n,aB as na,A as us,aC as On,t as ia,aD as Tn,aE as Rn,aF as _n,x as as,aG as Kt,aH as Qe,aI as la,aJ as Ln,U as ca,aK as zn}from"./index-ccEREGMx.js";import{T as Ze}from"./textarea-U6JL3bhr.js";import{C as G,a as Q,b as je,c as Pe,d as yt}from"./card-BfZFTeuQ.js";import{L as S}from"./label-BQlk_O0-.js";import{u as Un,S as Ne,a as we,b as Ce,c as Se,d as Z}from"./select-YebcfGSA.js";import{D as Ie,a as oa,b as De,c as Oe,d as Te,e as Bn,f as qn}from"./dialog-DwxW7RUW.js";import{U as da,c as ma,R as Kn,I as Vn,T as xa,a as Ps,b as As,d as pt,F as rs,e as Es}from"./tabs-3pJUc3Ng.js";import{D as Ft}from"./dollar-sign-CS-YAgZe.js";import{C as Is}from"./copy-88yKhtg1.js";import{L as Ds}from"./link-2-2alX7P_y.js";import{E as ht}from"./eye-B2nV5znC.js";import{E as Qn,L as ua}from"./lock-DD371YAG.js";import{u as Gn}from"./index-B9XAHSf3.js";import{C as ns}from"./check-vu1sVM-n.js";import{S as Hn,a as Wn,L as Yn,P as Jn}from"./shield-alert-CsCKiNKf.js";import{A as ha}from"./award-BmGcGQaQ.js";import{P as Zn}from"./pencil-BQz4A0zo.js";import{M as Xn,r as ei}from"./index-Dh_RgLvp.js";import{R as Ot}from"./refresh-cw-Dd4oxacp.js";import{P as is}from"./play-BAhsFCQV.js";import{C as Tt}from"./circle-x-Bqs0jYg0.js";import{T as ti}from"./trending-up-CpkkFXg9.js";import{C as Fs}from"./circle-check-big-2WstLeLs.js";import{M as xt}from"./mail-er0ggMtu.js";import{C as ls}from"./credit-card-CK789GeO.js";/** 2 * @license lucide-react v0.453.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 hs=ke("ArrowDown",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]);/** 7 * @license lucide-react v0.453.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 st=ke("ArrowUpDown",[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]]);/** 12 * @license lucide-react v0.453.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 si=ke("ArrowUpRight",[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]]);/** 17 * @license lucide-react v0.453.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 pa=ke("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);/** 22 * @license lucide-react v0.453.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 ai=ke("Bold",[["path",{d:"M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8",key:"mg9rjx"}]]);/** 27 * @license lucide-react v0.453.0 - ISC 28 * 29 * This source code is licensed under the ISC license. 30 * See the LICENSE file in the root directory of this source tree. 31 */const ri=ke("Calendar",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]]);/** 32 * @license lucide-react v0.453.0 - ISC 33 * 34 * This source code is licensed under the ISC license. 35 * See the LICENSE file in the root directory of this source tree. 36 */const ni=ke("ChartColumn",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M18 17V9",key:"2bz60n"}],["path",{d:"M13 17V5",key:"1frdt8"}],["path",{d:"M8 17v-3",key:"17ska0"}]]);/** 37 * @license lucide-react v0.453.0 - ISC 38 * 39 * This source code is licensed under the ISC license. 40 * See the LICENSE file in the root directory of this source tree. 41 */const ga=ke("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** 42 * @license lucide-react v0.453.0 - ISC 43 * 44 * This source code is licensed under the ISC license. 45 * See the LICENSE file in the root directory of this source tree. 46 */const ii=ke("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** 47 * @license lucide-react v0.453.0 - ISC 48 * 49 * This source code is licensed under the ISC license. 50 * See the LICENSE file in the root directory of this source tree. 51 */const ps=ke("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/** 52 * @license lucide-react v0.453.0 - ISC 53 * 54 * This source code is licensed under the ISC license. 55 * See the LICENSE file in the root directory of this source tree. 56 */const Vt=ke("FolderOpen",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]]);/** 57 * @license lucide-react v0.453.0 - ISC 58 * 59 * This source code is licensed under the ISC license. 60 * See the LICENSE file in the root directory of this source tree. 61 */const li=ke("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);/** 62 * @license lucide-react v0.453.0 - ISC 63 * 64 * This source code is licensed under the ISC license. 65 * See the LICENSE file in the root directory of this source tree. 66 */const Mt=ke("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/** 67 * @license lucide-react v0.453.0 - ISC 68 * 69 * This source code is licensed under the ISC license. 70 * See the LICENSE file in the root directory of this source tree. 71 */const ci=ke("LayoutGrid",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]]);/** 72 * @license lucide-react v0.453.0 - ISC 73 * 74 * This source code is licensed under the ISC license. 75 * See the LICENSE file in the root directory of this source tree. 76 */const Ms=ke("ListChecks",[["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}]]);/** 77 * @license lucide-react v0.453.0 - ISC 78 * 79 * This source code is licensed under the ISC license. 80 * See the LICENSE file in the root directory of this source tree. 81 */const oi=ke("List",[["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 18h.01",key:"1tta3j"}],["path",{d:"M3 6h.01",key:"1rqtza"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 18h13",key:"1lx6n3"}],["path",{d:"M8 6h13",key:"ik3vkj"}]]);/** 82 * @license lucide-react v0.453.0 - ISC 83 * 84 * This source code is licensed under the ISC license. 85 * See the LICENSE file in the root directory of this source tree. 86 */const ze=ke("Pen",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]]);/** 87 * @license lucide-react v0.453.0 - ISC 88 * 89 * This source code is licensed under the ISC license. 90 * See the LICENSE file in the root directory of this source tree. 91 */const Ke=ke("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);/** 92 * @license lucide-react v0.453.0 - ISC 93 * 94 * This source code is licensed under the ISC license. 95 * See the LICENSE file in the root directory of this source tree. 96 */const cs=ke("Tags",[["path",{d:"m15 5 6.3 6.3a2.4 2.4 0 0 1 0 3.4L17 19",key:"1cbfv1"}],["path",{d:"M9.586 5.586A2 2 0 0 0 8.172 5H3a1 1 0 0 0-1 1v5.172a2 2 0 0 0 .586 1.414L8.29 18.29a2.426 2.426 0 0 0 3.42 0l3.58-3.58a2.426 2.426 0 0 0 0-3.42z",key:"135mg7"}],["circle",{cx:"6.5",cy:"9.5",r:".5",fill:"currentColor",key:"5pm5xn"}]]),$s="/assets/Mandala-JM_1771495549568-D_5RXVO6.jpg";
96var gs="Switch",[di,Mo]=Bt(gs),[mi,xi]=di(gs),ja=i.forwardRef((t,a)=>{const{__scopeSwitch:s,name:n,checked:r,defaultChecked:o,required:x,disabled:m,value:h="on",onCheckedChange:u,form:w,...y}=t,[j,v]=i.useState(null),k=et(a,P=>v(P)),F=i.useRef(!1),L=j?w||!!j.closest("form"):!0,[c=!1,f]=Ws({prop:r,defaultProp:o,onChange:u});return e.jsxs(mi,{scope:s,checked:c,disabled:m,children:[e.jsx(Ae.button,{type:"button",role:"switch","aria-checked":c,"aria-required":x,"data-state":va(c),"data-disabled":m?"":void 0,disabled:m,value:h,...y,ref:k,onClick:ye(t.onClick,P=>{f(D=>!D),L&&(F.current=P.isPropagationStopped(),F.current||P.stopPropagation())})}),L&&e.jsx(ui,{control:j,bubbles:!F.current,name:n,value:h,checked:c,required:x,disabled:m,form:w,style:{transform:"translateX(-100%)"}})]})});ja.displayName=gs;var fa="SwitchThumb",ya=i.forwardRef((t,a)=>{const{__scopeSwitch:s,...n}=t,r=xi(fa,s);return e.jsx(Ae.span,{"data-state":va(r.checked),"data-disabled":r.disabled?"":void 0,...n,ref:a})});ya.displayName=fa;var ui=t=>{const{control:a,checked:s,bubbles:n=!0,...r}=t,o=i.useRef(null),x=Un(s),m=hn(a);return i.useEffect(()=>{const h=o.current,u=window.HTMLInputElement.prototype,y=Object.getOwnPropertyDescriptor(u,"checked").set;if(x!==s&&y){const j=new Event("click",{bubbles:n});y.call(h,s),h.dispatchEvent(j)}},[x,s,n]),e.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:s,...r,tabIndex:-1,ref:o,style:{...t.style,...m,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})};function va(t){return t?"checked":"unchecked"}var ba=ja,hi=ya;const Le=i.forwardRef(({className:t,...a},s)=>e.jsx(ba,{className:be("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",t),...a,ref:s,children:e.jsx(hi,{className:be("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));Le.displayName=ba.displayName;function Os({entityType:t,entityId:a,uploadedBy:s,onImagesUploaded:n,initialImages:r=[],maxImages:o=10}){const[x,m]=i.useState(r),[h,u]=i.useState(!1),[w,y]=i.useState(!1),j=i.useRef(null),{toast:v}=Ee();Ys();const k=JSON.stringify(r);i.useEffect(()=>{m(r)},[k,a]);const F=T=>{const U=Array.from(T).filter(_=>_.type.startsWith("image/")?_.size>10*1024*1024?(v({title:"File Too Large",description:`${_.name} is larger than 10MB`,variant:"destructive"}),!1):!0:(v({title:"Invalid File",description:`${_.name} is not an image file`,variant:"destructive"}),!1));U.length>0&&L(U)},L=async T=>{if(x.length+T.length>o){v({title:"Too Many Images",description:`You can only upload up to ${o} images`,variant:"destructive"});return}u(!0);try{const M=[];for(const _ of T){const R=_.type||"image/jpeg",ue=await fetch("/api/upload-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:_.name,contentType:R}),credentials:"include"});if(!ue.ok)throw new Error("Could not get upload URL");const{uploadURL:te,filename:A}=await ue.json();if(!(await fetch(te,{method:"PUT",headers:{"Content-Type":R},body:_})).ok)throw new Error("Direct upload to storage failed");const Y=await fetch("/api/upload-complete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:A,originalName:_.name,fileSize:_.size,mimeType:R,entityType:t,entityId:a??0}),credentials:"include"});if(!Y.ok)throw new Error("Could not finalize upload");const K=await Y.json();M.push(K.filePath)}const U=[...x,...M];m(U),n(U),v({title:"Upload Successful",description:`${T.length} image${T.length>1?"s":""} uploaded successfully`})}catch(M){console.error("Upload error:",M),v({title:"Upload Failed",description:"Failed to upload images. Please try again.",variant:"destructive"})}finally{u(!1)}},c=async T=>{const M=x[T];try{if(!M.startsWith("http")){const _=M.split("/").pop();_&&await fetch(`/api/files/${_}`,{method:"DELETE",credentials:"include"})}const U=x.filter((_,R)=>R!==T);m(U),n(U),v({title:"Success",description:"Image removed successfully"})}catch(U){console.error("Error removing image:",U),v({title:"Error",description:"Failed to remove image",variant:"destructive"})}},f=T=>{T.preventDefault(),T.stopPropagation(),T.type==="dragenter"||T.type==="dragover"?y(!0):T.type==="dragleave"&&y(!1)},P=T=>{T.preventDefault(),T.stopPropagation(),y(!1),T.dataTransfer.files&&T.dataTransfer.files.length>0&&F(T.dataTransfer.files)},D=()=>{var T;(T=j.current)==null||T.click()},[b,O]=i.useState(null),[g,B]=i.useState(null),ie=i.useCallback((T,M)=>{const U=[...x],[_]=U.splice(T,1);U.splice(M,0,_),m(U),n(U)},[x,n]),xe=i.useCallback((T,M)=>{O(M),T.dataTransfer.effectAllowed="move"},[]),fe=i.useCallback((T,M)=>{T.preventDefault(),T.dataTransfer.dropEffect="move",B(M)},[]),d=i.useCallback((T,M)=>{T.preventDefault(),b!==null&&b!==M&&ie(b,M),O(null),B(null)},[b,ie]),q=i.useCallback(()=>{O(null),B(null)},[]),z=T=>T.startsWith("http")||T.startsWith("/api/")?T:`/api/images/${T}`;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(S,{children:"Product Images"}),e.jsx(G,{className:`border-2 border-dashed cursor-pointer transition-colors ${w?"border-amber-600 bg-amber-50":"border-gray-300 hover:border-gray-400"}`,onDragEnter:f,onDragLeave:f,onDragOver:f,onDrop:P,onClick:D,children:e.jsxs(Q,{className:"flex flex-col items-center justify-center p-6",children:[e.jsx("input",{ref:j,type:"file",multiple:!0,accept:"image/*",onChange:T=>T.target.files&&F(T.target.files),className:"hidden"}),e.jsx(da,{className:"h-12 w-12 text-gray-400 mb-4"}),e.jsx("p",{className:"text-sm text-gray-600 text-center mb-2",children:"Drag and drop images here, or click to select"}),e.jsxs("p",{className:"text-xs text-gray-500 text-center",children:["PNG, JPG, JPEG up to 10MB each. Max ",o," images."]}),e.jsx(C,{type:"button",variant:"outline",className:"mt-4",disabled:h,children:h?"Uploading...":"Select Images"})]})}),x.length>0&&e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4",children:x.map((T,M)=>e.jsx(G,{className:`relative group cursor-grab active:cursor-grabbing ${b===M?"opacity-40 ring-2 ring-amber-400":""} ${g===M?"ring-2 ring-amber-600":""}`,draggable:!0,onDragStart:U=>xe(U,M),onDragOver:U=>fe(U,M),onDragLeave:()=>B(null),onDrop:U=>d(U,M),onDragEnd:q,children:e.jsxs(Q,{className:"p-2",children:[e.jsxs("div",{className:"aspect-square relative overflow-hidden rounded-md",children:[e.jsx("img",{src:z(T),alt:`Image ${M+1}`,className:"w-full h-full object-cover pointer-events-none",onError:U=>{U.currentTarget.src="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgdmlld0JveD0iMCAwIDIwMCAyMDAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIyMDAiIGhlaWdodD0iMjAwIiBmaWxsPSIjRjNGNEY2Ii8+CjxwYXRoIGQ9Ik0xMDAgMTAwQzEwMCA5NC40NzcyIDk1LjUyMjggOTAgOTAgOTBIMTEwQzEwNC40NzcgOTAgMTAwIDk0LjQ3NzIgMTAwIDEwMFoiIGZpbGw9IiM5Q0EzQUYiLz4KPC9zdmc+"}}),M===0&&e.jsxs("span",{className:"absolute top-2 left-2 bg-amber-600 text-white text-[10px] font-bold px-1.5 py-0.5 rounded flex items-center gap-0.5",children:[e.jsx(pn,{className:"h-2.5 w-2.5 fill-current"})," Featured"]}),e.jsx("div",{className:"absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(C,{type:"button",variant:"destructive",size:"sm",className:"h-7 w-7 p-0",onClick:U=>{U.stopPropagation(),c(M)},children:e.jsx(St,{className:"h-3.5 w-3.5"})})}),e.jsxs("div",{className:"absolute bottom-2 left-1/2 -translate-x-1/2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[M>0&&e.jsx(C,{type:"button",variant:"secondary",size:"sm",className:"h-7 w-7 p-0 bg-white/80 hover:bg-white",onClick:U=>{U.stopPropagation(),ie(M,M-1)},children:e.jsx(gn,{className:"h-3.5 w-3.5"})}),M<x.length-1&&e.jsx(C,{type:"button",variant:"secondary",size:"sm",className:"h-7 w-7 p-0 bg-white/80 hover:bg-white",onClick:U=>{U.stopPropagation(),ie(M,M+1)},children:e.jsx(Ge,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"absolute bottom-2 right-2 opacity-0 group-hover:opacity-30 transition-opacity",children:e.jsx(li,{className:"h-4 w-4 text-white drop-shadow"})})]}),e.jsxs("p",{className:"text-[10px] text-center text-gray-400 mt-1",children:[M+1," of ",x.length]})]})},T+M))}),x.length===0&&e.jsx(G,{className:"border-gray-200",children:e.jsxs(Q,{className:"flex flex-col items-center justify-center p-8",children:[e.jsx(Mt,{className:"h-12 w-12 text-gray-400 mb-4"}),e.jsx("p",{className:"text-sm text-gray-600 text-center",children:"No images uploaded yet. Upload product images above."})]})})]})}function Ts({id:t,testId:a,value:s,onChange:n,placeholder:r,rows:o=3}){const x=i.useRef(null),m=()=>{const h=x.current;if(!h)return;const u=h.selectionStart??0,w=h.selectionEnd??0,y=s.slice(0,u),j=s.slice(u,w),v=s.slice(w),k=j||"bold text",F=`${y}**${k}**${v}`;n(F),requestAnimationFrame(()=>{h.focus();const L=u+2,c=L+k.length;h.setSelectionRange(L,c)})};return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(C,{type:"button",variant:"outline",size:"sm",onClick:m,className:"h-7 px-2 text-xs","data-testid":`button-${a}-bold`,children:[e.jsx(ai,{className:"h-3.5 w-3.5 mr-1"}),"Bold"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Wrap text in ",e.jsx("code",{className:"font-mono",children:"**â¦**"})," to make it bold."]})]}),e.jsx(Ze,{ref:x,id:t,"data-testid":a,value:s,onChange:h=>n(h.target.value),placeholder:r,rows:o})]})}function pi({productId:t,productImages:a}){const{toast:s}=Ee(),[n,r]=i.useState(null),[o,x]=i.useState(!1),[m,h]=i.useState({title:"",sku:"",gtin:"",price:"",compareAtPrice:"",option1:"",option2:"",option3:"",inventoryQuantity:0,weight:"",weightUnit:"oz",position:1,variantImage:""}),{data:u=[],isLoading:w}=he({queryKey:[`/api/products/${t}/variants`]}),y=[`/api/products/${t}/variants`],j=c=>{const f={...c},P=["price","compareAtPrice","costPerItem","weight"];for(const b of P)(f[b]===""||f[b]===void 0)&&(f[b]=null);const D=["sku","barcode","gtin","option1","option2","option3","taxCode","variantImage"];for(const b of D)f[b]===""&&(f[b]=null);return f},v=ee({mutationFn:async c=>await ae(`/api/products/${t}/variants`,"POST",j(c)),onSuccess:()=>{X.invalidateQueries({queryKey:y}),x(!1),h({title:"",sku:"",gtin:"",price:"",compareAtPrice:"",option1:"",option2:"",option3:"",inventoryQuantity:0,weight:"",weightUnit:"oz",position:1,variantImage:""}),s({title:"Variant created"})},onError:()=>s({title:"Failed to create variant",variant:"destructive"})}),k=ee({mutationFn:async({id:c,data:f})=>{const{id:P,productId:D,createdAt:b,updatedAt:O,...g}=f;return await ae(`/api/variants/${c}`,"PATCH",j(g))},onSuccess:()=>{X.invalidateQueries({queryKey:y}),r(null),s({title:"Variant updated"})},onError:()=>s({title:"Failed to update variant",variant:"destructive"})}),F=ee({mutationFn:async c=>{await ae(`/api/variants/${c}`,"DELETE")},onSuccess:()=>{X.invalidateQueries({queryKey:y}),s({title:"Variant deleted"})},onError:()=>s({title:"Failed to delete variant",variant:"destructive"})}),L=(c,f,P,D,b,O)=>e.jsxs("div",{className:"space-y-3 p-3 border rounded-lg bg-gray-50",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Title *"}),e.jsx(E,{value:c.title,onChange:g=>f({title:g.target.value}),placeholder:"e.g. 6-Pack",className:"h-8 text-sm"})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"SKU"}),e.jsx(E,{value:c.sku,onChange:g=>f({sku:g.target.value}),placeholder:"e.g. product-6pack",className:"h-8 text-sm"})]})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"GTIN / UPC-12"}),e.jsx(E,{value:c.gtin,onChange:g=>f({gtin:g.target.value}),placeholder:"646223233551",className:"h-8 text-sm"}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:"12-digit UPC barcode. Leave blank if product has no barcode."})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Price *"}),e.jsx(E,{type:"number",step:"0.01",value:c.price,onChange:g=>f({price:g.target.value}),placeholder:"0.00",className:"h-8 text-sm"})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Compare At Price"}),e.jsx(E,{type:"number",step:"0.01",value:c.compareAtPrice,onChange:g=>f({compareAtPrice:g.target.value}),placeholder:"0.00",className:"h-8 text-sm"})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Inventory"}),e.jsx(E,{type:"number",value:c.inventoryQuantity,onChange:g=>f({inventoryQuantity:parseInt(g.target.value)||0}),className:"h-8 text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Option 1"}),e.jsx(E,{value:c.option1,onChange:g=>f({option1:g.target.value}),placeholder:"e.g. 6-Pack",className:"h-8 text-sm"})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Option 2"}),e.jsx(E,{value:c.option2,onChange:g=>f({option2:g.target.value}),placeholder:"e.g. Large",className:"h-8 text-sm"})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Option 3"}),e.jsx(E,{value:c.option3,onChange:g=>f({option3:g.target.value}),placeholder:"e.g. Gift",className:"h-8 text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Weight"}),e.jsx(E,{type:"number",step:"0.01",value:c.weight,onChange:g=>f({weight:g.target.value}),className:"h-8 text-sm"})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Weight Unit"}),e.jsxs(Ne,{value:c.weightUnit,onValueChange:g=>f({weightUnit:g}),children:[e.jsx(we,{className:"h-8 text-sm",children:e.jsx(Ce,{})}),e.jsxs(Se,{children:[e.jsx(Z,{value:"oz",children:"oz"}),e.jsx(Z,{value:"lb",children:"lb"}),e.jsx(Z,{value:"g",children:"g"}),e.jsx(Z,{value:"kg",children:"kg"})]})]})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Position"}),e.jsx(E,{type:"number",value:c.position,onChange:g=>f({position:parseInt(g.target.value)||1}),className:"h-8 text-sm"})]})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Variant Image"}),a.length>0?e.jsxs("div",{className:"mt-1",children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((g,B)=>{const ie=c.variantImage===g;return e.jsxs("button",{type:"button",onClick:()=>f({variantImage:ie?"":g}),className:`relative w-16 h-16 rounded border-2 overflow-hidden transition-all ${ie?"border-green-500 ring-2 ring-green-300":"border-gray-200 hover:border-gray-400"}`,children:[e.jsx("img",{src:g,alt:`Product image ${B+1}`,className:"w-full h-full object-cover"}),ie&&e.jsx("div",{className:"absolute inset-0 bg-green-500/20 flex items-center justify-center",children:e.jsx("div",{className:"bg-green-500 text-white rounded-full w-5 h-5 flex items-center justify-center text-xs",children:"â"})})]},B)})}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:c.variantImage?"Click again to remove selection.":"Click an image to assign it to this variant."})]}):e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:"Upload product images first, then you can assign one to this variant."})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-1",children:[e.jsx(C,{variant:"outline",size:"sm",onClick:D,children:"Cancel"}),e.jsx(C,{size:"sm",onClick:P,disabled:O||!c.title||!c.price,className:"bg-green-600 hover:bg-green-700 text-white",children:O?"Saving...":b})]})]});return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center",children:[e.jsx(cs,{className:"mr-2 h-5 w-5"}),"Variants (",u.length,")"]}),e.jsxs(C,{size:"sm",variant:"outline",onClick:()=>x(!o),children:[e.jsx(Be,{className:"h-4 w-4 mr-1"})," Add Variant"]})]}),o&&L(m,c=>h({...m,...c}),()=>v.mutate(m),()=>x(!1),"Create Variant",v.isPending),w?e.jsx("p",{className:"text-sm text-gray-500",children:"Loading variants..."}):u.lengt
96h===0?e.jsx("p",{className:"text-sm text-gray-500",children:"No variants yet. Add a variant to offer different options (e.g. 6-Pack)."}):e.jsx("div",{className:"space-y-2",children:u.map(c=>e.jsx("div",{children:(n==null?void 0:n.id)===c.id?L({title:n.title,sku:n.sku||"",gtin:n.gtin||"",price:n.price,compareAtPrice:n.compareAtPrice||"",option1:n.option1||"",option2:n.option2||"",option3:n.option3||"",inventoryQuantity:n.inventoryQuantity??0,weight:n.weight||"",weightUnit:n.weightUnit||"oz",position:n.position??1,variantImage:n.variantImage||""},f=>r({...n,...f}),()=>k.mutate({id:c.id,data:n}),()=>r(null),"Save Changes",k.isPending):e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg hover:bg-gray-50",children:[c.variantImage&&e.jsx("img",{src:c.variantImage,alt:c.title,className:"w-10 h-10 object-cover rounded border mr-3 flex-shrink-0"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm",children:c.title}),c.sku&&e.jsx(H,{variant:"outline",className:"text-xs",children:c.sku}),c.option1&&e.jsx(H,{variant:"secondary",className:"text-xs",children:c.option1}),c.variantImage&&e.jsx(H,{variant:"outline",className:"text-xs text-green-600",children:"Has Image"})]}),e.jsxs("div",{className:"flex items-center gap-4 mt-1 text-xs text-gray-500",children:[e.jsxs("span",{className:"font-semibold text-green-700",children:["$",c.price]}),c.compareAtPrice&&e.jsxs("span",{className:"line-through",children:["$",c.compareAtPrice]}),e.jsxs("span",{children:["Qty: ",c.inventoryQuantity??0]}),c.weight&&e.jsxs("span",{children:[c.weight," ",c.weightUnit]}),e.jsxs("span",{children:["Pos: ",c.position]})]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(C,{variant:"ghost",size:"sm",onClick:()=>r(c),children:e.jsx(ze,{className:"h-3.5 w-3.5"})}),e.jsx(C,{variant:"ghost",size:"sm",className:"text-red-500 hover:text-red-700",onClick:()=>{confirm(`Delete variant "${c.title}"?`)&&F.mutate(c.id)},children:e.jsx(Ve,{className:"h-3.5 w-3.5"})})]})]})},c.id))})]})}const Rs=["Ceremonial Cacao","Superfood Alchemy","Low Sugar","No Sugar","Bundles & Gifts","Popular Items","Best Value","Home Page Popular","Not In Shop"];function gi({productId:t,collections:a}){const{toast:s}=Ee(),[n,r]=i.useState([]),{data:o,isLoading:x}=he({queryKey:[`/api/products/${t}/collections`,t],enabled:!!t});i.useEffect(()=>{o&&r(o)},[o]);const m=ee({mutationFn:async j=>await ae(`/api/collections/${j}/products/${t}`,"POST"),onSuccess:()=>{X.invalidateQueries({queryKey:[`/api/products/${t}/collections`,t]}),X.invalidateQueries({queryKey:["/api/collections"]}),s({title:"Success",description:"Product added to collection"})},onError:j=>{s({title:"Error",description:`Failed to add product to collection: ${j}`,variant:"destructive"})}}),h=ee({mutationFn:async j=>await ae(`/api/collections/${j}/products/${t}`,"DELETE"),onSuccess:()=>{X.invalidateQueries({queryKey:[`/api/products/${t}/collections`,t]}),X.invalidateQueries({queryKey:["/api/collections"]}),s({title:"Success",description:"Product removed from collection"})},onError:j=>{s({title:"Error",description:`Failed to remove product from collection: ${j}`,variant:"destructive"})}}),u=j=>{m.mutate(j)},w=j=>{h.mutate(j)},y=a.filter(j=>!(n!=null&&n.some(v=>v.id===j.id)));return x?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading collections..."})}):e.jsxs("div",{className:"space-y-4",children:[n&&n.length>0&&e.jsxs("div",{children:[e.jsx(S,{className:"text-sm font-medium",children:"Current Collections"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:n.map(j=>e.jsxs(H,{variant:"secondary",className:"flex items-center gap-1","data-testid":`badge-collection-${j.id}`,children:[j.title,e.jsx("button",{onClick:()=>w(j.id),className:"ml-1 hover:bg-red-100 rounded-full p-0.5","data-testid":`button-remove-collection-${j.id}`,children:e.jsx(St,{className:"h-3 w-3"})})]},j.id))})]}),y.length>0&&e.jsxs("div",{children:[e.jsx(S,{htmlFor:"add-collection",className:"text-sm font-medium",children:"Add to Collection"}),e.jsxs(Ne,{onValueChange:j=>u(parseInt(j)),children:[e.jsx(we,{className:"mt-2","data-testid":"select-add-collection",children:e.jsx(Ce,{placeholder:"Select a collection to add this product to"})}),e.jsx(Se,{children:y.map(j=>e.jsxs(Z,{value:j.id.toString(),children:[j.title,!j.published&&e.jsx(H,{variant:"outline",className:"ml-2 text-xs",children:"Draft"})]},j.id))})]})]}),a.length===0&&e.jsxs("div",{className:"text-center py-4 text-muted-foreground",children:[e.jsx(Vt,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No collections available. Create collections in the Collections tab to organize your products."})]})]})}function ji(){const[t,a]=i.useState(!1),[s,n]=i.useState(!1),[r,o]=i.useState(null),[x,m]=i.useState(!1),[h,u]=i.useState(null),[w,y]=i.useState("list"),[j,v]=i.useState(""),k=l=>{const se=(Array.isArray(l.images)?l.images:[])[0]||l.featuredImage;return se?se.startsWith("http")||se.startsWith("/api/")?se:`/api/images/${se}`:null},[F,L]=i.useState("all"),[c,f]=i.useState("name"),[P,D]=i.useState("asc"),[b,O]=i.useState({name:"",description:"",type:"gear",price:"0.00",sku:"",gtin:"",slug:"",status:"draft",inventoryQuantity:0,trackInventory:!0,allowBackorders:!1,weight:"0.00",weightUnit:"kg",requiresShipping:!0,taxable:!0,compareAtPrice:void 0,costPerItem:void 0,vendor:"",productCategory:"",tags:[],images:[],featuredImage:"",seoTitle:"",seoDescription:"",handle:"",essence:"",bestFor:"",flavorAlchemy:"",shopCategories:[],sortOrder:0,isActive:!0}),{toast:g}=Ee(),{data:B,isLoading:ie}=he({queryKey:["/api/products","admin"],queryFn:async()=>{const l=await fetch("/api/products?includeAll=true",{cache:"no-store"});if(!l.ok)throw new Error("Failed to fetch products");return l.json()}}),{data:xe}=he({queryKey:["/api/collections"]}),fe=ee({mutationFn:async l=>await ae("/api/products","POST",l),onSuccess:l=>{X.invalidateQueries({queryKey:["/api/products"]}),u(l.id),m(!0),a(!1),g({title:"Success",description:"Product created successfully. You can now upload images."})},onError:l=>{console.error("Error creating product:",l),g({title:"Error",description:`Failed to create product: ${l.message}`,variant:"destructive"})}}),d=ee({mutationFn:async({id:l,updates:W})=>await ae(`/api/products/${l}`,"PUT",W),onSuccess:()=>{X.invalidateQueries({queryKey:["/api/products"]}),n(!1),o(null),g({title:"Success",description:"Product updated successfully"})},onError:l=>{console.error("Error updating product:",l),g({title:"Error",description:`Failed to update product: ${l.message}`,variant:"destructive"})}}),q=ee({mutationFn:async({id:l,updates:W})=>await ae(`/api/products/${l}`,"PUT",W),onSuccess:()=>{X.invalidateQueries({queryKey:["/api/products"]}),g({title:"Success",description:"Product images updated successfully"})},onError:l=>{console.error("Error updating product images:",l),g({title:"Error",description:`Failed to update product images: ${l.message}`,variant:"destructive"})}}),z=ee({mutationFn:async l=>await ae(`/api/products/${l}`,"DELETE"),onSuccess:()=>{X.invalidateQueries({queryKey:["/api/products"]}),g({title:"Success",description:"Product deleted successfully"})},onError:l=>{console.error("Error deleting product:",l),g({title:"Error",description:`Failed to delete product: ${l.message}`,variant:"destructive"})}}),T=ee({mutationFn:async l=>await ae(`/api/products/${l}/duplicate`,"POST"),onSuccess:l=>{X.invalidateQueries({queryKey:["/api/products"]}),g({title:"Success",description:`Product duplicated successfully: ${l.name}`})},onError:l=>{console.error("Error duplicating product:",l),g({title:"Error",description:`Failed to duplicate product: ${(l==null?void 0:l.message)||l}`,variant:"destructive"})}}),M=i.useCallback(l=>{h&&l.length>0&&d.mutate({id:h,updates:{images:l,featuredImage:l[0]}}),g({title:"Success",description:"Product images uploaded and saved successfully!"})},[h,g,d]),U=i.useCallback(l=>{if(!r)return;const W=l.length>0?l[0]:null,se={...r,images:l,featuredImage:W};o(se),q.mutate({id:r.id,updates:{images:l,featuredImage:W}})},[r,q]),_=()=>{O({name:"",description:"",type:"gear",price:"0.00",sku:"",gtin:"",slug:"",status:"draft",inventoryQuantity:0,trackInventory:!0,allowBackorders:!1,weight:"0.00",weightUnit:"kg",requiresShipping:!0,taxable:!0,compareAtPrice:void 0,costPerItem:void 0,vendor:"",productCategory:"",tags:[],images:[],featuredImage:"",seoTitle:"",seoDescription:"",handle:"",essence:"",bestFor:"",flavorAlchemy:"",shopCategories:[],isActive:!0}),m(!1),u(null)},R=async l=>{d.mutate({id:l.id,updates:{isActive:!l.isActive}})},ue=l=>{window.confirm(`Are you sure you want to delete "${l.name}"? This action cannot be undone.`)&&z.mutate(l.id)},te=l=>{window.confirm(`Are you sure you want to duplicate "${l.name}"?`)&&T.mutate(l.id)},A=async l=>{const W=l.slug||l.handle;if(!W){g({title:"No link available",description:"This product doesn't have a slug yet.",variant:"destructive"});return}const se=`${window.location.origin}/products/${W}`;try{await navigator.clipboard.writeText(se),g({title:"Link copied",description:se})}catch{g({title:"Couldn't copy link",description:se,variant:"destructive"})}},$=l=>l.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").trim(),Y=()=>{if(!b.name||!b.description||!b.price){g({title:"Error",description:"Please fill in all required fields (Name, Description, Price)",variant:"destructive"});return}
96const l={...b,slug:b.slug||$(b.name||""),handle:b.handle||$(b.name||""),seoTitle:b.seoTitle||b.name,seoDescription:b.seoDescription||b.description};fe.mutate(l)},K=()=>{if(!r)return;const l={},W=["isActive","trackInventory","allowBackorders","requiresShipping","taxable"],se=["id","createdAt","updatedAt"];for(const[de,Me]of Object.entries(r))se.includes(de)||(W.includes(de)?l[de]=!!Me:Me!==void 0&&(l[de]=Me));d.mutate({id:r.id,updates:l})},re=l=>{o({...l}),n(!0)},ne=l=>{c===l?D(P==="asc"?"desc":"asc"):(f(l),D("asc"))},ge=(()=>{if(!Array.isArray(B))return[];let l=B.filter(W=>{const se=j===""||W.name.toLowerCase().includes(j.toLowerCase())||W.sku&&W.sku.toLowerCase().includes(j.toLowerCase())||W.vendor&&W.vendor.toLowerCase().includes(j.toLowerCase()),de=F==="all"||F==="active"&&W.isActive&&W.status==="active"||F==="draft"&&W.status==="draft"||F==="archived"&&W.status==="archived"||F==="inactive"&&!W.isActive;return se&&de});return l.sort((W,se)=>{let de=0;switch(c){case"name":de=W.name.localeCompare(se.name);break;case"price":de=parseFloat(W.price||"0")-parseFloat(se.price||"0");break;case"status":de=(W.status||"").localeCompare(se.status||"");break;case"inventory":de=(W.inventoryQuantity||0)-(se.inventoryQuantity||0);break}return P==="asc"?de:-de}),l})(),oe={all:Array.isArray(B)?B.length:0,active:Array.isArray(B)?B.filter(l=>l.isActive&&l.status==="active").length:0,draft:Array.isArray(B)?B.filter(l=>l.status==="draft").length:0,archived:Array.isArray(B)?B.filter(l=>l.status==="archived").length:0,inactive:Array.isArray(B)?B.filter(l=>!l.isActive).length:0};return ie?e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-adventure-orange mx-auto"}),e.jsx("p",{className:"mt-4 text-gray-600",children:"Loading products..."})]})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900",children:"Products"}),e.jsxs("p",{className:"text-sm text-gray-500 mt-1",children:[oe.all," products total"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center border border-gray-200 rounded-lg overflow-hidden",children:[e.jsx("button",{onClick:()=>y("list"),className:`p-2 ${w==="list"?"bg-gray-100 text-gray-900":"text-gray-400 hover:text-gray-600"}`,children:e.jsx(oi,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>y("grid"),className:`p-2 ${w==="grid"?"bg-gray-100 text-gray-900":"text-gray-400 hover:text-gray-600"}`,children:e.jsx(ci,{className:"w-4 h-4"})})]}),e.jsxs(Ie,{open:t,onOpenChange:a,children:[e.jsx(oa,{asChild:!0,children:e.jsxs(C,{className:"bg-adventure-orange hover:bg-adventure-orange/90","data-testid":"button-create-product",children:[e.jsx(Be,{className:"mr-2 h-4 w-4"}),"Add New Product"]})}),e.jsxs(De,{className:"sm:max-w-[700px] max-h-[90vh] overflow-y-auto","aria-describedby":"create-product-description",children:[e.jsx(Oe,{children:e.jsx(Te,{children:"Create New Product"})}),e.jsx("div",{id:"create-product-description",className:"sr-only",children:"Fill out the form below to create a new product for your e-commerce store."}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Basic Information"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(S,{htmlFor:"name",children:"Product Name *"}),e.jsx(E,{id:"name","data-testid":"input-product-name",value:b.name,onChange:l=>O({...b,name:l.target.value}),placeholder:"Protective Helmet"})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"sku",children:"SKU"}),e.jsx(E,{id:"sku","data-testid":"input-product-sku",value:b.sku??"",onChange:l=>O({...b,sku:l.target.value}),placeholder:"HELMET-001"})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"gtin",children:"GTIN / UPC-12"}),e.jsx(E,{id:"gtin","data-testid":"input-product-gtin",value:b.gtin??"",onChange:l=>O({...b,gtin:l.target.value}),placeholder:"012345678901",maxLength:14,className:"font-mono"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"12-digit UPC barcode. Leave blank if product has no barcode."})]})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"description",children:"Description *"}),e.jsx(Ts,{id:"description",testId:"textarea-product-description",value:b.description||"",onChange:l=>O({...b,description:l}),placeholder:"High-quality protective helmet for ATV tours...",rows:3})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center",children:[e.jsx(Ms,{className:"mr-2 h-5 w-5"}),"Shop Categories"]}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:Rs.map(l=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer text-sm",children:[e.jsx("input",{type:"checkbox",checked:(b.shopCategories||[]).includes(l),onChange:W=>{const se=b.shopCategories||[];O({...b,shopCategories:W.target.checked?[...se,l]:se.filter(de=>de!==l)})},className:"rounded border-gray-300"}),l]},l))})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(S,{htmlFor:"status",children:"Status"}),e.jsxs(Ne,{value:b.status,onValueChange:l=>O({...b,status:l}),children:[e.jsx(we,{"data-testid":"select-product-status",children:e.jsx(Ce,{placeholder:"Select status"})}),e.jsxs(Se,{children:[e.jsx(Z,{value:"draft",children:"Draft"}),e.jsx(Z,{value:"active",children:"Active"}),e.jsx(Z,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"vendor",children:"Vendor"}),e.jsx(E,{id:"vendor","data-testid":"input-product-vendor",value:b.vendor,onChange:l=>O({...b,vendor:l.target.value}),placeholder:"Brand Name"})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"sortOrder",children:"Sort Order"}),e.jsx(E,{id:"sortOrder",type:"number",value:b.sortOrder??0,onChange:l=>O({...b,sortOrder:parseInt(l.target.value)||0}),placeholder:"0"})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center",children:[e.jsx(Mt,{className:"mr-2 h-5 w-5"}),"Product Images"]}),e.jsx("div",{className:"border border-gray-200 rounded-lg p-4",children:x&&h?e.
96jsx(Os,{entityType:"product",entityId:h,uploadedBy:1,onImagesUploaded:M}):e.jsxs("div",{className:"text-center py-4 text-gray-500",children:[e.jsx(Mt,{className:"mx-auto h-8 w-8 mb-2 text-gray-400"}),e.jsx("p",{children:"Create the product first, then you can upload images"})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center",children:[e.jsx(Ft,{className:"mr-2 h-5 w-5"}),"Pricing"]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(S,{htmlFor:"price",children:"Price *"}),e.jsx(E,{id:"price","data-testid":"input-product-price",type:"number",step:"0.01",value:b.price,onChange:l=>O({...b,price:l.target.value}),placeholder:"29.99"})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"compareAtPrice",children:"Compare at Price"}),e.jsx(E,{id:"compareAtPrice","data-testid":"input-product-compare-price",type:"number",step:"0.01",value:b.compareAtPrice||"",onChange:l=>O({...b,compareAtPrice:l.target.value||void 0}),placeholder:"39.99"})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"costPerItem",children:"Cost per Item"}),e.jsx(E,{id:"costPerItem","data-testid":"input-product-cost",type:"number",step:"0.01",value:b.costPerItem||"",onChange:l=>O({...b,costPerItem:l.target.value||void 0}),placeholder:"15.00"})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center",children:[e.jsx(tt,{className:"mr-2 h-5 w-5"}),"Inventory"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(S,{htmlFor:"inventoryQuantity",children:"Quantity"}),e.jsx(E,{id:"inventoryQuantity","data-testid":"input-product-quantity",type:"number",value:b.inventoryQuantity,onChange:l=>O({...b,inventoryQuantity:parseInt(l.target.value)||0}),placeholder:"50"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Le,{id:"trackInventory","data-testid":"switch-track-inventory",checked:b.trackInventory,onCheckedChange:l=>O({...b,trackInventory:l})}),e.jsx(S,{htmlFor:"trackInventory",children:"Track Inventory"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Le,{id:"allowBackorders","data-testid":"switch-allow-backorders",checked:b.allowBackorders,onCheckedChange:l=>O({...b,allowBackorders:l})}),e.jsx(S,{htmlFor:"allowBackorders",children:"Allow Backorders"})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center",children:[e.jsx(bt,{className:"mr-2 h-5 w-5"}),"Shipping"]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(S,{htmlFor:"weight",children:"Weight"}),e.jsx(E,{id:"weight","data-testid":"input-product-weight",type:"number",step:"0.01",value:b.weight,onChange:l=>O({...b,weight:l.target.value}),placeholder:"0.50"})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"weightUnit",children:"Weight Unit"}),e.jsxs(Ne,{value:b.weightUnit,onValueChange:l=>O({...b,weightUnit:l}),children:[e.jsx(we,{"data-testid":"select-weight-unit",children:e.jsx(Ce,{placeholder:"Select unit"})}),e.jsxs(Se,{children:[e.jsx(Z,{value:"kg",children:"Kilograms (kg)"}),e.jsx(Z,{value:"lb",children:"Pounds (lb)"}),e.jsx(Z,{value:"g",children:"Grams (g)"}),e.jsx(Z,{value:"oz",children:"Ounces (oz)"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Le,{id:"requiresShipping","data-testid":"switch-requires-shipping",checked:b.requiresShipping,onCheckedChange:l=>O({...b,requiresShipping:l})}),e.jsx(S,{htmlFor:"requiresShipping",children:"Requires Shipping"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Le,{id:"taxable","data-testid":"switch-taxable",checked:b.taxable,onCheckedChange:l=>O({...b,taxable:l})}),e.jsx(S,{htmlFor:"taxable",children:"Taxable"})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center",children:[e.jsx(ss,{className:"mr-2 h-5 w-5"}),"Product Attributes"]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"essence",children:"Essence"}),e.jsx(E,{id:"essence",value:b.essence||"",onChange:l=>O({...b,essence:l.target.value}),placeholder:"e.g. Expansive, Expressive, Magical"})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"bestFor",children:"Best For"}),e.jsx(E,{id:"bestFor",value:b.bestFor||"",onChange:l=>O({...b,bestFor:l.target.value}),placeholder:"e.g. Meditation and Creativity"})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"flavorAlchemy",children:"Flavor Alchemy"}),e.jsx(E,{id:"flavorAlchemy",value:b.flavorAlchemy||"",onChange:l=>O({...b,flavorAlchemy:l.target.value}),placeholder:"e.g. Amaretto, Manchego, Nutmeg"})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center",children:[e.jsx(cs,{className:"mr-2 h-5 w-5"}),"SEO & Organization"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(S,{htmlFor:"seoTitle",children:"SEO Title"}),e.jsx(E,{id:"seoTitle","data-testid":"input-seo-title",value:b.seoTitle,onChange:l=>O({...b,seoTitle:l.target.value}),placeholder:"Auto-generated from product name"})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"productCategory",children:"Category"}),e.jsx(E,{id:"productCategory","data-testid":"input-product-category",value:b.productCategory,onChange:l=>O({...b,productCategory:l.target.value}),placeholder:"Safety Equipment"})]})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"seoDescription",children:"SEO Description"}),e.jsx(Ze,{id:"seoDescription","data-testid":"textarea-seo-description",value:b.seoDescription,onChange:l=>O({...b,seoDescription:l.target.value}),placeholder:"Auto-generated from product description",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(S,{htmlFor:"slug",children:"URL Slug"}),e.jsx(E,{id:"slug","data-testid":"input-product-slug",value:b.slug,onChange:l=>O({...b,slug:l.target.value}),placeholder:"protective-helmet"})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"handle",children:"Handle"}),e.jsx(E,{id:"handle","data-testid":"input-product-handle",value:b.handle,onChange:l=>O({...b,handle:l.target.value}),placeholder:"protective-helmet"})]})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Le,{id:"isActive","data-testid":"switch-is-active",checked:b.isActive,onCheckedChange:l=>O({...b,isActive:l})}),e.jsx(S,{htmlFor:"isActive",children:"Active Product"})]}),e.jsxs("div",{className:"flex justify-end space-x-2",children:[e.jsx(C,{variant:"outline",onClick:()=>{a(!1),_()},children:"Cancel"}),x&&h?e.jsx(C,{onClick:()=>{a(!1),_()},className:"bg-adventure-orange hover:bg-adventure-orange/90","data-testid":"button-finish-product",children:"Finish"}):e.jsx(C,{onClick:Y,disabled:fe.isPending,className:"bg-adventure-orange hover:bg-adventure-orange/90","data-testid":"button-submit-product",children:fe.isPending?"Creating...":"Create Product"})]})]})]})]})]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:["all","active","draft","archived","inactive"].map(l=>e.jsxs(C,{variant:F===l?"default":"outline",size:"sm",onClick:()=>L(l),className:"text-xs capitalize",children:[l," (",oe[l],")"]},l))}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(He,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx(E,{placeholder:"Search products by name, SKU, or vendor...",className:"pl-9 bg-gray-50 border-gray-200",value:j,onChange:l=>v(l.target.value)})]}),w==="list"?e.jsx(G,{className:"border border-gray-200 shadow-sm",children:e.jsx(Q,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{className:"bg-gray-50 border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-3 cursor-pointer hover:text-gray-700",onClick:()=>ne("name"),children:e.jsxs("span",{className:"flex items-center gap-1",children:["Product",c==="name"&&e.jsx(st,{className:"w-3 h-3"})]})}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-3 cursor-pointer hover:text-gray-700",onClick:()=>ne("status"),children:e.jsxs("span",{className:"flex items-center gap-1",children:["Status",c==="status"&&e.jsx(st,{className:"w-3 h-3"})]})}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-3 cursor-pointer hover:text-gray-700",onClick:()=>ne("inventory"),children:e.jsxs("span",{className:"flex items-center gap-1",children:["Inventory",c==="inventory"&&e.jsx(st,{className:"w-3 h-3"})]})}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-3 w-16",children:"Order"}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-3",children:"Type"}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-3",children:"Vendor"}),e.jsx("th",{className:"text-right text-xs font-medium text-gray-500 uppercase px-4 py-3 cursor-pointer hover:text-gray-700",onClick:()=>ne("price"),children:e.jsxs("span",{className:"flex items-center gap-1 justify-end",children:["Price",c==="price"&&e.jsx(st,{className:"w-3 h-3"})]})}),e.jsx("th",{className:"text-right text-xs font-medium text-gray-500 uppercase px-4 py-3",children:"Actions"})]})}),e.jsx("tbody",{children:ge.length>0?ge.map(l=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-gray-50 transition-colors group",children:[e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-lg bg-gray-100 overflow-hidden flex-shrink-0",children:(()=>{const W=k(l);return W?e.jsx("img",{src:W,alt:l.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(tt,{className:"w-5 h-5 text-gray-400"})})})()}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:l.name}),l.sku&&e.jsxs("p",{className:"text-xs text-gray-500",children:["SKU: ",l.sku]})]})]})}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(H,{variant:"outline",className:`text-xs capitalize ${l.status==="active"&&l.isActive?"border-green-200 bg-green-50 text-green-700":l.status==="draft"?"border-amber-200 bg-amber-50 text-amber-700":l.status==="archived"?"border-gray-200 bg-gray-50 text-gray-600":"border-red-200 bg-red-50 text-red-700"}`,children:l.status}),!l.isActive&&l.status!=="archived"&&e.jsx(H,{variant:"outline",className:"text-xs border-red-200 bg-red-50 text-red-600",children:"Inactive"})]})}),e.jsx("td",{className:"px-4 py-3",children:l.trackInventory?e.jsxs("span",{className:`text-sm ${(l.inventoryQuantity||0)<=5?"text-red-600 font-medium":"text-gray-700"}`,children:[l.inventoryQuantity||0," in stock"]}):e.jsx("span",{className:"text-xs text-gray-400",children:"Not tracked"})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:"text-sm text-gray-500",children:l.sortOrder??0})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(H,{variant:"outline",className:"text-xs capitalize",children:l.type})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:"text-sm text-gray-600",children:l.vendor||"â"})}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsxs("div",{children:[e.jsxs("span",{className:"text-sm font-semibold text-gray-900",children:["$",parseFloat(l.price||"0").toFixed(2)]}),l.compareAtPrice&&e.jsxs("span",{className:"text-xs text-gray-400 line-through ml-1",children:["$",parseFloat(l.compareAtPrice).toFixed(2)]})]})}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(C,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>re(l),children:e.jsx(ze,{className:"h-3.5 w-3.5"})}),e.jsx(C,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-blue-600",onClick:()=>te(l),disabled:T.isPending,children:e.jsx(Is,{className:"h-3.5 w-3.5"})}),e.jsx(C,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",title:"Copy product link",onClick:()=>A(l),children:e.jsx(Ds,{className:"h-3.5 w-3.5"})}),e.jsx(C,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>R(l),children:e.jsx("span",{className:`text-xs font-medium ${l.isActive?"text-red-600":"text-green-600"}`,children:l.isActive?"Off":"On"})}),e.jsx(C,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-red-600",onClick:()=>ue(l),children:e.jsx(Ve,{className:"h-3.5 w-3.5"})})]})})]},l.id)):e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"px-4 py-8 text-center text-sm text-gray-500",children:j||F!=="all"?"No products match your filters":"No products found"})})})]})})})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:ge.map(l=>e.jsxs(G,{className:"relative","data-testid":`card-product-${l.id}`,children:[e.jsxs(je,{className:"pb-3",children:[(()=>{const W=k(l);return W?e.jsx("div",{className:"w-full h-40 rounded-lg bg-gray-100 overflow-hidden mb-3",children:e.jsx("img",{src:W,alt:l.name,className:"w-full h-full object-cover"})}):null})(),e.jsxs("div",{className:"flex justify-between items-start",children:[e.jsx(Pe,{className:"text-lg",children:l.name}),e.jsx("div",{className:"flex space-x-1",children:e.jsx(H,{variant:l.status==="active"?"default":"secondary",children:l.status})})]})]}),e.jsxs(Q,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm text-gray-600 line-clamp-2",children:l.description}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("span",{className:"text-lg font-bold text-gray-900",children:["$",parseFloat(l.price||"0").toFixed(2)]}),e.jsx(H,{variant:"outline",className:"capitalize",children:l.type})]}),l.sku&&e.jsxs("p",{className:"text-xs text-gray-500",children:["SKU: ",l.sku]}),l.trackInventory&&e.jsxs("p",{className:`text-xs ${(l.inventoryQuantity||0)<=5?"text-red-600 font-medium":"text-gray-500"}`,children:["Stock: ",l.inventoryQuantity]})]}),e.jsxs("div",{className:"flex justify-between items-center mt-4 pt-3 border-t",children:[e.jsxs("div",{className:"flex space-x-2",children:[e.jsx(C,{variant:"outline",size:"sm",onClick:()=>re(l),children:e.jsx(ze,{className:"h-4 w-4"})}),e.jsx(C,{variant:"outline",size:"sm",onClick:()=>te(l),className:"text-blue-600 hover:text-blue-700",disabled:T.isPending,children:e.jsx(Is,{className:"h-4 w-4"})}),e.jsx(C,{variant:"outline",size:"sm",title:"Copy product link",onClick:()=>A(l),children:e.jsx(Ds,{className:"h-4 w-4"})}),e.jsx(C,{variant:"outline",size:"sm",onClick:()=>ue(l),className:"text-red-600 hover:text-red-700",children:e.jsx(Ve,{className:"h-4 w-4"})})]}),e.jsx(C,{variant:"ghost",size:"sm",onClick:()=>R(l),className:l.isActive?"text-red-600 hover:text-red-700":"text-green-600 hover:text-green-700",children:l.isActive?"Deactivate":"Activate"})]})]})]},l.id))}),ge.length===0&&!j&&F==="all"&&e.jsx(G,{children:e.jsxs(Q,{className:"text-center py-8",children:[e.jsx(tt,{className:"mx-auto h-12 w-12 text-gray-400 mb-4"}),e.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No products found"}),e.jsx("p",{className:"text-gray-600 mb-4",children:"Get started by creating your first product"})]})}),e.jsx(Ie,{open:s,onOpenChange:n,children:e.jsxs(De,{className:"sm:max-w-[700px] max-h-[90vh] overflow-y-auto","aria-describedby":"edit-product-description",children:[e.jsx(Oe,{children:e.jsx(Te,{children:"Edit Product"})}),e.jsx("div",{id:"edit-product-description",className:"sr-only",children:"Edit the form below to update the product information."}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Basic Information"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(S,{htmlFor:"edit-name",children:"Product Name *"}),e.jsx(E,{id:"edit-name","data-testid":"input-edit-product-name",value:r.name,onChange:l=>o({...r,name:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(S,{ht
96mlFor:"edit-sku",children:"SKU"}),e.jsx(E,{id:"edit-sku","data-testid":"input-edit-product-sku",value:r.sku||"",onChange:l=>o({...r,sku:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"edit-gtin",children:"GTIN / UPC-12"}),e.jsx(E,{id:"edit-gtin","data-testid":"input-edit-product-gtin",value:r.gtin||"",onChange:l=>o({...r,gtin:l.target.value}),placeholder:"012345678901",maxLength:14,className:"font-mono"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"12-digit UPC barcode. Leave blank if product has no barcode."})]})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"edit-description",children:"Description *"}),e.jsx(Ts,{id:"edit-description",testId:"textarea-edit-product-description",value:r.description||"",onChange:l=>o({...r,description:l}),rows:3})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center",children:[e.jsx(Ms,{className:"mr-2 h-5 w-5"}),"Shop Categories"]}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:Rs.map(l=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer text-sm",children:[e.jsx("input",{type:"checkbox",checked:(r.shopCategories||[]).includes(l),onChange:W=>{const se=r.shopCategories||[];o({...r,shopCategories:W.target.checked?[...se,l]:se.filter(de=>de!==l)})},className:"rounded border-gray-300"}),l]},l))})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(S,{htmlFor:"edit-status",children:"Status"}),e.jsxs(Ne,{value:r.status,onValueChange:l=>o({...r,status:l}),children:[e.jsx(we,{"data-testid":"select-edit-product-status",children:e.jsx(Ce,{})}),e.jsxs(Se,{children:[e.jsx(Z,{value:"draft",children:"Draft"}),e.jsx(Z,{value:"active",children:"Active"}),e.jsx(Z,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"edit-vendor",children:"Vendor"}),e.jsx(E,{id:"edit-vendor","data-testid":"input-edit-product-vendor",value:r.vendor,onChange:l=>o({...r,vendor:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"edit-sortOrder",children:"Sort Order"}),e.jsx(E,{id:"edit-sortOrder",type:"number",value:r.sortOrder??0,onChange:l=>o({...r,sortOrder:parseInt(l.target.value)||0})})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center",children:[e.jsx(Mt,{className:"mr-2 h-5 w-5"}),"Product Images"]}),e.jsx("div",{className:"border border-gray-200 rounded-lg p-4",children:e.jsx(Os,{entityType:"product",entityId:r.id,uploadedBy:1,onImagesUploaded:U,initialImages:(()=>{const l=Array.isArray(r.images)?r.images:[],W=r.featuredImage;return W&&!l.includes(W)?[W,...l]:l.length>0?l:W?[W]:[]})()})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center",children:[e.jsx(Ft,{className:"mr-2 h-5 w-5"}),"Pricing"]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(S,{htmlFor:"edit-price",children:"Price *"}),e.jsx(E,{id:"edit-price","data-testid":"input-edit-product-price",type:"number",step:"0.01",value:r.price,onChange:l=>o({...r,price:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"edit-compareAtPrice",children:"Compare at Price"}),e.jsx(E,{id:"edit-compareAtPrice","data-testid":"input-edit-product-compare-price",type:"number",step:"0.01",value:r.compareAtPrice||"",onChange:l=>o({...r,compareAtPrice:l.target.value||void 0})})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"edit-costPerItem",children:"Cost per Item"}),e.jsx(E,{id:"edit-costPerItem","data-testid":"input-edit-product-cost",type:"number",step:"0.01",value:r.costPerItem||"",onChange:l=>o({...r,costPerItem:l.target.value||void 0})})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center",children:[e.jsx(Ft,{className:"mr-2 h-5 w-5"}),"Quantity Discounts"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Set automatic discounts when customers buy in bulk. Example: "Buy 3+ for $11.00 each"'}),(r.quantityDiscounts||[]).map((l,W)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(S,{className:"text-xs",children:"Min Qty"}),e.jsx(E,{type:"number",min:"2",value:l.minQty,onChange:se=>{const de=[...r.quantityDiscounts||[]];de[W]={...de[W],minQty:parseInt(se.target.value)||2},o({...r,quantityDiscounts:de})}})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx(S,{className:"text-xs",children:"Price Each ($)"}),e.jsx(E,{type:"number",step:"0.01",min:"0",value:l.priceEach,onChange:se=>{const de=[...r.quantityDiscounts||[]];de[W]={...de[W],priceEach:parseFloat(se.target.value)||0},o({...r,quantityDiscounts:de})}})]}),e.jsx(C,{variant:"ghost",size:"sm",className:"mt-4 text-red-500 hover:text-red-700",onClick:()=>{const se=[...r.quantityDiscounts||[]];se.splice(W,1),o({...r,quantityDiscounts:se})},children:e.jsx(St,{className:"h-4 w-4"})})]},W)),e.jsxs(C,{variant:"outline",size:"sm",onClick:()=>{const l=[...r.quantityDiscounts||[]];l.push({minQty:3,priceEach:parseFloat(String(r.price||"0"))*.9}),o({...r,quantityDiscounts:l})},children:[e.jsx(Be,{className:"h-4 w-4 mr-1"})," Add Tier"]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center",children:[e.jsx(tt,{className:"mr-2 h-5 w-5"}),"Inventory"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(S,{htmlFor:"edit-inventoryQuantity",children:"Quantity"}),e.jsx(E,{id:"edit-inventoryQuantity","data-testid":"input-edit-product-quantity",type:"number",value:r.
96inventoryQuantity,onChange:l=>o({...r,inventoryQuantity:parseInt(l.target.value)||0})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Le,{id:"edit-trackInventory","data-testid":"switch-edit-track-inventory",checked:r.trackInventory,onCheckedChange:l=>o({...r,trackInventory:l})}),e.jsx(S,{htmlFor:"edit-trackInventory",children:"Track Inventory"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Le,{id:"edit-allowBackorders","data-testid":"switch-edit-allow-backorders",checked:r.allowBackorders,onCheckedChange:l=>o({...r,allowBackorders:l})}),e.jsx(S,{htmlFor:"edit-allowBackorders",children:"Allow Backorders"})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center",children:[e.jsx(bt,{className:"mr-2 h-5 w-5"}),"Shipping"]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(S,{htmlFor:"edit-weight",children:"Weight"}),e.jsx(E,{id:"edit-weight","data-testid":"input-edit-product-weight",type:"number",step:"0.01",value:r.weight,onChange:l=>o({...r,weight:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"edit-weightUnit",children:"Weight Unit"}),e.jsxs(Ne,{value:r.weightUnit,onValueChange:l=>o({...r,weightUnit:l}),children:[e.jsx(we,{"data-testid":"select-edit-weight-unit",children:e.jsx(Ce,{})}),e.jsxs(Se,{children:[e.jsx(Z,{value:"kg",children:"Kilograms (kg)"}),e.jsx(Z,{value:"lb",children:"Pounds (lb)"}),e.jsx(Z,{value:"g",children:"Grams (g)"}),e.jsx(Z,{value:"oz",children:"Ounces (oz)"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Le,{id:"edit-requiresShipping","data-testid":"switch-edit-requires-shipping",checked:r.requiresShipping,onCheckedChange:l=>o({...r,requiresShipping:l})}),e.jsx(S,{htmlFor:"edit-requiresShipping",children:"Requires Shipping"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Le,{id:"edit-taxable","data-testid":"switch-edit-taxable",checked:r.taxable,onCheckedChange:l=>o({...r,taxable:l})}),e.jsx(S,{htmlFor:"edit-taxable",children:"Taxable"})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center",children:[e.jsx(ss,{className:"mr-2 h-5 w-5"}),"Product Attributes"]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"edit-essence",children:"Essence"}),e.jsx(E,{id:"edit-essence",value:r.essence||"",onChange:l=>o({...r,essence:l.target.value}),placeholder:"e.g. Expansive, Expressive, Magical"})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"edit-bestFor",children:"Best For"}),e.jsx(E,{id:"edit-bestFor",value:r.bestFor||"",onChange:l=>o({...r,bestFor:l.target.value}),placeholder:"e.g. Meditation and Creativity"})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"edit-flavorAlchemy",children:"Flavor Alchemy"}),e.jsx(E,{id:"edit-flavorAlchemy",value:r.flavorAlchemy||"",onChange:l=>o({...r,flavorAlchemy:l.target.value}),placeholder:"e.g. Amaretto, Manchego, Nutmeg"})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center",children:[e.jsx(cs,{className:"mr-2 h-5 w-5"}),"SEO & Organization"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(S,{htmlFor:"edit-seoTitle",children:"SEO Title"}),e.jsx(E,{id:"edit-seoTitle","data-testid":"input-edit-seo-title",value:r.seoTitle,onChange:l=>o({...r,seoTitle:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"edit-productCategory",children:"Category"}),e.jsx(E,{id:"edit-productCategory","data-testid":"input-edit-product-category",value:r.productCategory,onChange:l=>o({...r,productCategory:l.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"edit-seoDescription",children:"SEO Description"}),e.jsx(Ze,{id:"edit-seoDescription","data-testid":"textarea-edit-seo-description",value:r.seoDescription,onChange:l=>o({...r,seoDescription:l.target.value}),rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(S,{htmlFor:"edit-slug",children:"URL Slug"}),e.jsx(E,{id:"edit-slug","data-testid":"input-edit-product-slug",value:r.slug,onChange:l=>o({...r,slug:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"edit-handle",children:"Handle"}),e.jsx(E,{id:"edit-handle","data-testid":"input-edit-product-handle",value:r.handle,onChange:l=>o({...r,handle:l.target.value})})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center",children:[e.jsx(Vt,{className:"mr-2 h-5 w-5"}),"Collections"]}),e.jsx(gi,{productId:r.id,collections:xe||[]})]}),e.jsx(pi,{productId:r.id,productImages:r.images||[]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Le,{id:"edit-isActive","data-testid":"switch-edit-is-active",checked:r.isActive,onCheckedChange:l=>o({...r,isActive:l})}),e.jsx(S,{htmlFor:"edit-isActive",children:"Active Product"})]}),e.jsxs("div",{className:"sticky bottom-0 bg-white pt-4 pb-2 border-t border-gray-200 -mx-6 px-6 flex justify-end space-x-2",children:[e.jsx(C,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(C,{onClick:K,disabled:d.isPending,className:"bg-green-600 hover:bg-green-700 text-white px-6","data-testid":"button-update-product",children:d.isPending?"Saving...":"Save Product"})]})]})]})})]})}function fi(){const[t,a]=i.useState(!1),[s,n]=i.useState(!1),[r,o]=i.useState(null),[x,m]=i.useState({title:"",handle:"",description:"",published:!1,sortOrder:"manual",disjunctive:!0,rules:[],seoTitle:"",seoDescription:""}),{toast:h}=Ee(),{data:u,isLoading:w}=he({queryKey:["/api/collections"]}),y=ee({mutationFn:async f=>await ae("/api/collections","POST",f),onSuccess:()=>{X.invalidateQueries({queryKey:["/api/collections"]}),a(!1),m({title:"",handle:"",description:"",published:!1,sortOrder:"manual",disjunctive:!0,rules:[],seoTitle:"",seoDescription:""}),h({title:"Success",description:"Collection created successfully"})},onError:f=>{console.error("Error creating collection:",f),h({title:"Error",description:`Failed to create collection: ${f.message}`,variant:"destructive"})}}),j=ee({mutationFn:async({id:f,updates:P})=>await ae(`/api/collections/${f}`,"PUT",P),onSuccess:()=>{X.invalidateQueries({queryKey:["/api/collections"]}),n(!1),o(null),h({title:"Success",description:"Collection updated successfully"})},onError:f=>{console.error("Error updating collection:",f),h({title:"Error",description:`Failed to update collection: ${f.message}`,variant:"destructive"})}}),v=ee({mutationFn:async f=>await ae(`/api/collections/${f}`,"DELETE"),onSuccess:()=>{X.invalidateQueries({queryKey:["/api/collections"]}),h({title:"Success",description:"Collection deleted successfully"})},onError:f=>{console.error("Error deleting collection:",f),h({title:"Error",description:`Failed to delete collection: ${f.message}`,variant:"destructive"})}}),k=()=>{var P;const f=x.handle||((P=x.title)==null?void 0:P.toLowerCase().replace(/[^a-z0-9]/g,"-").replace(/-+/g,"-").trim());y.mutate({...x,handle:f})},F=f=>{o(f),n(!0)},L=()=>{r&&j.mutate({id:r.id,updates:r})},c=f=>{confirm("Are you sure you want to delete this collection?")&&v.mutate(f)};return w?e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx("div",{className:"text-lg",children:"Loading collections..."})}):e.jsxs("div",{className:"space-y-6","data-testid":"collection-management",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Collections"}),e.jsx("p",{className:"text-muted-foreground",children:"Organize your products into collections"})]}),e.jsxs(Ie,{open:t,onOpenChange:a,children:[e.jsx(oa,{asChild:!0,children:e.jsxs(C,{"data-testid":"button-create-collection",children:[e.jsx(Be,{className:"h-4 w-4 mr-2"}),"Create Collection"]})}),e.jsxs(De,{className:"max-w-2xl",children:[e.jsx(Oe,{children:e.jsx(Te,{children:"Create New Collection"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(S,{htmlFor:"title",children:"Collection Title"}),e.jsx(E,{id:"title","data-testid":"input-collection-title",value:x.title,onChange:f=>m({...x,title:f.target.value}),placeholder:"Enter collection title"})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"handle",children:"URL Handle"}),e.jsx(E,{id:"handle","data-testid":"input-collection-handle",value:x.handle,onChange:f=>m({...x,handle:f.target.value}),placeholder:"collection-url-handle"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Leave blank to auto-generate from title"})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"description",children:"Description"}),e.jsx(Ze,{id:"description","data-testid":"input-collection-description",value:x.description,onChange:f=>m({...x,description:f.target.value}),placeholder:"Describe this collection",rows:3})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Le,{id:"published","data-testid":"switch-collection-
96published",checked:x.published,onCheckedChange:f=>m({...x,published:f})}),e.jsx(S,{htmlFor:"published",children:"Published"})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(C,{onClick:k,disabled:!x.title||y.isPending,"data-testid":"button-save-collection",children:y.isPending?"Creating...":"Create Collection"}),e.jsx(C,{variant:"outline",onClick:()=>a(!1),children:"Cancel"})]})]})]})]})]}),e.jsx("div",{className:"grid gap-4",children:(u==null?void 0:u.length)===0?e.jsx(G,{children:e.jsxs(Q,{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(Vt,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No collections yet"}),e.jsx("p",{className:"text-muted-foreground text-center",children:"Create your first collection to organize products"})]})}):u==null?void 0:u.map(f=>e.jsx(G,{"data-testid":`collection-card-${f.id}`,children:e.jsx(Q,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h3",{className:"text-lg font-semibold","data-testid":`text-collection-title-${f.id}`,children:f.title}),e.jsx(H,{variant:f.published?"default":"secondary",children:f.published?e.jsxs(e.Fragment,{children:[e.jsx(ht,{className:"h-3 w-3 mr-1"}),"Published"]}):e.jsxs(e.Fragment,{children:[e.jsx(Qn,{className:"h-3 w-3 mr-1"}),"Draft"]})})]}),f.description&&e.jsx("p",{className:"text-muted-foreground","data-testid":`text-collection-description-${f.id}`,children:f.description}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[e.jsxs("span",{children:["Handle: ",f.handle]}),f.createdAt&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ri,{className:"h-3 w-3"}),"Created ",new Date(f.createdAt).toLocaleDateString()]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(C,{variant:"outline",size:"sm",onClick:()=>F(f),"data-testid":`button-edit-collection-${f.id}`,children:[e.jsx(ze,{className:"h-4 w-4 mr-1"}),"Edit"]}),e.jsxs(C,{variant:"outline",size:"sm",onClick:()=>c(f.id),"data-testid":`button-delete-collection-${f.id}`,children:[e.jsx(Ve,{className:"h-4 w-4 mr-1"}),"Delete"]})]})]})})},f.id))}),e.jsx(Ie,{open:s,onOpenChange:n,children:e.jsxs(De,{className:"max-w-2xl",children:[e.jsx(Oe,{children:e.jsx(Te,{children:"Edit Collection"})}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(S,{htmlFor:"edit-title",children:"Collection Title"}),e.jsx(E,{id:"edit-title","data-testid":"input-edit-collection-title",value:r.title,onChange:f=>o({...r,title:f.target.value})})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"edit-handle",children:"URL Handle"}),e.jsx(E,{id:"edit-handle","data-testid":"input-edit-collection-handle",value:r.handle,onChange:f=>o({...r,handle:f.target.value})})]}),e.jsxs("div",{children:[e.jsx(S,{htmlFor:"edit-description",children:"Description"}),e.jsx(Ze,{id:"edit-description","data-testid":"input-edit-collection-description",value:r.description||"",onChange:f=>o({...r,description:f.target.value}),rows:3})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Le,{id:"edit-published","data-testid":"switch-edit-collection-published",checked:r.published,onCheckedChange:f=>o({...r,published:f})}),e.jsx(S,{htmlFor:"edit-published",children:"Published"})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(C,{onClick:L,disabled:j.isPending,"data-testid":"button-update-collection",children:j.isPending?"Updating...":"Update Collection"}),e.jsx(C,{variant:"outline",onClick:()=>n(!1),children:"Cancel"})]})]})]})})]})}var _s=1,yi=.9,vi=.8,bi=.17,Yt=.1,Jt=.999,Ni=.9999,wi=.99,Ci=/[\\\/_+.#"@\[\(\{&]/,Si=/[\\\/_+.#"@\[\(\{&]/g,ki=/[\s-]/,Na=/[\s-]/g;function os(t,a,s,n,r,o,x){if(o===a.length)return r===t.length?_s:wi;var m=`${r},${o}`;if(x[m]!==void 0)return x[m];for(var h=n.charAt(o),u=s.indexOf(h,r),w=0,y,j,v,k;u>=0;)y=os(t,a,s,n,u+1,o+1,x),y>w&&(u===r?y*=_s:Ci.test(t.charAt(u-1))?(y*=vi,v=t.slice(r,u-1).match(Si),v&&r>0&&(y*=Math.pow(Jt,v.length))):ki.test(t.charAt(u-1))?(y*=yi,k=t.slice(r,u-1).match(Na),k&&r>0&&(y*=Math.pow(Jt,k.length))):(y*=bi,r>0&&(y*=Math.pow(Jt,u-r))),t.charAt(u)!==a.charAt(o)&&(y*=Ni)),(y<Yt&&s.charAt(u-1)===n.charAt(o+1)||n.charAt(o+1)===n.charAt(o)&&s.charAt(u-1)!==n.charAt(o))&&(j=os(t,a,s,n,u+1,o+2,x),j*Yt>y&&(y=j*Yt)),y>w&&(w=y),u=s.indexOf(h,u+1);return x[m]=w,w}function Ls(t){return t.toLowerCase().replace(Na," ")}function Pi(t,a,s){return t=s&&s.length>0?`${t+" "+s.join(" ")}`:t,os(t,a,Ls(t),Ls(a),0,0,{})}var gt='[cmdk-group=""]',Zt='[cmdk-group-items=""]',Ai='[cmdk-group-heading=""]',wa='[cmdk-item=""]',z
vendor: 10,299 bytes, line 96
96s=`${wa}:not([aria-disabled="true"])`,ds="cmdk-item-select",dt="data-value",Ei=(t,a,s)=>Pi(t,a,s),Ca=i.createContext(void 0),kt=()=>i.useContext(Ca),Sa=i.createContext(void 0),js=()=>i.useContext(Sa),ka=i.createContext(void 0),Pa=i.forwardRef((t,a)=>{let s=mt(()=>{var A,$;return{search:"",value:($=(A=t.value)!=null?A:t.defaultValue)!=null?$:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),n=mt(()=>new Set),r=mt(()=>new Map),o=mt(()=>new Map),x=mt(()=>new Set),m=Aa(t),{label:h,children:u,value:w,onValueChange:y,filter:j,shouldFilter:v,loop:k,disablePointerSelection:F=!1,vimBindings:L=!0,...c}=t,f=Je(),P=Je(),D=Je(),b=i.useRef(null),O=zi();nt(()=>{if(w!==void 0){let A=w.trim();s.current.value=A,g.emit()}},[w]),nt(()=>{O(6,q)},[]);let g=i.useMemo(()=>({subscribe:A=>(x.current.add(A),()=>x.current.delete(A)),snapshot:()=>s.current,setState:(A,$,Y)=>{var K,re,ne,ge;if(!Object.is(s.current[A],$)){if(s.current[A]=$,A==="search")d(),xe(),O(1,fe);else if(A==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let oe=document.getElementById(D);oe?oe.focus():(K=document.getElementById(f))==null||K.focus()}if(O(7,()=>{var oe;s.current.selectedItemId=(oe=z())==null?void 0:oe.id,g.emit()}),Y||O(5,q),((re=m.current)==null?void 0:re.value)!==void 0){let oe=$??"";(ge=(ne=m.current).onValueChange)==null||ge.call(ne,oe);return}}g.emit()}},emit:()=>{x.current.forEach(A=>A())}}),[]),B=i.useMemo(()=>({value:(A,$,Y)=>{var K;$!==((K=o.current.get(A))==null?void 0:K.value)&&(o.current.set(A,{value:$,keywords:Y}),s.current.filtered.items.set(A,ie($,Y)),O(2,()=>{xe(),g.emit()}))},item:(A,$)=>(n.current.add(A),$&&(r.current.has($)?r.current.get($).add(A):r.current.set($,new Set([A]))),O(3,()=>{d(),xe(),s.current.value||fe(),g.emit()}),()=>{o.current.delete(A),n.current.delete(A),s.current.filtered.items.delete(A);let Y=z();O(4,()=>{d(),(Y==null?void 0:Y.getAttribute("id"))===A&&fe(),g.emit()})}),group:A=>(r.current.has(A)||r.current.set(A,new Set),()=>{o.current.delete(A),r.current.delete(A)}),filter:()=>m.current.shouldFilter,label:h||t["aria-label"],getDisablePointerSelection:()=>m.current.disablePointerSelection,listId:f,inputId:D,labelId:P,listInnerRef:b}),[]);function ie(A,$){var Y,K;let re=(K=(Y=m.current)==null?void 0:Y.filter)!=null?K:Ei;return A?re(A,s.current.search,$):0}function xe(){if(!s.current.search||m.current.shouldFilter===!1)return;let A=s.current.filtered.items,$=[];s.current.filtered.groups.forEach(K=>{let re=r.current.get(K),ne=0;re.forEach(ge=>{let oe=A.get(ge);ne=Math.max(oe,ne)}),$.push([K,ne])});let Y=b.current;T().sort((K,re)=>{var ne,ge;let oe=K.getAttribute("id"),l=re.getAttribute("id");return((ne=A.get(l))!=null?ne:0)-((ge=A.get(oe))!=null?ge:0)}).forEach(K=>{let re=K.closest(Zt);re?re.appendChild(K.parentElement===re?K:K.closest(`${Zt} > *`)):Y.appendChild(K.parentElement===Y?K:K.closest(`${Zt} > *`))}),$.sort((K,re)=>re[1]-K[1]).forEach(K=>{var re;let ne=(re=b.current)==null?void 0:re.querySelector(`${gt}[${dt}="${encodeURIComponent(K[0])}"]`);ne==null||ne.parentElement.appendChild(ne)})}function fe(){let A=T().find(Y=>Y.getAttribute("aria-disabled")!=="true"),$=A==null?void 0:A.getAttribute(dt);g.setState("value",$||void 0)}function d(){var A,$,Y,K;if(!s.current.search||m.current.shouldFilter===!1){s.current.filtered.count=n.current.size;return}s.current.filtered.groups=new Set;let re=0;for(let ne of n.current){let ge=($=(A=o.current.get(ne))==null?void 0:A.value)!=null?$:"",oe=(K=(Y=o.current.get(ne))==null?void 0:Y.keywords)!=null?K:[],l=ie(ge,oe);s.current.filtered.items.set(ne,l),l>0&&re++}for(let[ne,ge]of r.current)for(let oe of ge)if(s.current.filtered.items.get(oe)>0){s.current.filtered.groups.add(ne);break}s.current.filtered.count=re}function q(){var A,$,Y;let K=z();K&&(((A=K.parentElement)==null?void 0:A.firstChild)===K&&((Y=($=K.closest(gt))==null?void 0:$.querySelector(Ai))==null||Y.scrollIntoView({block:"nearest"})),K.scrollIntoView({block:"nearest"}))}function z(){var A;return(A=b.current)==null?void 0:A.querySelector(`${wa}[aria-selected="true"]`)}function T(){var A;return Array.from(((A=b.current)==null?void 0:A.querySelectorAll(zs))||[])}function M(A){let $=T()[A];$&&g.setState("value",$.getAttribute(dt))}function U(A){var $;let Y=z(),K=T(),re=K.findIndex(ge=>ge===Y),ne=K[re+A];($=m.current)!=null&&$.loop&&(ne=re+A<0?K[K.length-1]:re+A===K.length?K[0]:K[re+A]),ne&&g.setState("value",ne.getAttribute(dt))}function _(A){let $=z(),Y=$==null?void 0:$.closest(gt),K;for(;Y&&!K;)Y=A>0?_i(Y,gt):Li(Y,gt),K=Y==null?void 0:Y.querySelector(zs);K?g.setState("value",K.getAttribute(dt)):U(A)}let R=()=>M(T().length-1),ue=A=>{A.preventDefault(),A.metaKey?R():A.altKey?_(1):U(1)},te=A=>{A.preventDefault(),A.metaKey?M(0):A.altKey?_(-1):U(-1)};return i.createElement(Ae.div,{ref:a,tabIndex:-1,...c,"cmdk-root":"",onKeyDown:A=>{var $;($=c.onKeyDown)==null||$.call(c,A);let Y=A.nativeEvent.isComposing||A.keyCode===229;if(!(A.defaultPrevented||Y))switch(A.key){case"n":case"j":{L&&A.ctrlKey&&ue(A);break}case"ArrowDown":{ue(A);break}case"p":case"k":{L&&A.ctrlKey&&te(A);break}case"ArrowUp":{te(A);break}case"Home":{A.preventDefault(),M(0);break}case"End":{A.preventDefault(),R();break}case"Enter":{A.preventDefault();let K=z();if(K){let re=new Event(ds);K.dispatchEvent(re)}}}}},i.createElement("label",{"cmdk-label":"",htmlFor:B.inputId,id:B.labelId,style:Bi},h),Qt(t,A=>i.createElement(Sa.Provider,{value:g},i.createElement(Ca.Provider,{value:B},A))))}),Ii=i.forwardRef((t,a)=>{var s,n;let r=Je(),o=i.useRef(null),x=i.useContext(ka),m=kt(),h=Aa(t),u=(n=(s=h.current)==null?void 0:s.forceMount)!=null?n:x==null?void 0:x.forceMount;nt(()=>{if(!u)return m.item(r,x==null?void 0:x.id)},[u]);let w=Ea(r,o,[t.value,t.children,o],t.keywords),y=js(),j=Xe(O=>O.value&&O.value===w.current),v=Xe(O=>u||m.filter()===!1?!0:O.search?O.filtered.items.get(r)>0:!0);i.useEffect(()=>{let O=o.current;if(!(!O||t.disabled))return O.addEventListener(ds,k),()=>O.removeEventListener(ds,k)},[v,t.onSelect,t.disabled]);function k(){var O,g;F(),(g=(O=h.current).onSelect)==null||g.call(O,w.current)}function F(){y.setState("value",w.current,!0)}if(!v)return null;let{disabled:L,value:c,onSelect:f,forceMount:P,keywords:D,...b}=t;return i.createElement(Ae.div,{ref:rt(o,a),...b,id:r,"cmdk-item":"",role:"option","aria-disabled":!!L,"aria-selected":!!j,"data-disabled":!!L,"data-selected":!!j,onPointerMove:L||m.getDisablePointerSelection()?void 0:F,onClick:L?void 0:k},t.children)}),Di=i.forwardRef((t,a)=>{let{heading:s,children:n,forceMount:r,...o}=t,x=Je(),m=i.useRef(null),h=i.useRef(null),u=Je(),w=kt(),y=Xe(v=>r||w.filter()===!1?!0:v.search?v.filtered.groups.has(x):!0);nt(()=>w.group(x),[]),Ea(x,m,[t.value,t.heading,h]);let j=i.useMemo(()=>({id:x,forceMount:r}),[r]);return i.createElement(Ae.div,{ref:rt(m,a),...o,"cmdk-group":"",role:"presentation",hidden:y?void 0:!0},s&&i.createElement("div",{ref:h,"cmdk-group-heading":"","aria-hidden":!0,id:u},s),Qt(t,v=>i.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":s?u:void 0},i.createElement(ka.Provider,{value:j},v))))}),Fi=i.forwardRef((t,a)=>{let{alwaysRender:s,...n}=t,r=i.useRef(null),o=Xe(x=>!x.search);return!s&&!o?null:i.createElement(Ae.div,{ref:rt(r,a),...n,"cmdk-separator":"",role:"separator"})}),Mi=i.forwardRef((t,a)=>{let{onValueChange:s,...n}=t,r=t.value!=null,o=js(),x=Xe(u=>u.search),m=Xe(u=>u.selectedItemId),h=kt();return i.useEffect(()=>{t.value!=null&&o.setState("search",t.value)},[t.value]),i.createElement(Ae.input,{ref:a,...n,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":h.listId,"aria-labelledby":h.labelId,"aria-activedescendant":m,id:h.inputId,type:"text",value:r?t.value:x,onChange:u=>{r||o.setState("search",u.target.value),s==null||s(u.target.value)}})}),$i=i.forwardRef((t,a)=>{let{children:s,label:n="Suggestions",...r}=t,o=i.useRef(null),x=i.useRef(null),m=Xe(u=>u.selectedItemId),h=kt();return i.useEffect(()=>{if(x.current&&o.current){let u=x.current,w=o.current,y,j=new ResizeObserver(()=>{y=requestAnimationFrame(()=>{let v=u.offsetHeight;w.style.setProperty("--cmdk-list-height",v.toFixed(1)+"px")})});return j.observe(u),()=>{cancelAnimationFrame(y),j.unobserve(u)}}},[]),i.createElement(Ae.div,{ref:rt(o,a),...r,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":m,"aria-label":n,id:h.listId},Qt(t,u=>i.createElement("div",{ref:rt(x,h.listInnerRef),"cmdk-list-sizer":""},u)))}),Oi=i.forwardRef((t,a)=>{let{open:s,onOpenChange:n,overlayClassName:r,contentClassName:o,container:x,...m}=t;return i.createElement(Js,{open:s,onOpenChange:n},i.createElement(Zs,{container:x},i.createElement(Xs,{"cmdk-overlay":"",className:r}),i.createElement(ea,{"aria-label":t.label,"cmdk-dialog":"",className:o},i.createElement(Pa,{ref:a,...m}))))}),Ti=i.forwardRef((t,a)=>Xe(s=>s.filtered.count===0)?i.createElement(Ae.div,{ref:a,...t,"cmdk-empty":"",role:"presentation"}):null),Ri=i.forwardRef((t,a)=>{let{progress:s,children:n,label:r="Loading...",...o}=t;return i.createElement(Ae.div,{ref:a,...o,"cmdk-loading":"",role:"progressbar","aria-valuenow":s,"aria-valuemin":0,"aria-valuemax":100,"aria-label":r},Qt(t,x=>i.createElement("div",{"aria-hidden":!0},x)))}),Re=Object.assign(Pa,{List:$i,Item:Ii,Input:Mi,Group:Di,Separator:Fi,Dialog:Oi,Empty:Ti,Loading:Ri});function _i(t,a){let s=t.nextElementSibling;for(;s;){if(s.matches(a))return s;s=s.nextElementSibling}}function Li(t,a){let s=t.previousElementSibling;for(;s;){if(s.matches(a))return s;s=s.previousElementSibling}}function Aa(t){let a=i.useRef(t);return nt(()=>{a.current=t}),a}var nt=typeof window>"u"?i.useEffect:i.useLayoutEffect;function mt(t){let a=i.useRef();return a.current===void 0&&(a.current=t()),a}function Xe(t){let a=js(),s=()=>t(a.snapshot());return i.useSyncExternalStore(a.subscribe,s,s)}function Ea(t,a,s,n=[]){let r=i.useRef(),o=kt();return nt(()=>{var x;let m=(()=>{var u;for(let w of s){if(typeof w=="string")return w.trim();if(typeof w=="object"&&"current"in w)return w.current?(u=w.current.textContent)==null?void 0:u.trim():r.current}})(),h=n.map(u=>u.trim());o.value(t,m,h),(x=a.current)==null||x.setAttribute(dt,m),r.current=m}),r}var zi=()=>
96{let[t,a]=i.useState(),s=mt(()=>new Map);return nt(()=>{s.current.forEach(n=>n()),s.current=new Map},[t]),(n,r)=>{s.current.set(n,r),a({})}};function Ui(t){let a=t.type;return typeof a=="function"?a(t.props):"render"in a?a.render(t.props):t}function Qt({asChild:t,children:a},s){return t&&i.isValidElement(a)?i.cloneElement(Ui(a),{ref:a.ref},s(a.props.children)):s(a)}var Bi={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const Ia=i.forwardRef(({className:t,...a},s)=>e.jsx(Re,{ref:s,className:be("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",t),...a}));Ia.displayName=Re.displayName;const qi=({children:t,...a})=>e.jsx(Ie,{...a,children:e.jsxs(De,{className:"overflow-hidden p-0 shadow-lg","aria-describedby":"command-dialog-description",children:[e.jsx("div",{id:"command-dialog-description",className:"sr-only",children:"Search and select from available commands and options."}),e.jsx(Ia,{className:"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:t})]})}),Da=i.forwardRef(({className:t,...a},s)=>e.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[e.jsx(He,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx(Re.Input,{ref:s,className:be("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",t),...a})]}));Da.displayName=Re.Input.displayName;const Fa=i.forwardRef(({className:t,...a},s)=>e.jsx(Re.List,{ref:s,className:be("max-h-[300px] overflow-y-auto overflow-x-hidden",t),...a}));Fa.displayName=Re.List.displayName;const Ma=i.forwardRef((t,a)=>e.jsx(Re.Empty,{ref:a,className:"py-6 text-center text-sm",...t}));Ma.displayName=Re.Empty.displayName;const $a=i.forwardRef(({className:t,...a},s)=>e.jsx(Re.Group,{ref:s,className:be("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",t),...a}));$a.displayName=Re.Group.displayName;const Ki=i.forwardRef(({className:t,...a},s)=>e.jsx(Re.Separator,{ref:s,className:be("-mx-1 h-px bg-border",t),...a}));Ki.displayName=Re.Separator.displayName;const Oa=i.forwardRef(({className:t,...a},s)=>e.jsx(Re.Item,{ref:s,className:be("relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",t),...a}));Oa.displayName=Re.Item.displayName;var Ta={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Us=at.createContext&&at.createContext(Ta),Vi=["attr","size","title"];function Qi(t,a){if(t==null)return{};var s=Gi(t,a),n,r;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(r=0;r<o.length;r++)n=o[r],!(a.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(s[n]=t[n])}return s}function Gi(t,a){if(t==null)return{};var s={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(a.indexOf(n)>=0)continue;s[n]=t[n]}return s}function Rt(){return Rt=Object.assign?Object.assign.bind():function(t){for(var a=1;a<arguments.length;a++){var s=arguments[a];for(var n in s)Object.prototype.hasOwnProperty.call(s,n)&&(t[n]=s[n])}return t},Rt.apply(this,arguments)}function Bs(t,a){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);a&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),s.push.apply(s,n)}return s}function _t(t){for(var a=1;a<arguments.length;a++){var s=arguments[a]!=null?arguments[a]:{};
96a%2?Bs(Object(s),!0).forEach(function(n){Hi(t,n,s[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):Bs(Object(s)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(s,n))})}return t}function Hi(t,a,s){return a=Wi(a),a in t?Object.defineProperty(t,a,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[a]=s,t}function Wi(t){var a=Yi(t,"string");return typeof a=="symbol"?a:a+""}function Yi(t,a){if(typeof t!="object"||!t)return t;var s=t[Symbol.toPrimitive];if(s!==void 0){var n=s.call(t,a||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(t)}function Ra(t){return t&&t.map((a,s)=>at.createElement(a.tag,_t({key:s},a.attr),Ra(a.child)))}function Ji(t){return a=>at.createElement(Zi,Rt({attr:_t({},t.attr)},a),Ra(t.child))}function Zi(t){var a=s=>{var{attr:n,size:r,title:o}=t,x=Qi(t,Vi),m=r||s.size||"1em",h;return s.className&&(h=s.className),t.className&&(h=(h?h+" ":"")+t.className),at.createElement("svg",Rt({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},s.attr,n,x,{className:h,style:_t(_t({color:t.color||s.color},s.style),t.style),height:m,width:m,xmlns:"http://www.w3.org/2000/svg"}),o&&at.createElement("title",null,o),t.children)};return Us!==void 0?at.createElement(Us.Consumer,null,s=>a(s)):a(Ta)}function qs(t){return Ji({tag:"svg",attr:{role:"img",viewBox:"0 0 24 24"},child:[{tag:"path",attr:{d:"M22.84 2.9982v17.9987c.0086 1.6473-1.3197 2.9897-2.967 2.9984a2.9808 2.9808 0 01-.3677-.0208c-1.528-.226-2.6477-1.5558-2.6105-3.1V3.1204c-.0369-1.5458 1.0856-2.8762 2.6157-3.1 1.6361-.1915 3.1178.9796 3.3093 2.6158.014.1201.0208.241.0202.3619zM4.1326 18.0548c-1.6417 0-2.9726 1.331-2.9726 2.9726C1.16 22.6691 2.4909 24 4.1326 24s2.9726-1.3309 2.9726-2.9726-1.331-2.9726-2.9726-2.9726zm7.8728-9.0098c-.0171 0-.0342 0-.0513.0003-1.6495.0904-2.9293 1.474-2.891 3.1256v7.9846c0 2.167.9535 3.4825 2.3505 3.763 1.6118.3266 3.1832-.7152 3.5098-2.327.04-.1974.06-.3983.0593-.5998v-8.9585c.003-1.6474-1.33-2.9852-2.9773-2.9882z"},child:[]}]})(t)}var ms=["Enter"," "],Xi=["ArrowDown","PageUp","Home"],_a=["ArrowUp","PageDown","End"],el=[...Xi,..._a],tl={ltr:[...ms,"ArrowRight"],rtl:[...ms,"ArrowLeft"]},sl={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Pt="Menu",[Nt,al,rl]=jn(Pt),[it,La]=Bt(Pt,[rl,ta,ma]),Gt=ta(),za=ma(),[nl,lt]=it(Pt),[il,At]=it(Pt),Ua=t=>{const{__scopeMenu:a,open:s=!1,children:n,dir:r,onOpenChange:o,modal:x=!0}=t,m=Gt(a),[h,u]=i.useState(null),w=i.useRef(!1),y=sa(o),j=Gn(r);return i.useEffect(()=>{const v=()=>{w.current=!0,document.addEventListener("pointerdown",k,{capture:!0,once:!0}),document.addEventListener("pointermove",k,{capture:!0,once:!0})},k=()=>w.current=!1;return document.addEventListener("keydown",v,{capture:!0}),()=>{document.removeEventListener("keydown",v,{capture:!0}),document.removeEventListener("pointerdown",k,{capture:!0}),document.removeEventListener("pointermove",k,{capture:!0})}},[]),e.jsx(Pn,{...m,children:e.jsx(nl,{scope:a,open:s,onOpenChange:y,content:h,onContentChange:u,children:e.jsx(il,{scope:a,onClose:i.useCallback(()=>y(!1),[y]),isUsingKeyboardRef:w,dir:j,modal:x,children:n})})})};Ua.displayName=Pt;var ll="MenuAnchor",fs=i.forwardRef((t,a)=>{const{__scopeMenu:s,...n}=t,r=Gt(s);return e.jsx(fn,{...r,...n,ref:a})});fs.displayName=ll;var ys="MenuPortal",[cl,Ba]=it(ys,{forceMount:void 0}),qa=t=>{const{__scopeMenu:a,forceMount:s,children:n,container:r}=t,o=lt(ys,a);return e.jsx(cl,{scope:a,forceMount:s,children:e.jsx(qt,{present:s||o.open,children:e.jsx(An,{asChild:!0,container:r,children:n})})})};qa.displayName=ys;var Ue="MenuContent",[ol,vs]=it(Ue),Ka=i.forwardRef((t,a)=>{const s=Ba(Ue,t.__scopeMenu),{forceMount:n=s.forceMount,...r}=t,o=lt(Ue,t.__scopeMenu),x=At(Ue,t.__scopeMenu);return e.jsx(Nt.Provider,{scope:t.__scopeMenu,children:e.jsx(qt,{present:n||o.open,children:e.jsx(Nt.Slot,{scope:t.__scopeMenu,children:x.modal?e.jsx(dl,{...r,ref:a}):e.jsx(ml,{...r,ref:a})})})})}),dl=i.forwardRef((t,a)=>{const s=lt(Ue,t.__scopeMenu),n=i.useRef(null),r=et(a,n);return i.useEffect(()=>{const o=n.current;if(o)return yn(o)},[]),e.jsx(bs,{...t,ref:r,trapFocus:s.open,disableOutsidePointerEvents:s.open,disableOutsideScroll:!0,onFocusOutside:ye(t.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>s.onOpenChange(!1)})}),ml=i.forwardRef((t,a)=>{const s=lt(Ue,t.__scopeMenu);
vendor: 11,952 bytes, line 96
96return e.jsx(bs,{...t,ref:a,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>s.onOpenChange(!1)})}),xl=En("MenuContent.ScrollLock"),bs=i.forwardRef((t,a)=>{const{__scopeMenu:s,loop:n=!1,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:x,disableOutsidePointerEvents:m,onEntryFocus:h,onEscapeKeyDown:u,onPointerDownOutside:w,onFocusOutside:y,onInteractOutside:j,onDismiss:v,disableOutsideScroll:k,...F}=t,L=lt(Ue,s),c=At(Ue,s),f=Gt(s),P=za(s),D=al(s),[b,O]=i.useState(null),g=i.useRef(null),B=et(a,g,L.onContentChange),ie=i.useRef(0),xe=i.useRef(""),fe=i.useRef(0),d=i.useRef(null),q=i.useRef("right"),z=i.useRef(0),T=k?Sn:i.Fragment,M=k?{as:xl,allowPinchZoom:!0}:void 0,U=R=>{var ne,ge;const ue=xe.current+R,te=D().filter(oe=>!oe.disabled),A=document.activeElement,$=(ne=te.find(oe=>oe.ref.current===A))==null?void 0:ne.textValue,Y=te.map(oe=>oe.textValue),K=Cl(Y,ue,$),re=(ge=te.find(oe=>oe.textValue===K))==null?void 0:ge.ref.current;(function oe(l){xe.current=l,window.clearTimeout(ie.current),l!==""&&(ie.current=window.setTimeout(()=>oe(""),1e3))})(ue),re&&setTimeout(()=>re.focus())};i.useEffect(()=>()=>window.clearTimeout(ie.current),[]),vn();const _=i.useCallback(R=>{var te,A;return q.current===((te=d.current)==null?void 0:te.side)&&kl(R,(A=d.current)==null?void 0:A.area)},[]);return e.jsx(ol,{scope:s,searchRef:xe,onItemEnter:i.useCallback(R=>{_(R)&&R.preventDefault()},[_]),onItemLeave:i.useCallback(R=>{var ue;_(R)||((ue=g.current)==null||ue.focus(),O(null))},[_]),onTriggerLeave:i.useCallback(R=>{_(R)&&R.preventDefault()},[_]),pointerGraceTimerRef:fe,onPointerGraceIntentChange:i.useCallback(R=>{d.current=R},[]),children:e.jsx(T,{...M,children:e.jsx(bn,{asChild:!0,trapped:r,onMountAutoFocus:ye(o,R=>{var ue;R.preventDefault(),(ue=g.current)==null||ue.focus({preventScroll:!0})}),onUnmountAutoFocus:x,children:e.jsx(Nn,{asChild:!0,disableOutsidePointerEvents:m,onEscapeKeyDown:u,onPointerDownOutside:w,onFocusOutside:y,onInteractOutside:j,onDismiss:v,children:e.jsx(Kn,{asChild:!0,...P,dir:c.dir,orientation:"vertical",loop:n,currentTabStopId:b,onCurrentTabStopIdChange:O,onEntryFocus:ye(h,R=>{c.isUsingKeyboardRef.current||R.preventDefault()}),preventScrollOnEntryFocus:!0,children:e.jsx(wn,{role:"menu","aria-orientation":"vertical","data-state":ir(L.open),"data-radix-menu-content":"",dir:c.dir,...f,...F,ref:B,style:{outline:"none",...F.style},onKeyDown:ye(F.onKeyDown,R=>{const te=R.target.closest("[data-radix-menu-content]")===R.currentTarget,A=R.ctrlKey||R.altKey||R.metaKey,$=R.key.length===1;te&&(R.key==="Tab"&&R.preventDefault(),!A&&$&&U(R.key));const Y=g.current;if(R.target!==Y||!el.includes(R.key))return;R.preventDefault();const re=D().filter(ne=>!ne.disabled).map(ne=>ne.ref.current);_a.includes(R.key)&&re.reverse(),Nl(re)}),onBlur:ye(t.onBlur,R=>{R.currentTarget.contains(R.target)||(window.clearTimeout(ie.current),xe.current="")}),onPointerMove:ye(t.onPointerMove,wt(R=>{const ue=R.target,te=z.current!==R.clientX;if(R.currentTarget.contains(ue)&&te){const A=R.clientX>z.current?"right":"left";q.current=A,z.current=R.clientX}}))})})})})})})});Ka.displayName=Ue;var ul="MenuGroup",Ns=i.forwardRef((t,a)=>{const{__scopeMenu:s,...n}=t;return e.jsx(Ae.div,{role:"group",...n,ref:a})});Ns.displayName=ul;var hl="MenuLabel",Va=i.forwardRef((t,a)=>{const{__scopeMenu:s,...n}=t;return e.jsx(Ae.div,{...n,ref:a})});Va.displayName=hl;var Lt="MenuItem",Ks="menu.itemSelect",Ht=i.forwardRef((t,a)=>{const{disabled:s=!1,onSelect:n,...r}=t,o=i.useRef(null),x=At(Lt,t.__scopeMenu),m=vs(Lt,t.__scopeMenu),h=et(a,o),u=i.useRef(!1),w=()=>{const y=o.current;if(!s&&y){const j=new CustomEvent(Ks,{bubbles:!0,cancelable:!0});y.addEventListener(Ks,v=>n==null?void 0:n(v),{once:!0}),kn(y,j),j.defaultPrevented?u.current=!1:x.onClose()}};return e.jsx(Qa,{...r,ref:h,disabled:s,onClick:ye(t.onClick,w),onPointerDown:y=>{var j;(j=t.onPointerDown)==null||j.call(t,y),u.current=!0},onPointerUp:ye(t.onPointerUp,y=>{var j;u.current||(j=y.currentTarget)==null||j.click()}),onKeyDown:ye(t.onKeyDown,y=>{const j=m.searchRef.current!=="";s||j&&y.key===" "||ms.includes(y.key)&&(y.currentTarget.click(),y.preventDefault())})})});Ht.displayName=Lt;var Qa=i.forwardRef((t,a)=>{const{__scopeMenu:s,disabled:n=!1,textValue:r,...o}=t,x=vs(Lt,s),m=za(s),h=i.useRef(null),u=et(a,h),[w,y]=i.useState(!1),[j,v]=i.useState("");return i.useEffect(()=>{const k=h.current;k&&v((k.textContent??"").trim())},[o.children]),e.jsx(Nt.ItemSlot,{scope:s,disabled:n,textValue:r??j,children:e.jsx(Vn,{asChild:!0,...m,focusable:!n,children:e.jsx(Ae.div,{role:"menuitem","data-highlighted":w?"":void 0,"aria-disabled":n||void 0,"data-disabled":n?"":void 0,...o,ref:u,onPointerMove:ye(t.onPointerMove,wt(k=>{n?x.onItemLeave(k):(x.onItemEnter(k),k.defaultPrevented||k.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:ye(t.onPointerLeave,wt(k=>x.onItemLeave(k))),onFocus:ye(t.onFocus,()=>y(!0)),onBlur:ye(t.onBlur,()=>y(!1))})})})}),pl="MenuCheckboxItem",Ga=i.forwardRef((t,a)=>{const{checked:s=!1,onCheckedChange:n,...r}=t;return e.jsx(Za,{scope:t.__scopeMenu,checked:s,children:e.jsx(Ht,{role:"menuitemcheckbox","aria-checked":zt(s)?"mixed":s,...r,ref:a,"data-state":Cs(s),onSelect:ye(r.onSelect,()=>n==null?void 0:n(zt(s)?!0:!s),{checkForDefaultPrevented:!1})})})});Ga.displayName=pl;var Ha="MenuRadioGroup",[gl,jl]=it(Ha,{value:void 0,onValueChange:()=>{}}),Wa=i.forwardRef((t,a)=>{const{value:s,onValueChange:n,...r}=t,o=sa(n);return e.jsx(gl,{scope:t.__scopeMenu,value:s,onValueChange:o,children:e.jsx(Ns,{...r,ref:a})})});Wa.displayName=Ha;var Ya="MenuRadioItem",Ja=i.forwardRef((t,a)=>{const{value:s,...n}=t,r=jl(Ya,t.__scopeMenu),o=s===r.value;return e.jsx(Za,{scope:t.__scopeMenu,checked:o,children:e.jsx(Ht,{role:"menuitemradio","aria-checked":o,...n,ref:a,"data-state":Cs(o),onSelect:ye(n.onSelect,()=>{var x;return(x=r.onValueChange)==null?void 0:x.call(r,s)},{checkForDefaultPrevented:!1})})})});Ja.displayName=Ya;var ws="MenuItemIndicator",[Za,fl]=it(ws,{checked:!1}),Xa=i.forwardRef((t,a)=>{const{__scopeMenu:s,forceMount:n,...r}=t,o=fl(ws,s);return e.jsx(qt,{present:n||zt(o.checked)||o.checked===!0,children:e.jsx(Ae.span,{...r,ref:a,"data-state":Cs(o.checked)})})});Xa.displayName=ws;var yl="MenuSeparator",er=i.forwardRef((t,a)=>{const{__scopeMenu:s,...n}=t;return e.jsx(Ae.div,{role:"separator","aria-orientation":"horizontal",...n,ref:a})});er.displayName=yl;var vl="MenuArrow",tr=i.forwardRef((t,a)=>{const{__scopeMenu:s,...n}=t,r=Gt(s);return e.jsx(Cn,{...r,...n,ref:a})});tr.displayName=vl;var bl="MenuSub",[$o,sr]=it(bl),ft="MenuSubTrigger",ar=i.forwardRef((t,a)=>{const s=lt(ft,t.__scopeMenu),n=At(ft,t.__scopeMenu),r=sr(ft,t.__scopeMenu),o=vs(ft,t.__scopeMenu),x=i.useRef(null),{pointerGraceTimerRef:m,onPointerGraceIntentChange:h}=o,u={__scopeMenu:t.__scopeMenu},w=i.useCallback(()=>{x.current&&window.clearTimeout(x.current),x.current=null},[]);return i.useEffect(()=>w,[w]),i.useEffect(()=>{const y=m.current;return()=>{window.clearTimeout(y),h(null)}},[m,h]),e.jsx(fs,{asChild:!0,...u,children:e.jsx(Qa,{id:r.triggerId,"aria-haspopup":"menu","aria-expanded":s.open,"aria-controls":r.contentId,"data-state":ir(s.open),...t,ref:rt(a,r.onTriggerChange),onClick:y=>{var j;(j=t.onClick)==null||j.call(t,y),!(t.disabled||y.defaultPrevented)&&(y.currentTarget.focus(),s.open||s.onOpenChange(!0))},onPointerMove:ye(t.onPointerMove,wt(y=>{o.onItemEnter(y),!y.defaultPrevented&&!t.disabled&&!s.open&&!x.current&&(o.onPointerGraceIntentChange(null),x.current=window.setTimeout(()=>{s.onOpenChange(!0),w()},100))})),onPointerLeave:ye(t.onPointerLeave,wt(y=>{var v,k;w();const j=(v=s.content)==null?void 0:v.getBoundingClientRect();if(j){const F=(k=s.content)==null?void 0:k.dataset.side,L=F==="right",c=L?-5:5,f=j[L?"left":"right"],P=j[L?"right":"left"];o.onPointerGraceIntentChange({area:[{x:y.clientX+c,y:y.clientY},{x:f,y:j.top},{x:P,y:j.top},{x:P,y:j.bottom},{x:f,y:j.bottom}],side:F}),window.clearTimeout(m.current),m.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(y),y.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:ye(t.onKeyDown,y=>{var v;const j=o.searchRef.current!=="";t.disabled||j&&y.key===" "||tl[n.dir].includes(y.key)&&(s.onOpenChange(!0),(v=s.content)==null||v.focus(),y.preventDefault())})})})});ar.displayName=ft;var rr="MenuSubContent",nr=i.forwardRef((t,a)=>{const s=Ba(Ue,t.__scopeMenu),{forceMount:n=s.forceMount,...r}=t,o=lt(Ue,t.__scopeMenu),x=At(Ue,t.__scopeMenu),m=sr(rr,t.__scopeMenu),h=i.useRef(null),u=et(a,h);return e.jsx(Nt.Provider,{scope:t.__scopeMenu,children:e.jsx(qt,{present:n||o.open,children:e.jsx(Nt.Slot,{scope:t.__scopeMenu,children:e.jsx(bs,{id:m.contentId,"aria-labelledby":m.triggerId,...r,ref:u,align:"start",side:x.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:w=>{var y;x.isUsingKeyboardRef.current&&((y=h.current)==null||y.focus()),w.preventDefault()},onCloseAutoFocus:w=>w.preventDefault(),onFocusOutside:ye(t.onFocusOutside,w=>{w.target!==m.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:ye(t.onEscapeKeyDown,w=>{x.onClose(),w.preventDefault()}),onKeyDown:ye(t.onKeyDown,w=>{var v;const y=w.currentTarget.contains(w.target),j=sl[x.dir].includes(w.key);y&&j&&(o.onOpenChange(!1),(v=m.trigger)==null||v.focus(),w.preventDefault())})})})})})});nr.displayName=rr;function ir(t){return t?"open":"closed"}function zt(t){return t==="indeterminate"}function Cs(t){return zt(t)?"indeterminate":t?"checked":"unchecked"}function Nl(t){const a=document.activeElement;for(const s of t)if(s===a||(s.focus(),document.activeElement!==a))return}function wl(t,a){return t.map((s,n)=>t[(a+n)%t.length])}function Cl(t,a,s){const r=a.length>1&&Array.from(a).every(u=>u===a[0])?a[0]:a,o=s?t.indexOf(s):-1;let x=wl(t,Math.max(o,0));r.length===1&&(x=x.filter(u=>u!==s));const h=x.find(u=>u.toLowerCase().startsWith(r.toLowerCase()));return h!==s?h:void 0}function Sl(t,a){const{x:s,y:n}=t;let r=!1;for(let o=0,x=a.length-1;o<a.length;x=o++){const m=a[o].x,h=a[o].y,u=a[x].x,w=a[x].y;h>n!=w>n&&s<(u-m)*(n-h)/(w-h)+m&&(r=!r)}return r}function kl(t,a){if(!a)return!1;const s={x:t.clientX,y:t.clientY};return Sl(s,a)}function wt(t){return a=>a.pointerType==="mouse"?t(a):void 0}var Pl=Ua,Al=fs,El=qa,Il=Ka,Dl=Ns,Fl=Va,Ml=Ht,$l=Ga,Ol=Wa,Tl=Ja,Rl=Xa,_l=er,Ll=tr,zl=ar,Ul=nr,Ss="DropdownMenu",[Bl,Oo]=Bt(Ss,[La]),Fe=La(),[ql,lr]=Bl(Ss),cr=t=>{const{__scopeDropdownMenu:a,children:s,dir:n,open:r,defaultOpen:o,onOpenChange:x,modal:m=!0}=t,h=Fe(a),u=i.useRef(null),[w=!1,y]=Ws({prop:r,defaultProp:o,onChange:x});return e.jsx(ql,{scope:a,triggerId:Je(),triggerRef:u,contentId:Je(),open:w,onOpenChange:y,onOpenToggle:i.useCallback(()=>y(j=>!j),[y]),modal:m,children:e.jsx(Pl,{...h,open:w,onOpenChange:y,dir:n,modal:m,children:s})})};cr.displayName=Ss;var or="DropdownMenuTrigger",dr=i.forwardRef((t,a)=>{const{__scopeDropdownMenu:s,disabled:n=!1,...r}=t,o=lr(or,s),x=Fe(s);return e.jsx(Al,{asChild:!0,...x,children:e.jsx(Ae.button,{type:"button",id:o.triggerId,"aria-haspopup":"menu","aria-expanded":o.open,"aria-controls":o.open?o.contentId:void 0,"data-state":o.open?"open":"closed","data-disabled":n?"":void 0,disabled:n,...r,ref:rt(a,o.triggerRef),onPointerDown:ye(t.onPointerDown,m=>{!n&&m.button===0&&m.ctrlKey===!1&&(o.onOpenToggle(),o.open||m.preventDefault())}),onKeyDown:ye(t.onKeyDown,m=>{n||(["Enter"," "].includes(m.key)&&o.onOpenToggle(),m.key==="ArrowDown"&&o.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(m.key)&&m.preventDefault())})})})});dr.displayName=or;var Kl="DropdownMenuPortal",mr=t=>{const{__scopeDropdownMenu:a,...s}=t,n=Fe(a);return e.jsx(El,{...n,...s})};mr.displayName=Kl;var xr="DropdownMenuContent",ur=i.forwardRef((t,a)=>{const{__scopeDropdownMenu:s,...n}=t,r=lr(xr,s),o=Fe(s),x=i.useRef(!1);return e.jsx(Il,{id:r.contentId,"aria-labelledby":r.triggerId,...o,...n,ref:a,onCloseAutoFocus:ye(t.onCloseAutoFocus,m=>{var h;
96x.current||(h=r.triggerRef.current)==null||h.focus(),x.current=!1,m.preventDefault()}),onInteractOutside:ye(t.onInteractOutside,m=>{const h=m.detail.originalEvent,u=h.button===0&&h.ctrlKey===!0,w=h.button===2||u;(!r.modal||w)&&(x.current=!0)}),style:{...t.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});ur.displayName=xr;var Vl="DropdownMenuGroup",Ql=i.forwardRef((t,a)=>{const{__scopeDropdownMenu:s,...n}=t,r=Fe(s);return e.jsx(Dl,{...r,...n,ref:a})});Ql.displayName=Vl;var Gl="DropdownMenuLabel",hr=i.forwardRef((t,a)=>{const{__scopeDropdownMenu:s,...n}=t,r=Fe(s);return e.jsx(Fl,{...r,...n,ref:a})});hr.displayName=Gl;var Hl="DropdownMenuItem",pr=i.forwardRef((t,a)=>{const{__scopeDropdownMenu:s,...n}=t,r=Fe(s);return e.jsx(Ml,{...r,...n,ref:a})});pr.displayName=Hl;var Wl="DropdownMenuCheckboxItem",gr=i.forwardRef((t,a)=>{const{__scopeDropdownMenu:s,...n}=t,r=Fe(s);return e.jsx($l,{...r,...n,ref:a})});gr.displayName=Wl;var Yl="DropdownMenuRadioGroup",Jl=i.forwardRef((t,a)=>{const{__scopeDropdownMenu:s,...n}=t,r=Fe(s);return e.jsx(Ol,{...r,...n,ref:a})});Jl.displayName=Yl;var Zl="DropdownMenuRadioItem",jr=i.forwardRef((t,a)=>{const{__scopeDropdownMenu:s,...n}=t,r=Fe(s);return e.jsx(Tl,{...r,...n,ref:a})});jr.displayName=Zl;var Xl="DropdownMenuItemIndicator",fr=i.forwardRef((t,a)=>{const{__scopeDropdownMenu:s,...n}=t,r=Fe(s);return e.jsx(Rl,{...r,...n,ref:a})});fr.displayName=Xl;var ec="DropdownMenuSeparator",yr=i.forwardRef((t,a)=>{const{__scopeDropdownMenu:s,...n}=t,r=Fe(s);return e.jsx(_l,{...r,...n,ref:a})});yr.displayName=ec;var tc="DropdownMenuArrow",sc=i.forwardRef((t,a)=>{const{__scopeDropdownMenu:s,...n}=t,r=Fe(s);return e.jsx(Ll,{...r,...n,ref:a})});sc.displayName=tc;var ac="DropdownMenuSubTrigger",vr=i.forwardRef((t,a)=>{const{__scopeDropdownMenu:s,...n}=t,r=Fe(s);return e.jsx(zl,{...r,...n,ref:a})});vr.displayName=ac;var rc="DropdownMenuSubContent",br=i.forwardRef((t,a)=>{const{__scopeDropdownMenu:s,...n}=t,r=Fe(s);return e.jsx(Ul,{...r,...n,ref:a,style:{...t.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});br.displayName=rc;var nc=cr,ic=dr,lc=mr,Nr=ur,wr=hr,Cr=pr,Sr=gr,kr=jr,Pr=fr,Ar=yr,Er=vr,Ir=br;const cc=nc,oc=ic,dc=i.forwardRef(({className:t,inset:a,children:s,...n},r)=>e.jsxs(Er,{ref:r,className:be("flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",a&&"pl-8",t),...n,children:[s,e.jsx(Ge,{className:"ml-auto"})]}));dc.displayName=Er.displayName;const mc=i.forwardRef(({className:t,...a},s)=>e.jsx(Ir,{ref:s,className:be("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-dropdown-menu-content-transform-origin]",t),...a}));mc.displayName=Ir.displayName;const Dr=i.forwardRef(({className:t,sideOffset:a=4,...s},n)=>e.jsx(lc,{children:e.jsx(Nr,{ref:n,sideOffset:a,className:be("z-50 max-h-[var(--radix-dropdown-menu-content-available-height)] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:sli
96de-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-dropdown-menu-content-transform-origin]",t),...s})}));Dr.displayName=Nr.displayName;const $t=i.forwardRef(({className:t,inset:a,...s},n)=>e.jsx(Cr,{ref:n,className:be("relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",a&&"pl-8",t),...s}));$t.displayName=Cr.displayName;const xc=i.forwardRef(({className:t,children:a,checked:s,...n},r)=>e.jsxs(Sr,{ref:r,className:be("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:s,...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Pr,{children:e.jsx(ns,{className:"h-4 w-4"})})}),a]}));xc.displayName=Sr.displayName;const uc=i.forwardRef(({className:t,children:a,...s},n)=>e.jsxs(kr,{ref:n,className:be("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Pr,{children:e.jsx(ii,{className:"h-2 w-2 fill-current"})})}),a]}));uc.displayName=kr.displayName;const hc=i.forwardRef(({className:t,inset:a,...s},n)=>e.jsx(wr,{ref:n,className:be("px-2 py-1.5 text-sm font-semibold",a&&"pl-8",t),...s}));hc.displayName=wr.displayName;const pc=i.forwardRef(({className:t,...a},s)=>e.jsx(Ar,{ref:s,className:be("-mx-1 my-1 h-px bg-muted",t),...a}));pc.displayName=Ar.displayName;const Fr={identity:"Mandala Naturals is a land-rooted cacao and functional chocolate company built around 6-day stone-ground cacao craft, botanical formulation intelligence, regenerative reciprocity, sensory pleasure, and daily ritual.",shortPublic:"Mandala Naturals is a true love story to the power and capabilities of cacao when tended and crafted in the most lovingly intentional way possible.",operational:"Mandala Naturals is the innovator in truly regenerative, highly nutritious, delectable chocolate and cacao bars.",category:"Category-disruptive premium functional regenerative cacao.",proofStack:[{name:"6-day stone grind",note:"72hr cacao alone, then 72hr with ingredients"},{name:"Maya Mountain Belize cacao",note:"single-origin via Uncommon Cacao"},{name:"Founder formulation method",note:"magnetic intuition + scientific verification"},{name:"Yacon",note:"non-glycemic root, prebiotic inulin"},{name:"Mandala Springs",note:"wild herbs + mushrooms, certified organic Appalachian forest farm"},{name:"Plastic-free plant-cellulose packaging",note:"surface where sustainability matters"},{name:"B Corp triple bottom line",note:"people, environment, profit"}],voice:["precise","warm","sensorial","grounded","casually expert","ingredient-literate","reverent without vague","confident without hype","alive","somatic","loud when it matters"],voiceEngine:["Product Ground","Living Context","Formulation Intelligence","Reframe","Invitation"],nonNegotiables:["Product clarity before philosophy","Taste before abstraction","Current facts or VERIFY","No 10% conservation donation language","No medical / disease / guaranteed-outcome claims","No invented testimonials, prices, ingredients, certifications","Sugar-free bars are the destination, not the entry point","Subscribers are the most valuable segment","DTC is the current growth priority"]},Mr=[{id:"ceremonial",name:"Ceremonial Cacao",lead:"Ceremonial Cacao, 1 lb disk",promise:"Raw, unroasted ceremonial cacao, stone-ground for 6 days total, crafted for daily ritual and deeper ceremony.",customer:"Ceremonial buyers · ritual-curious · high-margin DTC",proof:["100% cacao","Single-origin Maya Mountain Belize","via Uncommon Cacao","6-day stone grind"],ctas:["Begin With Ceremonial Cacao","Learn The Ritual","Subscribe For Monthly Ritual"],verify:["price","inventory","URL","
96subscription","prep guidance"]},{id:"sugarfree",name:"Sugar-Free Superfood Bars",lead:"Cacao Alchemy · Appalachian Wild Chai",promise:"Sugar-free functional cacao bars for the sophisticated palate, crafted with yacon and botanicals selected for synergy, depth, and daily ritual.",customer:"Functional buyers · adaptogen-curious · ready for bitters",proof:["Yacon as non-glycemic prebiotic","Chaga + reishi (Alchemy)","Wood betony + spiceberries (Wild Chai)","Founder formulation method"],ctas:["Taste The Functional Bars","Try The Sophisticated Palate Bundle","Subscribe To Your Functional Bars"],verify:["prices","active SKUs","ingredient lists","yacon language","nutrition + allergen"]},{id:"flavor",name:"Flavor-Focused Bars",lead:"Vanilla Orchid · Lavender Citrus · Cloud Forest",promise:"Premium chocolate bars with familiar pleasure, deeper craft, and Mandala's full intentionality.",customer:"Premium chocolate buyers · gift buyers · first-time customers",proof:["Familiar flavor","Single-origin cacao","6-day stone grind","Low-glycemic coconut sugar / honey"],ctas:["Start With The Flavor Bars","Find Your First Bar","Try The Variety Pack"],verify:["active flavor list","prices","ingredients","Cloud Forest conservation copy","subscription"]}],vt=[{id:1,name:"Low-Risk Cleanup",items:["Remove 10% donation language","Update 72hr â 6-day grind","Refresh /llms.txt"],status:"active",progress:.6},{id:2,name:"Product Page Updates",items:["Ceremonial Cacao","Cacao Alchemy","Appalachian Wild Chai"],status:"todo",progress:.15},{id:3,name:"Homepage Routing",items:["Three-path entry","Manifesto as variant"],status:"todo",progress:0},{id:4,name:"Subscriber Layer",items:["Product page modules","Cart upsell","Reorder email","Sub landing"],status:"todo",progress:0},{id:5,name:"Content",items:["6-day stone grind blog","Founder formulation blog","Social manifesto set"],status:"todo",progress:0}],$r=["cures","treats","prevents","heals","detoxes","reverses","eliminates","guarantees","boosts testosterone","fixes libido","balances hormones","restores libido","transforms your life","clinically proven","fixes digestion","10% goes to conservation","10% supports regenerative","10% donation","72-hour stone grind","72 hour stone grind","72hr stone grind"],Or=["adaptogen","testosterone","hormone","inflammation","libido","anandamide","heart opener","vasodilator","calm, clean, sustained energy","nervous-system support","digestive support","respiratory support","immune support","bioavailability","10-micron","enzymatic","no glycemic impact","keto","paleo","raw"],Tr=["6-day stone grind","Maya Mountain","Uncommon Cacao","yacon","Mandala Springs","foun
96der formulation","plastic-free plant-cellulose","B Corp","single-origin","Cacao Alchemy","Appalachian Wild Chai","Ceremonial Cacao"],Rr=[["cures / treats / prevents","crafted with · designed for · selected for its role in"],["72-hour stone grind","6-day stone grind"],["10% goes to conservation","regenerative practices · wild harvest · plastic-free packaging"],["boosts energy","many people enjoy it as · can support a daily ritual"],["clinically proven","traditionally used for · associated with"]],xs=[{id:"t1",title:"Ceremonial Cacao PDP â replace 72hr grind copy",phase:2,owner:"Andrew",verify:2},{id:"t2",title:"Cloud Forest â strip donation-percentage line",phase:1,owner:"Andrew",verify:1},{id:"t3",title:"/llms.txt â review claims block, push",phase:1,owner:"Andrew",verify:0},{id:"t4",title:"Cacao Alchemy PDP â yacon section + sub module",phase:2,owner:"Andrew",verify:4},{id:"t5",title:"Homepage 3-path router (variant A)",phase:3,owner:"Andrew",verify:0}],gc=[{num:1,title:"Strip 10% donation language",tag:"restricted",note:"4 pages still mention it",surfaces:"/products/cloud-forest · /our-story · /shop · /llms.txt",cta:"Run check â"},{num:2,title:"72-hour â 6-day stone grind",tag:"restricted",note:"copy out of date on 6 pages",surfaces:"/products/* · /process · email footer · /llms.txt",cta:"Run check â"},{num:3,title:"Refresh /llms.txt",tag:"todo",note:"needs claim review before push",surfaces:"layer-a-llms-txt/llms.txt",cta:"Preview â"}],Xt=[{id:"backlog",name:"Backlog"},{id:"doing",name:"In Progress"},{id:"review",name:"Awaiting Rob"},{id:"done",name:"Shipped"}],jc=[{id:"k1",phase:1,title:"Strip 10% donation line · Cloud Forest PDP",owner:"Andrew",verify:0,claim:"restricted",tag:"copy"},{id:"k2",phase:1,title:"Strip 10% donation line · /our-story",owner:"Andrew",verify:0,claim:"restricted",tag:"copy"},{id:"k3",phase:1,title:"Replace 72hr â 6-day grind · email footer",owner:"Andrew",verify:0,claim:"restricted",tag:"copy"},{id:"k4",phase:1,title:"/llms.txt refresh · claim review pass",owner:"Andrew",verify:2,claim:"caution",tag:"seo"},{id:"k5",phase:2,title:"Ceremonial Cacao PDP rewrite",owner:"Andrew",verify:2,claim:"ok",tag:"PDP"},{id:"k6",phase:2,title:"Cacao Alchemy PDP · yacon section + sub module",owner:"Andrew",verify:4,claim:"caution",tag:"PDP"},{id:"k7",phase:2,title:"Appalachian Wild Chai PDP rewrite",owner:"Andrew",verify:3,claim:"caution",tag:"PDP"},{id:"k8",phase:3,title:"Three-path homepage router (variant A)",owner:"Andrew",verify:0,claim:"ok",tag:"homepage"},{id:"k9",phase:3,title:"Manifesto homepage variant (A/B)",owner:"Andrew",verify:1,claim:"ok",tag:"homepage"},{id:"k10",phase:4,title:"Subscription module · Ceremonial Cacao PDP",owner:"Andrew",verify:2,claim:"ok",tag:"subs"},{id:"k11",phase:4,title:"Reorder reminder email",owner:"Andrew",verify:1,claim:"ok",tag:"email"},{id:"k12",phase:4,title:"Cart upsell · subscribe & save",owner:"Andrew",verify:1,claim:"ok",tag:"cart"},{id:"k13",phase:5,title:"Blog: 6-day stone grind",owner:"Andrew",verify:0,claim:"caution",tag:"blog"},{id:"k14",phase:5,title:"Blog: founder formulation method",owner:"Andrew",verify:1,claim:"caution",tag:"blog"},{id:"k15",phase:5,title:"Social manifesto set · 6 posts",owner:"Andrew",verify:0,claim:"ok",tag:"social"}],es={k1:"doing",k2:"review",k3:"doing",k4:"backlog",k5:"doing",k6:"backlog",k7:"backlog",k8:"backlog",k9:"backlog",k10:"backlog",k11:"backlog",k12:"backlog",k13:"backlog",k14:"backlog",k15:"done"},Vs={1:"#fce8d8",2:"#fde9b8",3:"#d8e6cf",4:"#cfd9ea",5:"#e6d5e2"},Ct=[{heading:"1. One-Sentence Identity",body:Fr.identity},{heading:"2. Operational Identity",body:"Mandala Naturals is the innovator in truly regenerative, highly nutritious, delectable chocolate and cacao bars."},{heading:"3. Website Proof Stack",body:"Use these proof points repeatedly: 6-day stone grind. Maya Mountain Belize cacao via Uncommon Cacao. Founder formulation method â magnetic intuition plus scientific verification. Yacon as non-glycemic prebiotic. Mandala Springs wild harvest. Plastic-free plant-cellulose packaging. B Corp triple bottom line. The 10% conservation donation is paused â do not publish that language."},{heading:"4. Voice",body:"Precise. Warm. Sensorial. Grounded. Casually expert. Ingredient-literate. Reverent without being vague. Confident without hype. Alive. Somatic. Loud when it matters."},{heading:"5. Voice Engine",body:"Product Ground â Living Context â Formulation Intelligence â Reframe â Invitation. Start with the actual product or use moment, widen into body, land, ritual, craft, or sourcing, explain why the formulation matters, reframe chocolate as cacao, invite the customer to a clear next step."},{heading:"6. Non-Negotiables",body:"Product clarity before philosophy. Taste before abstraction. Current facts or VERIFY. No 10% conservation donation language. No medical, disease, or guaranteed-outcome claims. Sugar-free bars are for the sophisticated palate, not the entry point. Subscribers are the most valuable customer segment. DTC is the current growth priority."}],_r=["01-brand-core.md","02-website-copy-rules.md","03-product-and-funnel-brain.md","04-claims-and-verify.md","05-page-payload-index.md","06-andrew-implementation-map.md"];var Lr="AlertDialog",[fc,To]=Bt(Lr,[aa]),We=aa(),zr=t=>{const{__scopeAlertDialog:a,...s}=t,n=We(a);return e.jsx(Js,{...n,...s,modal:!0})};zr.displayName=Lr;var yc="AlertDialogTrigger",Ur=i.forwardRef((t,a)=>{const{__scopeAlertDialog:s,...n}=t,r=We(s);return e.jsx(In,{...r,...n,ref:a})});Ur.displayName=yc;var vc="AlertDialogPortal",Br=t=>{const{__scopeAlertDialog:a,...s}=t,n=We(a);return e.jsx(Zs,{...n,...s})};Br.displayName=vc;var bc="AlertDialogOverlay",qr=i.forwardRef((t,a)=>{const{__scopeAlertDialog:s,...n}=t,r=We(s);return e.jsx(Xs,{...r,...n,ref:a})});qr.displayName=bc;var ut="AlertDialogContent",[Nc,wc]=fc(ut),Cc=$n("AlertDialogContent"),Kr=i.forwardRef((t,a)=>{const{__scopeAlertDialog:s,children:n,...r}=t,o=We(s),x=i.useRef(null),m=et(a,x),h=i.useRef(null);return e.jsx(Dn,{contentName:ut,titleName:Vr,docsSlug:"alert-dialog",children:e.jsx(Nc,{scope:s,cancelRef:h,children:e.jsxs(ea,{role:"alertdialog",...o,...r,ref:m,onOpenAutoFocus:ye(r.onOpenAutoFocus,u=>{var w;u.preventDefault(),(w=h.current)==null||w.focus({preventScroll:!0})}),onPointerDownOutside:u=>u.preventDefault(),onInteractOutside:u=>u.preventDefault(),children:[e.jsx(Cc,{children:n}),e.jsx(kc,{contentRef:x})]})})})});Kr.displayName=ut;var Vr="AlertDialogTitle",Qr=i.forwardRef((t,a)=>{const{__scopeAlertDialog:s,...n}=t,r=We(s);return e.jsx(Fn,{...r,...n,ref:a})});Qr.displayName=Vr;var Gr="AlertDialogDescription",Hr=i.forwardRef((t,a)=>{const{__scopeAlertDialog:s,...n}=t,r=We(s);return e.jsx(Mn,{...r,...n,ref:a})});Hr.displayName=Gr;var Sc="AlertDialogAction",Wr=i.forwardRef((t,a)=>{const{__scopeAlertDialog:s,...n}=t,r=We(s);return e.jsx(ra,{...r,...n,ref:a})});Wr.displayName=Sc;var Yr="AlertDialogCancel",Jr=i.forwardRef((t,a)=>{const{__scopeAlertDialog:s,...n}=t,{cancelRef:r}=wc(Yr,s),o=We(s),x=et(a,r);return e.jsx(ra,{...o,...n,ref:x})});Jr.displayName=Yr;var kc=({contentRef:t})=>{const a=`\`${ut}\` requires a description for the component to be accessible for screen reader users. 97
98You can add a description to the \`${ut}\` by passing a \`${Gr}\` component as a child, which also benefits sighted users by adding visible context to the dialog. 99 100Alternatively, you can use your own component as a description by assigning it an \`id\` and passing the same value to the \`aria-describedby\` prop in \`${ut}\`. If the description is confusing or duplicative for sighted users, you can use the \`@radix-ui/react-visually-hidden\` primitive as a wrapper around your description component. 101 102For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return i.useEffect(()=>{var n;document.getElementById((n=t.current)==null?void 0:n.getAttribute("aria-describedby"))||console.warn(a)},[a,t]),null},Pc=zr,Ac=Ur,Ec=Br,Zr=qr,Xr=Kr,en=Wr,tn=Jr,sn=Qr,an=Hr;const Ic=Pc,Dc=Ac,Fc=Ec,rn=i.forwardRef(({className:t,...a},s)=>e.jsx(Zr,{className:be("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...a,ref:s}));rn.displayName=Zr.displayName;const nn=i.forwardRef(({className:t,...a},s)=>e.jsxs(Fc,{children:[e.jsx(rn,{}),e.jsx(Xr,{ref:s,className:be("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...a})]}));nn.displayName=Xr.displayName;const ln=({className:t,...a})=>e.jsx("div",{className:be("flex flex-col space-y-2 text-center sm:text-left",t),...a});ln.displayName="AlertDialogHeader";const cn=({className:t,...a})=>e.jsx("div",{className:be("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...a});cn.displayName="AlertDialogFooter";const on=i.forwardRef(({className:t,...a},s)=>e.jsx(sn,{ref:s,className:be("text-lg font-semibold",t),...a}));on.displayName=sn.displayName;const dn=i.forwardRef(({className:t,...a},s)=>e.jsx(an,{ref:s,className:be("text-sm text-muted-foreground",t),...a}));dn.displayName=an.displayName;const mn=i.forwardRef(({className:t,...a},s)=>e.jsx(en,{ref:s,className:be(na(),t),...a}));mn.displayName=en.displayName;const xn=i.forwardRef(({className:t,...a},s)=>e.jsx(tn,{ref:s,className:be(na({variant:"outline"}),"mt-2 sm:mt-0",t),...a}));xn.displayName=tn.displayName;const ks=[...$r.map(t=>({t,k:"restricted"})),...Or.map(t=>({t,k:"caution"})),...Tr.map(t=>({t,k:"proof"}))].sort((t,a)=>a.t.length-t.t.length),Qs=new RegExp("("+ks.map(t=>t.t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|")+")","gi"),Mc=new Map(ks.map(t=>[t.t.toLowerCase(),t.k])),$e={restricted:"bg-red-100 text-red-900 px-1 rounded line-through decoration-red-700",caution:"bg-amber-100 text-amber-900 px-1 rounded",proof:"bg-emerald-100 text-emerald-900 px-1 rounded"};function qe({text:t,on:a}){if(!a)return t;const s=[];let n=0,r,o=0;for(Qs.lastIndex=0;(r=Qs.exec(t))!==null;){r.index>n&&s.push(t.slice(n,r.index));const x=Mc.get(r[0].toLowerCase());x?s.push(e.jsx("span",{className:$e[x],children:r[0]},o++)):s.push(r[0]),n=r.index+r[0].length}return n<t.length&&s.push(t.slice(n)),e.jsx(i.Fragment,{children:s})}function un({compact:t=!1}){return e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-2",children:vt.map(a=>{const s=a.status==="active";return e.jsxs("div",{className:`border rounded-md p-3 ${s?"border-amber-400 bg-amber-50":"border-gray-200 bg-white"}`,"data-testid":`phase-${a.id}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-xs font-mono text-gray-500",children:a.id}),s?e.jsx(H,{className:"bg-amber-200 text-amber-900 hover:bg-amber-200 text-[10px] uppercase",children:"Active"}):e.jsx(H,{variant:"outline",className:"text-[10px] uppercase text-gray-500",children:"Todo"})]}),e.jsx("div",{className:"font-serif text-sm font-semibold text-gray-900 leading-tight",children:a.name}),!t&&e.jsx("ul",{className:"mt-2 space-y-0.5 text-[11px] text-gray-600",children:a.items.slice(0,3).map(n=>e.jsxs("li",{className:"truncate",children:["· ",n]},n))}),e.jsx("div",{className:"mt-2 h-1 bg-gray-100 rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full ${s?"bg-amber-500":"bg-gray-300"}`,style:{width:`${Math.round(a.progress*100)}%`}})})]},a.id)})})}function Ut({color:t="amber",children:a}){const s={amber:"bg-amber-100 border-amber-300 text-amber-950",blue:"bg-sky-50 border-sky-300 text-sky-950",green:"bg-emerald-50 border-emerald-300 text-emerald-950"};return e.jsx("div",{className:`border-2 ${s[t]} rounded-md p-4 text-sm shadow-sm`,children:a})}function $c(){return e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 ga
102p-3",children:vt.map(t=>{const a=t.status==="active";return e.jsxs("div",{className:"ba-box",style:{padding:"12px 14px 0",background:a?"#fde7a8":"var(--ba-paper)",minHeight:96,display:"flex",flexDirection:"column"},"data-testid":`phase-${t.id}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"ba-caveat",style:{fontSize:32,lineHeight:1},children:t.id}),e.jsx("span",{className:`ba-tag ${a?"":"ba-tag--todo"}`,style:a?{background:"var(--ba-ink)",color:"var(--ba-paper)"}:void 0,children:a?"Active":"Todo"})]}),e.jsx("div",{className:"ba-caveat",style:{fontSize:20,lineHeight:1.05,marginTop:4},children:t.name}),e.jsx("div",{style:{flex:1}}),e.jsx("div",{className:"ba-progress",style:{marginTop:10},children:e.jsx("span",{style:{width:`${Math.round(t.progress*100)}%`}})})]},t.id)})})}function Oc({num:t,title:a,tag:s,note:n,surfaces:r,cta:o,checkType:x}){var k;const[m,h]=i.useState(null),[u,w]=i.useState(null),y=ee({mutationFn:async()=>x==="preview-llms"?await(await ae("POST","/api/admin/brand-authority/preview-llms",{})).json():await(await ae("POST","/api/admin/brand-authority/run-check",{checkType:x})).json(),onSuccess:F=>{x==="preview-llms"?(w(F),h(null)):(h(F),w(null))}}),j=x==="preview-llms",v=y.isPending;return e.jsxs("div",{className:"ba-box ba-box--corner","data-corner":`cleanup #${t}`,"data-testid":`cleanup-${t}`,children:[e.jsx("div",{className:"ba-caveat",style:{fontSize:24,marginBottom:8},children:a}),e.jsxs("div",{className:"flex items-center gap-2 mb-2",style:{flexWrap:"wrap"},children:[e.jsx("span",{className:`ba-tag ${s==="restricted"?"ba-tag--restricted":"ba-tag--todo"}`,children:s.toUpperCase()}),e.jsx("span",{style:{fontSize:12,color:"var(--ba-muted)"},children:n})]}),e.jsx("div",{className:"ba-mono",style:{marginBottom:12,wordBreak:"break-word"},children:r}),e.jsxs(Ic,{children:[e.jsx(Dc,{asChild:!0,children:e.jsxs("button",{type:"button",className:`ba-btn ${j?"":"ba-btn--primary"}`,disabled:v,"data-testid":`button-cleanup-${t}`,children:[v?e.jsx(On,{className:"w-3.5 h-3.5 animate-spin"}):j?e.jsx(ht,{className:"w-3.5 h-3.5"}):null,v?"Scanningâ¦":o]})}),e.jsxs(nn,{"data-testid":`dialog-cleanup-${t}`,children:[e.jsxs(ln,{children:[e.jsx(on,{children:j?"Preview /llms.txt?":`Run check: ${a}?`}),e.jsx(dn,{asChild:!0,children:e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("p",{children:["This is a ",e.jsx("span",{className:"font-semibold",children:"read-only"})," scan. It looks at your source files, product database rows, and the live /llms.txt output, then reports anywhere these phrases appear."]}),e.jsx("p",{className:"font-semibold text-gray-900",children:"Nothing on the public website will change."}),!j&&e.jsxs("p",{className:"text-xs text-gray-600",children:["Surfaces watched: ",e.jsx("span",{className:"font-mono",children:r})]})]})})]}),e.jsxs(cn,{children:[e.jsx(xn,{"data-testid":`button-cancel-${t}`,children:"Cancel"}),e.jsx(mn,{onClick:()=>y.mutate(),"data-testid":`button-approve-${t}`,children:"Approve & run"})]})]})]}),y.isError&&e.jsxs("div",{className:"ba-mono",style:{marginTop:12,color:"var(--ba-warn)",background:"#fbe8e3",border:"1.2px solid var(--ba-warn)",padding:"6px 8px"},children:["Scan failed: ",((k=y.error)==null?void 0:k.message)??"unknown"]}),m&&e.jsxs("div",{className:"ba-box",style:{marginTop:14,padding:10,background:"var(--ba-paper-3)"},"data-testid":`findings-${t}`,children:[e.jsx("div",{className:"flex items-center gap-2 mb-2",children:m.summary.totalFindings===0?e.jsxs(e.Fragment,{children:[e.jsx(ga,{className:"w-4 h-4",style:{color:"var(--ba-ok)"}}),e.jsx("span",{style:{color:"var(--ba-ok)",fontWeight:600,fontSize:13},children:"Clean â no occurrences found"})]}):e.jsxs(e.Fragment,{children:[e.jsx(xa,{className:"w-4 h-4",style:{color:"var(--ba-warn)"}}),e.jsxs("span",{style:{color:"var(--ba-warn)",fontWeight:600,fontSize:13},children:[m.summary.totalFindings," occurrences in ",m.summary.sourcesWithFindings," sources"]})]})}),e.jsx("div",{style:{maxHeight:180,overflowY:"auto"},children:m.findings.slice(0,12).map((F,L)=>e.jsxs("div",{className:"ba-find-row",children:[e.jsxs("div",{className:"ba-mono",style:{color:"var(--ba-ink)"},children:[F.source,F.line?`:${F.line}`:""]}),e.jsxs("div",{style:{fontSize:12,color:"var(--ba-muted)",marginTop:2},children:["â¦",F.snippet,"â¦"]})]},L))})]}),u&&e.jsxs("div",{className:"ba-box",style:{marginTop:14,padding:10,background:"var(--ba-paper-3)"},"data-testid":`preview-${t}`,children:[e.jsxs("div",{className:"ba-mono",style:{marginBottom:6}
102,children:[u.url," · v",u.version," · ",u.length.toLocaleString()," chars"]}),e.jsxs("pre",{style:{maxHeight:220,overflow:"auto",fontSize:11,lineHeight:1.5,fontFamily:'"JetBrains Mono", monospace',background:"var(--ba-paper)",border:"1px dashed var(--ba-ink)",padding:8,margin:0,whiteSpace:"pre-wrap"},children:[u.contents.slice(0,1200),u.contents.length>1200?` 103â¦`:""]})]})]})}function Tc(t){return e.jsxs("div",{className:"ba-paper","data-testid":"direction-a",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",style:{marginBottom:24},children:[e.jsxs("div",{children:[e.jsx("h1",{className:"ba-title",children:"Brand Authority"}),e.jsx("div",{className:"ba-sub",children:"The CEO's voice, in one place. Read it. Then build."})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("button",{type:"button",className:"ba-btn",onClick:t.onOpenSearch,children:[e.jsx(He,{className:"w-3.5 h-3.5"}),"Search"]}),e.jsx("button",{type:"button",className:"ba-btn",onClick:t.onUpload,"data-testid":"button-upload-md",children:"Upload md"}),e.jsxs("button",{type:"button",className:"ba-btn ba-btn--primary",onClick:t.onOpenClaimChecker,"data-testid":"button-open-claim-checker",children:["Open Claim Checker",e.jsx(us,{className:"w-3.5 h-3.5"})]})]})]}),e.jsxs("div",{className:"grid gap-5",style:{gridTemplateColumns:"minmax(0,1fr) 320px",marginBottom:28},children:[e.jsxs("div",{className:"ba-box ba-box--corner","data-corner":"who we are",children:[e.jsx("p",{className:"ba-caveat",style:{fontSize:26,lineHeight:1.35,margin:"8px 0 0"},children:e.jsx(qe,{text:Fr.identity,on:t.vocab})}),e.jsxs("p",{className:"ba-mono",style:{marginTop:18},children:["Source: 01-brand-core.md · approved by Rob · last updated"," ",t.lastUpdatedLabel]})]}),e.jsxs("div",{className:"ba-sticky","data-testid":"andrew-sticky",children:[e.jsx("strong",{children:"Andrew â"}),e.jsx("div",{style:{marginTop:6},children:"Use this page as your North Star. If a page or paste fails the rules here, fix it before shipping."}),e.jsx("div",{style:{marginTop:8,fontSize:16},children:"â Rob"})]})]}),e.jsx("h2",{className:"ba-h",children:"What to fix today"}),e.jsx("div",{className:"grid gap-4",style:{gridTemplateColumns:"repeat(3, minmax(0, 1fr))",marginBottom:28},children:gc.map(a=>{const s=a.num===1?"10pct":a.num===2?"72hr":"preview-llms";return e.jsx(Oc,{num:a.num,title:a.title,tag:a.tag,note:a.note,surfaces:a.surfaces,cta:a.cta,checkType:s},a.num)})}),e.jsx("h2",{className:"ba-h",children:"Implementation phases"}),e.jsx("div",{style:{marginBottom:28},children:e.jsx($c,{})}),e.jsx("h2",{className:"ba-h",children:"The brand authority document"}),e.jsxs("div",{className:"ba-box",style:{padding:22},children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",style:{paddingBottom:12,marginBottom:16,borderBottom:"1.2px dashed var(--ba-ink)"},children:[_r.map(a=>e.jsx("span",{className:"ba-tag",children:a},a)),e.jsx("span",{style:{flex:1}}),e.jsxs("span",{className:"ba-mono",children:[t.docChars.toLocaleString()," chars"]})]}),e.jsx("div",{className:"space-y-5",children:Ct.map(a=>e.jsxs("div",{children:[e.jsx("h3",{className:"ba-h",style:{fontSize:22,marginBottom:4},children:a.heading}),e.jsx("p",{style:{fontSize:14,lineHeight:1.6,color:"var(--ba-ink)",margin:0},children:e.jsx(qe,{text:a.body,on:t.vocab})})]},a.heading))})]})]})}function Rc(t){return e.jsxs("div",{className:"space-y-6","data-testid":"direction-b",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-serif font-semibold text-gray-900",children:"Brand Authority"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Authority + workflow. Andrew's implementation cockpit."})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(C,{variant:"outline",size:"sm",onClick:t.onOpenSearch,children:[e.jsx(He,{className:"w-4 h-4 mr-1.5"}),"Search"]}),e.jsxs(C,{variant:"outline",size:"sm",onClick:t.onDownload,disabled:!t.docDraft,children:[e.jsx(ps,{className:"w-4 h-4 mr-1.5"}),"Download"]})]})]}),e.jsxs(G,{className:"border-gray-300",children:[e.jsx(je,{className:"pb-2",children:e.jsx("div",{className:"text-[11px] font-mono uppercase tracking-wide text-gray-500",children:"implementation phases"})}),e.jsxs(Q,{children:[e.jsx(un,{}),e.jsxs("div",{className:"flex items-center justify-between mt-3 text-xs",children:[e.jsx("span",{className:"text-gray-600",children:"Phase 1 active · 60% complete · 3 of 5 phases not started"}),e.jsx("span",{className:"font-mono text-amber-700",children:"view full plan â"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[1.2fr_0.9fr] gap-5",children:[e.jsxs(G,{className:"border-gray-300",children:[e.jsx(je,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] font-mono uppercase tracking-wide text-gray-500",children:"active tasks"}),e.jsx(Pe,{className:"text-base mt-1",children:"What Andrew is building this week"})]}),e.jsxs(H,{variant:"outline",className:"text-xs",children:[xs.length," open"]})]})}),e.jsx(Q,{children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-left text-xs text-gray-500 uppercase",children:[e.jsx("th",{className:"py-2 pr-2 font-medium",children:"Task"}),e.jsx("th",{className:"py-2 px-2 font-medium w-16",children:"Phase"}),e.jsx("th",{className:"py-2 px-2 font-medium w-24",children:"Verify"}),e.jsx("th",{className:"py-2 pl-2 w-20"})]})}),e.jsx("tbody",{children:xs.map(s=>e.jsxs("tr",{className:"border-b border-dashed last:border-b-0",children:[e.jsxs("td",{className:"py-2.5 pr-2",children:[e.jsx("div",{className:"text-gray-900",children:e.jsx(qe,{text:s.title,on:t.vocab})}),e.jsxs("div",{className:"text-[11px] text-gray-500",children:["owner · ",s.owner]})]}),e.jsx("td",{className:"py-2.5 px-2",children:e.jsxs(H,{variant:"outline",className:"text-[10px] font-mono",children:["P",s.phase]})}),e.jsx("td",{className:"py-2.5 px-2",children:s.verify>
1030?e.jsxs(H,{className:"bg-amber-100 text-amber-900 hover:bg-amber-100 border-amber-200 text-[10px]",children:[s.verify," items"]}):e.jsx(H,{className:"bg-emerald-100 text-emerald-900 hover:bg-emerald-100 border-emerald-200 text-[10px]",children:"clear"})}),e.jsx("td",{className:"py-2.5 pl-2"})]},s.id))})]})})]}),e.jsxs(G,{className:"border-gray-300 bg-gray-50",children:[e.jsx(je,{className:"pb-2",children:e.jsx("div",{className:"text-[11px] font-mono uppercase tracking-wide text-gray-500",children:"claim checker · paste & check"})}),e.jsxs(Q,{children:[e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:"Drop any draft copy. We highlight restricted words, suggest replacements, and surface VERIFY items."}),e.jsx("div",{className:"border-2 border-dashed border-gray-300 bg-white rounded-md p-3 text-sm leading-relaxed min-h-[110px]",children:e.jsx(qe,{text:"Our 72-hour stone grind cacao bars boost testosterone and 10% goes to conservation. Made with yacon and Mandala Springs reishi at our Maya Mountain Belize source.",on:!0})}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 flex-wrap",children:[e.jsx(H,{className:"bg-red-100 text-red-900 hover:bg-red-100 border-red-200 text-[10px]",children:"3 restricted"}),e.jsx(H,{variant:"outline",className:"text-[10px]",children:"2 caution"}),e.jsx(H,{className:"bg-emerald-100 text-emerald-900 hover:bg-emerald-100 border-emerald-200 text-[10px]",children:"3 proof"}),e.jsx("span",{className:"flex-1"}),e.jsxs(C,{size:"sm",onClick:t.onOpenClaimChecker,"data-testid":"button-open-full-checker",children:["Open full checker",e.jsx(us,{className:"w-4 h-4 ml-1.5"})]})]})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-serif font-semibold text-gray-900 mb-3",children:"Three traffic paths · the V3 routing"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:Mr.map(s=>e.jsxs(G,{className:"border-gray-300","data-testid":`funnel-${s.id}`,children:[e.jsxs(je,{className:"pb-2",children:[e.jsx("div",{className:"text-[11px] font-mono uppercase tracking-wide text-gray-500",children:s.id}),e.jsx(Pe,{className:"text-base mt-0.5",children:s.name}),e.jsx("p",{className:"text-xs text-gray-500",children:s.customer})]}),e.jsxs(Q,{className:"space-y-3",children:[e.jsx("p",{className:"text-sm leading-relaxed text-gray-700",children:e.jsx(qe,{text:s.promise,on:t.vocab})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase font-mono text-gray-500 mb-1",children:"Proof"}),s.proof.map((n,r)=>e.jsxs("div",{className:"text-xs text-gray-700",children:["· ",e.jsx(qe,{text:n,on:t.vocab})]},r))]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase font-mono text-gray-500 mb-1",children:"CTAs"}),s.ctas.map((n,r)=>e.jsxs("div",{className:"text-xs text-gray-700",children:["â ",n]},r))]}),e.jsxs("div",{className:"text-[11px] border-t border-dashed pt-2 text-gray-600",children:[e.jsx("span",{className:"bg-amber-100 text-amber-900 px-1 rounded font-mono mr-1",children:"VERIFY:"}),s.verify.join(" · ")]})]})]},s.id))})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[1.4fr_1fr] gap-5",children:[e.jsxs(G,{className:"border-gray-300",children:[e.jsx(je,{className:"pb-2",children:e.jsx("div",{className:"text-[11px] font-mono uppercase tracking-wide text-gray-500",children:"preferred language"})}),e.jsx(Q,{children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-left text-xs text-gray-500 uppercase",children:[e.jsx("th",{className:"py-2 pr-2 font-medium w-2/5",children:"Don't say"}),e.jsx("th",{className:"py-2 pl-2 font-medium",children:"Say instead"})]})}),e.jsx("tbody",{children:Rr.map(([s,n],r)=>e.jsxs("tr",{className:"border-b border-dashed last:border-b-0 align-top",children:[e.jsx("td",{className:"py-2 pr-2",children:e.jsx("span",{className:$e.restricted,children:s})}),e.jsx("td",{className:"py-2 pl-2",children:e.jsx("span",{className:$e.proof,children:n})})]},r))})]})})]}),e.jsxs(G,{className:"border-gray-300 border-dashed",children:[e.jsx(je,{className:"pb-2",children:e.jsx("div",{className:"text-[11px] font-mono uppercase tracking-wide text-gray-500",children:"source files"})}),e.jsxs(Q,{children:[e.jsx("p",{className:"text-xs text-gray-600 mb-2",children:"CEO markdown â read order"}),e.jsx("ol",{className:"space-y-1 list-decimal list-inside font-mono text-xs text-gray-700",children:_r.map(s=>e.jsx("li",{children:s},s))}),e.jsxs("p",{className:"text-[11px] text-gray-500 mt-3",children:["last commit · Rob · ",t.lastUpdatedLabel]})]})]})]})]})}function _c(t){return e.jsxs("div",{className:"space-y-5","data-testid":"direction-c",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-serif font-semibold text-gray-900",children:"Brand Authority â Cockpit"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Document · phases · claim rules · funnels · tasks. Single surface."})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(C,{variant:"outline",size:"sm",onClick:t.onOpenSearch,children:[e.jsx(He,{className:"w-4 h-4 mr-1.5"}),"Search"]}),e.jsxs(C,{variant:"outline",size:"sm",onClick:t.onDownload,disabled:!t.docDraft,children:[e.jsx(ps,{className:"w-4 h-4 mr-1.5"}),"Download"]}),e.jsxs(C,{variant:"outline",size:"sm",onClick:()=>t.setVocab(!t.vocab),children:[e.jsx(ss,{className:"w-4 h-4 mr-1.5"}),"Highlight vocab ",t.vocab?"ON":"OFF"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsx(G,{className:"border-gray-300",children:e.jsxs(Q,{className:"p-3",children:[e.jsx("div",{className:"text-[10px] font-mono uppercase tracking-wider text-gray-500",children:"Document"}),e.jsxs("div",{className:"font-serif text-2xl text-gray-900 leading-tight mt-0.5",children:["v3 · ",t.docChars.toLocaleStr
103ing()," chars"]}),e.jsxs("div",{className:"text-[11px] text-gray-500 mt-1",children:["6 markdown files · last commit ",t.lastUpdatedLabel]})]})}),e.jsx(G,{className:"border-gray-300",children:e.jsxs(Q,{className:"p-3",children:[e.jsx("div",{className:"text-[10px] font-mono uppercase tracking-wider text-gray-500",children:"Claims"}),e.jsx("div",{className:"font-serif text-2xl text-gray-900 leading-tight mt-0.5",children:"2 restricted on site"}),e.jsx("div",{className:"text-[11px] text-gray-500 mt-1",children:"10% donation · 72-hour grind"})]})}),e.jsx(G,{className:"border-gray-300",children:e.jsxs(Q,{className:"p-3",children:[e.jsx("div",{className:"text-[10px] font-mono uppercase tracking-wider text-gray-500",children:"Phase"}),e.jsx("div",{className:"font-serif text-2xl text-gray-900 leading-tight mt-0.5",children:"1 of 5 active"}),e.jsx("div",{className:"text-[11px] text-gray-500 mt-1",children:"low-risk cleanup · 60%"})]})}),e.jsx(G,{className:"border-gray-300",children:e.jsxs(Q,{className:"p-3",children:[e.jsx("div",{className:"text-[10px] font-mono uppercase tracking-wider text-gray-500",children:"Verify Queue"}),e.jsx("div",{className:"font-serif text-2xl text-gray-900 leading-tight mt-0.5",children:"14 items"}),e.jsx("div",{className:"text-[11px] text-gray-500 mt-1",children:"prices · subs · ingredients"})]})})]}),e.jsx(un,{compact:!0}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[200px_1fr_280px] gap-4",children:[e.jsxs(G,{className:"border-gray-300 self-start",children:[e.jsx(je,{className:"pb-2",children:e.jsx("div",{className:"text-[11px] font-mono uppercase tracking-wide text-gray-500",children:"contents"})}),e.jsxs(Q,{className:"text-xs space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-serif text-sm font-semibold text-gray-900 mb-1",children:"01-brand-core"}),Ct.map(s=>e.jsx("div",{className:"py-0.5 pl-2 text-gray-700",children:s.heading},s.heading))]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-serif text-sm font-semibold text-gray-900 mb-1",children:"02-website-copy"}),e.jsx("div",{className:"py-0.5 pl-2 text-gray-500",children:"Page rules"}),e.jsx("div",{className:"py-0.5 pl-2 text-gray-500",children:"Voice registers"}),e.jsx("div",{className:"py-0.5 pl-2 text-gray-500",children:"CTA rules"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-serif text-sm font-semibold text-gray-900 mb-1",children:"03-funnels"}),e.jsx("div",{className:"py-0.5 pl-2 text-gray-500",children:"Ceremonial"}),e.jsx("div",{className:"py-0.5 pl-2 text-gray-500",children:"Sugar-free"}),e.jsx("div",{className:"py-0.5 pl-2 text-gray-500",children:"Flavor"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-serif text-sm font-semibold text-gray-900 mb-1",children:"04-claims"}),e.jsx("div",{className:"py-0.5 pl-2 text-gray-500",children:"Safe / caution / restricted"}),e.jsx("div",{className:"py-0.5 pl-2 text-gray-500",children:"Preferred language"}),e.jsx("div",{className:"py-0.5 pl-2 text-gray-500",children:"VERIFY list"})]})]})]}),e.jsx(G,{className:"border-gray-300",children:e.jsxs(Q,{className:"p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3 text-xs",children:[e.jsx(H,{variant:"outline",className:"text-[10px] uppercase",children:"Preview"}),e.jsx("span",{className:"text-gray-500",children:"/ edit"}),e.jsx("span",{className:"flex-1"}),e.jsxs(H,{variant:"outline",className:"text-[10px]",children:["highlight vocab ",t.vocab?"on":"off"]})]}),e.jsx("div",{className:"space-y-4",children:Ct.map(s=>e.jsxs("div",{children:[e.jsx("h4",{className:"font-serif text-base text-gray-900 mb-1",children:s.heading}),e.jsx("p",{className:"text-sm leading-relaxed text-gray-700",children:e.jsx(qe,{text:s.body,on:t.vocab})})]},s.heading))}),e.jsx("div",{className:"mt-5",children:e.jsxs(Ut,{color:"blue",children:[e.jsx("p",{className:"font-semibold mb-1",children:"Inline note from Rob â"}),e.jsxs("p",{children:["When in doubt, route the customer to ",e.jsx("em",{children:"taste"})," first, philosophy second. The bars sell the worldview, not the other way around."]})]})}),e.jsxs("div",{className:"mt-5 pt-4 border-t border-dashed",children:[e.jsx("h4",{className:"font-serif text-base text-gray-900 mb-2",children:"The Three Funnels"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:Mr.map(s=>e.jsxs("div",{className:"border bg-gray-50 rounded-md p-2.5 text-xs",children:[e.jsx("div",{className:"font-semibold text-gray-900 mb-0.5",children:s.name}),e.jsx("div",{className:"text-[10px] text-gray-500 mb-1",children:s.lead}),e.jsx("p",{className:"text-[11px] leading-snug text-gray-700",children:e.jsx(qe,{text:s.promise,on:t.vocab})})]},s.id))})]})]})}),e.jsxs("div",{className:"space-y-3 self-start",children:[e.jsxs(G,{className:"border-gray-300",children:[e.jsx(je,{className:"pb-2",children:e.jsx("div",{className:"text-[11px] font-mono uppercase tracking-wide text-gray-500",children:"vocab legend"})}),e.jsxs(Q,{className:"text-xs space-y-1.5",children:[e.jsxs("div",{children:[e.jsx("span",{className:$e.proof,children:"proof term"})," ",e.jsx("span",{className:"text-gray-500 text-[10px]",children:"surface often"})]}),e.jsx("div",{children:e.jsx("span",{className:$e.caution,children:"caution / VERIFY"})}),e.jsxs("div",{children:[e.jsx("span",{className:$e.restricted,children:"restricted"})," ",e.jsx("span",{className:"text-gray-500 text-[10px]",children:"never publish"})]}),e.jsxs("div",{className:"text-[10px] text-gray-500 pt-1",children:[Tr.length," proof · ",Or.length," caution ·"," ",$r.length," restricted"]})]})]}),e.jsxs(G,{className:"border-gray-300",children:[e.jsx(je,{className:"pb-2",children:e.jsx("div",{className:"text-[11px] font-mono uppercase tracking-wide text-gray-500",children:"claim checker"})}),e.jsxs(Q,{children:[e.jsx("p",{className:"text-[11px] text-gray-500 mb-2",children:"Paste copy below"}),e.jsx("div",{className:"border border-dashed bg-gray-50 rounded p-2 text-xs leading-snug min-h-[80px]",children:e.jsx(qe,{text:"72-hour stone grind. Cures inflammation. 10% donation. Made with yacon.",on:!0})}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-2 flex-wrap",children:[e.jsx(H,{className:"bg-red-100 text-red-900 hover:bg-red-100 border-red-200 text-[10px]",children:"3 restricted"}),e.jsx(H,{className:"bg-emerald-100 text-emerald-900 hover:bg-emerald-100 border-emerald-200 text-[10px]",children:"1 proof"})]}),e.jsxs(C,{size:"sm",className:"w-full mt-3",onClick:t.onOpenClaimChecker,children:["Full checker",e.jsx(us,{className:"w-4 h-4 ml-1.5"})]})]})]}),e.jsxs(G,{className:"border-gray-300",children:[e.jsx(je,{className:"pb-2",children:e.jsx("div",{className:"text-[11px] font-mono uppercase tracking-wide text-gray-500",children:"active tasks"})}),e.jsxs(Q,{className:"text-xs space-y-2",children:[xs.slice(0,4).map(s=>e.jsxs("div",{className:"border-b border-dashed pb-1.5 last:border-b-0 last:pb-0 flex gap-2",children:[e.jsxs(H,{variant:"outline",className:"text-[10px] font-mono",children:["P",s.phase]}),e.jsx("span",{className:"text-gray-700 text-[11px] leading-snug",children:s.title})]},s.id)),e.jsx("div",{className:"text-[10px] text-gray-500 pt-1",children:"+ 1 more"})]})]}),e.jsxs(Ut,{color:"green",children:[e.jsx("p",{className:"font-semibold",children:"Approval queue:"}),e.jsx("p",{children:"2 edits awaiting Rob's review."})]})]})]})]})}const Lc="Our Cacao Alchemy bar is a sugar-free chocolate bar that boosts testosterone and treats inflammation through its 10-micron particle size. 72-hour stone grind, single-origin Maya Mountain Belize cacao, and 10% goes to conservation. Made with yacon and Mandala Springs reishi. Clinically proven to balance hormones â guarantees lasting energy.";function zc(t){const a=ks,s=x=>x.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp("("+a.map(x=>s(x.t)).join("|")+")","gi"),r={restricted:[],caution:[],proof:[]};let o;for(;(o=n.exec(t))!==null;){const x=a.find(m=>m.t.toLowerCase()===o[0].toLowerCase());x&&!r[x.k].some(m=>m.t.toLowerCase()===x.t.toLowerCase())&&r[x.k].push({t:o[0],original:x.t})}return r}function Uc(t){const[a,s]=i.useState(Lc),n=i.useMemo(()=>zc(a),[a]),r=n.restricted.length===0?n.caution.length===0?"READY TO PUBLISH":"REVIEW NEEDED":"DO NOT PUBLISH",o=n.restricted.length===0?n.caution.length===0?"ok":"note":"warn",x={ok:"bg-emerald-50 border-emerald-400 text-emerald-950",note:"bg-amber-50 border-amber-400 text-amber-950",warn:"bg-red-50 border-red-400 text-red-950"}[o],m=o==="ok"?ga:o==="warn"?Hn:xa;return e.jsxs("div",{className:"space-y-5","data-testid":"direction-claim-checker",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-serif font-semibold text-gray-900",children:"Claim Checker"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1 max-w-2xl",children:"Paste any draft copy. We surface restricted phrases, caution items, proof points, and VERIFY blockers."})]}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:e.jsx(C,{variant:"outline",size:"sm",onClick:t.onBack,children:"â Back to Brand Authority"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[1.2fr_0.8fr] gap-5",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs(G,{className:"border-gray-300",children:[e.jsx(je,{className:"pb-2",children:e.jsx("div",{className:"text-[11px] font-mono uppercase tracking-wide text-gray-500",children:"paste copy here"})}),e.jsxs(Q,{className:"p-0",children:[e.jsx(Ze,{value:a,onChange:h=>s(h.target.value),className:"border-0 focus-visible:ring-0 rounded-none min-h-[220px] font-sans text-sm leading-relaxed resize-y","data-testid":"textarea-claim-input"}),e.jsxs("div",{className:"border-t border-dashed px-4 py-2 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-gray-500",children:[a.length," chars"]}),e.jsx("span",{className:"flex-1"}),e.jsx(C,{variant:"outline",size:"sm",onClick:()=>s(""),"data-testid":"button-clear-claim",children:"clear"})]})]})]}),e.jsxs(G,{className:"border-gray-300",children:[e.jsx(je,{className:"pb-2",children:e.jsx("div",{className:"text-[11px] font-mono uppercase tracking-wide text-gray-500",children:"highlighted preview"})}),e.jsx(Q,{children:e.jsx("div",{className:"text-sm leading-relaxed text-gray-800",children:e.jsx(qe,{text:a,on:!0})})})]}),e.jsxs(G,{className:"border-gray-300",children:[e.jsx(je,{className:"pb-2",children:e.jsx("div",{className:"text-[11px] font-mono uppercase tracking-wide text-gray-500",children:"suggested rewrites"})}),e.jsx(Q,{children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-left text-xs text-gray-500 uppercase",children:[e.jsx("th",{className:"py-2 pr-2 font-medium w-2/5",children:"Don't say"}),e.jsx("th",{className:"py-2 px-2 font-medium",children:"Say instead"}),e.jsx("th",{className:"py-2 pl-2 w-16"})]})}),e.jsx("tbody",{children:Rr.map(([h,u],w)=>e.jsxs("tr",{className:"border-b border-dashed last:border-b-0 align-top",children:[e.jsx("td",{className:"py-2 pr-2",children:e.jsx("span",{className:$e.restricted,children:h})}),e.jsx("td",{className:"py-2 px-2",children:e.jsx("span",{className:$e.proof,children:u})}),e.jsx("td",{className:"py-2 pl-2"})]},w))})]})})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:`border-2 ${x} rounded-md p-5 shadow-sm`,"data-testid":"verdict-card",children:[e.jsx("div",{className:"text-[10px] font-mono uppercase tracking-widest opacity-70",children:"Verdict"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[e.jsx(m,{className:"w-7 h-7"}),e.jsx("div",{className:"font-serif text-3xl leading-tight",children:r})]}),e.jsxs("div",{className:"text-xs mt-3 flex flex-wrap gap-2",children:[e.jsxs("span",{className:$e.restricted,children:[n.restricted.length," restricted"]}),e.jsxs("span",{className:$e.caution,children:[n.caution.length," caution"]}),e.jsxs("span",{className:$e.proof,children:[n.proof.length," proof"]})]})]}),e.jsxs(G,{className:"border-gray-300",children:[e.jsx(je,{className:"pb-2",children:e.jsx("div",{className:"text-[11px] font-mono uppercase tracking-wide text-gray-500",children:"restricted â must fix"})}),e.jsx(Q,{children:n.restricted.length===0?e.jsx("p",{className:"text-sm text-gray-500",children:"No restricted phrases found."}):e.jsx("div",{className:"space-y-1.5",children:n.restricted.map((h,u)=>e.jsxs("div",{className:"flex items-center gap-2 text-sm border-b border-dashed pb-1.5 last:border-b-0 last:pb-0",children:[e.jsx(H,{className:"bg-red-200 text-red-900 hover:bg-red-200 text-[10px]",children:"BLOCK"}),e.jsx("span",{className:$e.restricted,children:h.t})]},u))})})]}),e.jsxs(G,{className:"border-gray-300",children:[e.jsx(je,{className:"pb-2",children:e.jsx("div",{className:"text-[11px] font-mono uppercase tracking-wide text-gray-500",children:"caution / VERIFY"})}),e.jsx(Q,{children:n.caution.length===0?e.jsx("p",{className:"text-sm text-gray-500",children:"Nothing to verify."}):e.jsx("div",{className:"space-y-1.5",children:n.caution.map((h,u)=>e.jsxs("div",{className:"flex items-center gap-2 text-sm border-b border-dashed pb-1.5 last:border-b-0 last:pb-0",children:[e.jsx(H,{variant:"outline",className:"text-[10px]",children:"VERIFY"}),e.jsx("span",{className:$e.caution,children:h.t})]},u))})})]}),e.jsxs(G,{className:"border-gray-300 bg-emerald-50/50",children:[e.jsx(je,{className:"pb-2",children:e.jsx("div",{className:"text-[11px] font-mono uppercase tracking-wide text-gray-500",children:"proof points found"})}),e.jsx(Q,{children:n.proof.length===0?e.jsx("p",{className:"text-sm text-gray-500",children:"No brand proof points found â
103copy may be too generic."}):e.jsx("div",{className:"space-y-1.5",children:n.proof.map((h,u)=>e.jsxs("div",{className:"flex items-center gap-2 text-sm border-b border-dashed pb-1.5 last:border-b-0 last:pb-0",children:[e.jsx(H,{className:"bg-emerald-200 text-emerald-900 hover:bg-emerald-200 text-[10px]",children:"GOOD"}),e.jsx("span",{className:$e.proof,children:h.t})]},u))})})]}),e.jsxs(Ut,{color:"blue",children:[e.jsx("p",{className:"font-semibold mb-1",children:"Approval workflow â"}),e.jsxs("p",{children:["When verdict is ",e.jsx("em",{children:"READY"}),`, "Submit for Rob's review" appears here. Edits route through the markdown commit path.`]}),e.jsxs("p",{className:"text-xs text-sky-800 mt-2 flex items-center gap-1.5",children:[e.jsx(ua,{className:"w-3 h-3"}),"Manual approval flow â coming soon."]})]})]})]})]})}const Gs="ma-kanban-status",Hs="ma-kanban-custom",ts={title:"",owner:"Andrew",phase:1,status:"backlog",claim:"ok",tag:"copy",verify:0},Bc={ok:"bg-emerald-600",caution:"bg-amber-500",restricted:"bg-red-600"},qc={ok:"claim-clean",caution:"caution / VERIFY",restricted:"restricted phrase present"};function Kc(t){const[a,s]=i.useState(()=>{if(typeof window>"u")return es;try{const g=window.localStorage.getItem(Gs);if(g){const B=JSON.parse(g);return{...es,...B}}}catch{}return es}),[n,r]=i.useState("status"),[o,x]=i.useState("all"),[m,h]=i.useState(null),[u,w]=i.useState(()=>{if(typeof window>"u")return[];try{const g=window.localStorage.getItem(Hs);if(g)return JSON.parse(g)}catch{}return[]}),[y,j]=i.useState(!1),[v,k]=i.useState(ts),F=g=>{s(g);try{window.localStorage.setItem(Gs,JSON.stringify(g))}catch{}},L=g=>{w(g);try{window.localStorage.setItem(Hs,JSON.stringify(g))}catch{}},c=i.useMemo(()=>[...jc,...u],[u]),f=i.useMemo(()=>c.filter(g=>o==="all"?!0:g.phase===Number(o)),[o,c]),P=()=>{const g=v.title.trim();if(!g)return;const B=`c${Date.now()}`,ie={id:B,phase:v.phase,title:g,owner:v.owner.trim()||"Andrew",verify:Math.max(0,Math.floor(v.verify)||0),claim:v.claim,tag:v.tag.trim()||"task"};L([...u,ie]),F({...a,[B]:v.status}),k(ts),j(!1)},D=g=>{m&&(n==="status"&&F({...a,[m]:g}),h(null))},b=n==="status"?Xt.map(g=>({id:g.id,name:g.name,phaseId:null,items:f.filter(B=>a[B.id]===g.id)})):vt.map(g=>({id:`p${g.id}`,name:`Phase ${g.id} · ${g.name}`,phaseId:g.id,items:f.filter(B=>B.phase===g.id)})),O=Object.values(a).filter(g=>g==="done").length;return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900",children:"Implementation Board"}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:"Andrew's kanban · drag cards across columns. Grouped by status by default."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(C,{variant:"outline",size:"sm",disabled:!0,children:"Filters"}),e.jsx(C,{variant:"outline",size:"sm",disabled:!0,children:"Export CSV"}),e.jsx(C,{size:"sm",onClick:()=>{k(ts),j(!0)},"data-testid":"button-new-card",children:"+ New card"})]})]}),e.jsx(G,{className:"border-gray-300",children:e.jsx(Q,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wide text-gray-500",children:"Group by"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(C,{size:"sm",variant:n==="status"?"default":"outline",onClick:()=>r("status"),"data-testid":"button-group-status",children:"Status"}),e.jsx(C,{size:"sm",variant:n==="phase"?"default":"outline",onClick:()=>r("phase"),"data-testid":"button-group-phase",children:"Phase"})]}),e.jsx("span",{className:"w-px h-6 bg-gray-300"}),e.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wide text-gray-500",children:"Filter phase"}),e.jsxs("select",{value:o,onChange:g=>x(g.target.value),className:"text-sm border border-gray-300 rounded px-2 py-1 bg-white","data-testid":"select-filter-phase",children:[e.jsx("option",{value:"all",children:"All phases"}),vt.map(g=>e.jsxs("option",{value:g.id,children:["P",g.id," · ",g.name]},g.id))]}),e.jsx("div",{className:"flex-1"}),e.jsxs("span",{className:"text-xs text-gray-500",children:[f.length," cards · ",O," shipped"]})]})})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Xt.map(g=>{const B=f.filter(ie=>a[ie.id]===g.id).length;return e.jsx(G,{className:"border-gray-300",children:e.jsxs(Q,{className:"p-3",children:[e.jsx("div",{className:"text-[10px] font-mono uppercase tracking-wide text-gray-500",children:g.name}),e.jsx("div",{className:"text-3xl font-bold text-gray-900 mt-1 leading-none",children:B})]})},g.id)})}),e.jsx("div",{className:"grid gap-3",style:{gridTemplateColumns:`repeat(${b.length}, minmax(0, 1fr))`},children:b.map(g=>e.jsxs("div",{onDragOver:B=>B.preventDefault(),onDrop:()=>D(g.id),className:"border border-gray-300 rounded-md flex flex-col min-h-[540px]",style:{background:g.phaseId!==null?Vs[g.phaseId]??"#f5f5f5":"#fafaf7"},"data-testid":`kanban-col-${g.id}`,children:[e.jsxs("div",{className:"px-3 py-2 border-b border-dashed border-gray-400 flex items-baseline gap-2 bg-white/40 rounded-t-md",children:[e.jsx("span",{className:"text-base font-semibold text-gray-900",children:g.name}),e.jsx("div",{className:"flex-1"}),e.jsx(H,{variant:"outline",className:"bg-white",children:g.items.length})]}),e.jsxs("div",{className:"p-2.5 flex flex-col gap-2.5 flex-1",children:[g.items.map(B=>e.jsxs("div",{draggable:n==="status",onDragStart:()=>h(B.id),onDragEnd:()=>h(null),className:"bg-white border border-gray-300 rounded-md p-2.5 shadow-sm transition-opacity",style:{cursor:n==="status"?"grab":"default",opacity:m===B.id?.4:1},"data-testid":`kanban-card-${B.id}`,children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-sm border border-gray-400",style:{background:Vs[B.phase]??"#eee"}}),e.jsxs("span",{className:"text-[10px] font-mono uppercase tracking-wide text-gray-500",children:["P",B.phase," · ",B.tag]}),e.jsx("div",{className:"flex-1"}),e.jsx("span",{title:qc[B.claim],className:`w-2 h-2 rounded-full ${Bc[B.claim]}`})]}),e.jsx("div",{className:"text-sm font-medium text-gray-900 leading-snug mb-2",children:B.title}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-5 h-5 rounded-full bg-amber-700 text-white inline-flex items-center justify-center text-[10px] font-bold",children:B.owner[0]}),e.jsx("span",{className:"text-[11px] text-gray-600",children:B.owner}),e.jsx("div",{className:"flex-1"}),B.verify>
1030?e.jsxs(H,{className:"bg-amber-100 text-amber-900 hover:bg-amber-100 text-[10px] px-1.5 py-0",children:[B.verify," verify"]}):e.jsx(H,{className:"bg-emerald-100 text-emerald-900 hover:bg-emerald-100 text-[10px] px-1.5 py-0",children:"clear"})]})]},B.id)),g.items.length===0&&e.jsx("div",{className:"border border-dashed border-gray-400 rounded text-[11px] text-gray-500 italic flex items-center justify-center h-20",children:"drop card here"})]})]},g.id))}),e.jsxs("div",{className:"grid md:grid-cols-[1fr_auto] gap-4 items-start",children:[e.jsx(G,{className:"border-dashed border-gray-400",children:e.jsxs(Q,{className:"p-3 text-xs text-gray-700 flex flex-wrap gap-x-5 gap-y-1.5 items-center",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-600"}),"claim-clean"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-amber-500"}),"caution / VERIFY"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-red-600"}),"restricted phrase present"]}),e.jsx("span",{className:"text-gray-500 ml-auto",children:"drag cards across status columns · grouped by phase is read-only"})]})}),e.jsxs(Ut,{color:"green",children:[e.jsx("p",{className:"font-semibold mb-1",children:"Tip:"}),e.jsxs("p",{children:["Drag a card to ",e.jsx("em",{children:"Awaiting Rob"})," to push the markdown commit for review."]})]})]}),e.jsx(Ie,{open:y,onOpenChange:j,children:e.jsxs(De,{className:"sm:max-w-[480px]","data-testid":"dialog-new-card",children:[e.jsxs(Oe,{children:[e.jsx(Te,{children:"New kanban card"}),e.jsx(Bn,{children:"Add a card to the implementation board. Saved locally to this browser."})]}),e.jsxs("div",{className:"grid gap-3 py-2",children:[e.jsxs("div",{className:"grid gap-1.5",children:[e.jsx(S,{htmlFor:"new-card-title",className:"text-xs",children:"Title"}),e.jsx(E,{id:"new-card-title",value:v.title,onChange:g=>k({...v,title:g.target.value}),placeholder:"e.g. Rewrite Cacao Alchemy hero copy",autoFocus:!0,"data-testid":"input-new-card-title"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"grid gap-1.5",children:[e.jsx(S,{htmlFor:"new-card-owner",className:"text-xs",children:"Owner"}),e.jsx(E,{id:"new-card-owner",value:v.owner,onChange:g=>k({...v,owner:g.target.value}),"data-testid":"input-new-card-owner"})]}),e.jsxs("div",{className:"grid gap-1.5",children:[e.jsx(S,{htmlFor:"new-card-tag",className:"text-xs",children:"Tag"}),e.jsx(E,{id:"new-card-tag",value:v.tag,onChange:g=>k({...v,tag:g.target.value}),placeholder:"copy / PDP / emailâ¦","data-testid":"input-new-card-tag"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"grid gap-1.5",children:[e.jsx(S,{className:"text-xs",children:"Phase"}),e.jsxs(Ne,{value:String(v.phase),onValueChange:g=>k({...v,phase:Number(g)}),children:[e.jsx(we,{"data-testid":"select-new-card-phase",children:e.jsx(Ce,{})}),e.jsx(Se,{children:vt.map(g=>e.jsxs(Z,{value:String(g.id),children:["P",g.id," · ",g.name]},g.id))})]})]}),e.jsxs("div",{className:"grid gap-1.5",children:[e.jsx(S,{className:"text-xs",children:"Status"}),e.jsxs(Ne,{value:v.status,onValueChange:g=>k({...v,status:g}),children:[e.jsx(we,{"data-testid":"select-new-card-status",children:e.jsx(Ce,{})}),e.jsx(Se,{children:Xt.map(g=>e.jsx(Z,{value:g.id,children:g.name},g.id))})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"grid gap-1.5",children:[e.jsx(S,{className:"text-xs",children:"Claim status"}),e.jsxs(Ne,{value:v.claim,onValueChange:g=>k({...v,claim:g}),children:[e.jsx(we,{"data-testid":"select-new-card-claim",children:e.jsx(Ce,{})}),e.jsxs(Se,{children:[e.jsx(Z,{value:"ok",children:"claim-clean"}),e.jsx(Z,{value:"caution",children:"caution / VERIFY"}),e.jsx(Z,{value:"restricted",children:"restricted phrase present"})]})]})]}),e.jsxs("div",{className:"grid gap-1.5",children:[e.jsx(S,{htmlFor:"new-card-verify",className:"text-xs",children:"Verify count"}
103),e.jsx(E,{id:"new-card-verify",type:"number",min:0,value:v.verify,onChange:g=>k({...v,verify:Number(g.target.value)||0}),"data-testid":"input-new-card-verify"})]})]})]}),e.jsxs(qn,{children:[e.jsx(C,{variant:"outline",onClick:()=>j(!1),"data-testid":"button-cancel-new-card",children:"Cancel"}),e.jsx(C,{onClick:P,disabled:!v.title.trim(),"data-testid":"button-save-new-card",children:"Add card"})]})]})})]})}const It="brand_authority_doc",Dt="brand_authority_doc_updated_at",jt={A:"A · Sparse / Reader-First",B:"B · Workflow Cockpit",C:"C · Dense Cockpit"};function Vc(t){if(!t)return"â";const a=Date.now()-t.getTime(),s=Math.floor(a/(1e3*60*60*24));if(s<=0)return"today";if(s===1)return"1 day ago";if(s<30)return`${s} days ago`;const n=Math.floor(s/30);return n===1?"1 month ago":`${n} months ago`}function Qc(){const{toast:t}=Ee(),a=i.useRef(null),[s,n]=i.useState("A"),{data:r}=he({queryKey:["/api/store-settings",It],queryFn:async()=>(await fetch(`/api/store-settings/${It}`)).json()}),{data:o}=he({queryKey:["/api/store-settings",Dt],queryFn:async()=>(await fetch(`/api/store-settings/${Dt}`)).json()}),x=i.useMemo(()=>{const M=((r==null?void 0:r.value)??"").trim();return M.length>0?M:Ct.map(U=>`## ${U.heading} 104 105${U.body}`).join(` 106 107`)},[r]),[m,h]=i.useState(""),[u,w]=i.useState(!1);i.useEffect(()=>{!u&&r!==void 0&&(h(x),w(!0))},[u,r,x]);const y=u&&m!==x,j=ee({mutationFn:async M=>{const U=new Date().toISOString();return await ae("PUT",`/api/store-settings/${It}`,{value:M}),await ae("PUT",`/api/store-settings/${Dt}`,{value:U}),U},onSuccess:()=>{X.invalidateQueries({queryKey:["/api/store-settings",It]}),X.invalidateQueries({queryKey:["/api/store-settings",Dt]}),t({title:"Brand authority doc saved",description:"Changes are now the canonical version of record."})},onError:M=>{t({title:"Save failed",description:(M==null?void 0:M.message)??"Could not save the doc.",variant:"destructive"})}}),v=i.useCallback(()=>{!y||j.isPending||j.mutate(m)},[y,j,m]),k=i.useCallback(()=>{var M;(M=a.current)==null||M.click()},[]),F=i.useCallback(async M=>{var _;const U=(_=M.target.files)==null?void 0:_[0];if(U){if(!/\.(md|markdown|txt)$/i.test(U.name)){t({title:"Unsupported file",description:"Please upload a .md, .markdown, or .txt file.",variant:"destructive"}),M.target.value="";return}try{const R=await U.text();h(R),t({title:"File loaded into draft",description:`${U.name} is in the editor. Review, then click Save to persist.`})}catch{t({title:"Could not read file",description:"Try downloading and re-uploading the file.",variant:"destructive"})}finally{M.target.value=""}}},[t]),[L,c]=i.useState(!0),[f,P]=i.useState(!1),[D,b]=i.useState(""),[O,g]=i.useState("edit"),B=i.useCallback(()=>{const M=new Blob([m||x],{type:"text/markdown"}),U=URL.createObjectURL(M),_=document.createElement("a");_.href=U,_.download=`brand-authority-${new Date().toISOString().slice(0,10)}.md`,_.click(),URL.revokeObjectURL(U)},[m,x]),ie=i.useCallback(()=>n("claim"),[]),xe=i.useCallback(()=>n("A"),[]);i.useEffect(()=>{const M=U=>{(U.metaKey||U.ctrlKey)&&U.key.toLowerCase()==="k"&&(U.preventDefault(),P(_=>!_))};return document.addEventListener("keydown",M),()=>document.removeEventListener("keydown",M)},[]);const fe=i.useMemo(()=>Ct.map((M,U)=>({id:U,breadcrumb:M.heading,text:M.body})),[]),d=i.useMemo(()=>{const M=D.trim().toLowerCase();return M?fe.filter(U=>U.text.toLowerCase().includes(M)||U.breadcrumb.toLowerCase().includes(M)):fe},[D,fe]),q=o!=null&&o.value?new Date(o.value):null,z=Vc(q),T={vocab:L,setVocab:c,docDraft:m,docChars:m.length,lastUpdatedLabel:z,onOpenSearch:()=>P(!0),onDownload:B,onUpload:k,onOpenClaimChecker:ie};return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-3xl font-bold text-gray-900 flex items-center gap-3",children:[e.jsx(ha,{className:"w-8 h-8 text-amber-600"}),"Brand Authority Dashboard"]}),e.jsx("p",{className:"text-sm text-gray-600 mt-1 max-w-3xl",children:"Three layout directions, the deep-view Claim Checker, and the implementation Kanban. Single source of truth for the Mandala Naturals brand."})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[y&&e.jsx(H,{className:"bg-amber-100 text-amber-900 hover:bg-amber-100",children:"Unsaved changes"}),q&&e.jsxs(H,{variant:"outline",className:"bg-white",children:[e.jsx(ia,{className:"w-3 h-3 mr-1.5"}),"Doc updated ",q.toLocaleDateString()]})]})]}),e.jsxs("div",{className:"flex items-start gap-3 border border-amber-300 bg-amber-50 rounded-md px-4 py-3 text-sm text-amber-950",children:[e.jsx(ua,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Scoped dashboard."}),e.jsx("p",{className:"text-amber-900 mt-0.5",children:"You can edit the brand authority doc and upload new markdown files below â those changes save to the canonical record. Everything else (Run check, Preview, Download, Search, Highlight vocab) is read-only and never mutates the website, products, or other settings."})]})]}),e.jsx("input",{ref:a,type:"file",accept:".md,.markdown,.txt,text/markdown,text/plain",className:"hidden",onChange:F,"data-testid":"input-upload-md"}),e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsx(Ps,{value:s,onValueChange:M=>n(M),children:e.jsxs(As,{className:"bg-gray-900 text-gray-300 p-1 h-auto flex-wrap",children:[e.jsxs(cc,{children:[e.jsx(oc,{asChild:!0,children:e.jsxs("button",{type:"button","data-state":s==="A"||s==="B"||s==="C"?"active":"inactive",className:"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-4 py-2 text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring data-[state=active]:bg-white data-[state=active]:text-gray-900 text-gray-300 hover:text-white","data-testid":"tab-direction-variants",children:[s==="B"||s==="C"?jt[s]:jt.A,e.jsx(Tn,{className:"w-3.5 h-3.5 ml-1.5 opacity-70"})]})}),e.jsxs(Dr,{align:"start",className:"min-w-[220px]",children:[e.jsx($t,{onClick:()=>n("A"),"data-testid":"menu-direction-a",children:jt.A}),e.jsx($t,{onClick:()=>n("B"),"data-testid":"menu-direction-b",children:jt.B}),e.jsx($t,{onClick:()=>n("C"),"data-testid":"menu-direction-c",children:jt.C})]})]}),e.jsx(pt,{value:"claim",className:"data-[state=active]:bg-white data-[state=active]:text-gray-900 px-4 py-2 text-sm","data-testid":"tab-direction-claim",children:"Deep view â Claim Checker"}),e.jsx(pt,{value:"K",className:"data-[state=active]:bg-white data-[state=active]:text-gray-900 px-4 py-2 text-sm","data-testid":"tab-direction-kanban",children:"Kanban Board"}),e.jsxs(pt,{value:"doc",className:"data-[state=active]:bg-white data-[state=active]:text-gray-900 px-4 py-2 text-sm","data-testid":"tab-direction-doc",children:[e.jsx(rs,{className:"w-3.5 h-3.5 mr-1.5"}),"Brand Authority Doc"]})]})}),e.jsxs("button",{type:"button",onClick:()=>n("marketing"),"data-state":s==="marketing"?"active":"inactive",className:"group inline-flex items-center gap-2 rounded-md border border-gray-300 bg-white px-3.5 py-2 text-sm font-medium shadow-sm transition-all hover:shadow data-[state=active]:ring-2 data-[state=active]:ring-[#4285F4] data-[state=active]:border-[#4285F4]","data-testid":"button-marketing-analytics",children:[e.jsx(qs,{className:"w-4 h-4 text-[#E37400]"}),e.jsxs("span",{children:[e.jsx("span",{className:"text-[#4285F4]",children:"M"}),e.jsx("span",{className:"text-[#EA4335]",children:"a"}),e.jsx("span",{className:"text-[#FBBC04]",children:"r"}),e.jsx("span",{className:"text-[#4285F4]",children:"k"}),e.jsx("span",{className:"text-[#34A853]",children:"e"}),e.jsx("span",{className:"text-[#EA4335]",children:"t"}),e.jsx("span",{className:"text-gray-900",children:"ing Analytics"})]})]})]}),s==="A"&&e.jsx(Tc,{...T}),s==="B"&&e.jsx(Rc,{...T}),s==="C"&&e.jsx(_c,{...T}),s==="claim"&&e.jsx(Uc,{...T,onBack:xe}),s==="K"&&e.jsx(Kc,{...T}),s==="doc"&&e.jsxs(G,{className:"border-gray-300","data-testid":"brand-authority-doc-tab",children:[e.jsx(je,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs(Pe,{className:"flex items-center gap-2 text-lg",children:[e.jsx(rs,{className:"w-5 h-5 text-amber-600"}),"Brand Authority Doc"]}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Edit the markdown below or upload a new .md file. Click Save to make it canonical. Last updated"," ",e.jsx("span",{className:"font-medium",children:z}),"."]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(C,{variant:"outline",size:"sm",onClick:k,"data-testid":"button-upload-md",children:[e.jsx(da,{className:"w-4 h-4 mr-1.5"}),"Upload .md"]}),e.jsxs(C,{size:"sm",onClick:v,disabled:!y||j.isPending,"data-testid":"button-save-doc",children:[e.jsx(Ke,{className:"w-4 h-4 mr-1.5"}),j.isPending?"Savingâ¦":"Save"]})]})]})}),e.jsx(Q,{children:e.jsxs(Ps,{value:O,onValueChange:M=>g(M),children:[e.jsxs(As,{className:"mb-3",children:[e.jsxs(pt,{value:"edit","data-testid":"tab-doc-edit",children:[e.jsx(Zn,{className:"w-3.5 h-3.5 mr-1.5"}),"Edit"]}),e.jsxs(pt,{value:"preview","data-testid":"tab-doc-preview",children:[e.jsx(ht,{className:"w-3.5 h-3.5 mr-1.5"}),"Preview"]})]}),e.jsxs(Es,{value:"edit",className:"m-0",children:[e.jsx(Ze,{value:m,onChange:M=>h(M.target.value),placeholder:"Paste or type markdown hereâ¦",className:"font-mono text-xs min-h-[420px] resize-y","data-testid":"textarea-doc-draft"}),e.jsxs("div",{className:"flex items-center justify-between mt-2 text-xs text-gray-500",children:[e.jsxs("span",{children:[m.length.toLocaleStr
107ing()," chars"]}),y&&e.jsx("span",{className:"text-amber-700 font-medium",children:"Unsaved changes"})]})]}),e.jsx(Es,{value:"preview",className:"m-0",children:e.jsx("div",{className:"prose prose-sm max-w-none border rounded-md p-4 bg-white min-h-[420px] overflow-auto","data-testid":"preview-doc-draft",children:m.trim()?e.jsx(Xn,{remarkPlugins:[ei],children:m}):e.jsx("p",{className:"text-sm text-gray-400 italic",children:"Nothing to preview yet."})})})]})})]}),s==="marketing"&&e.jsxs(G,{className:"border-gray-300","data-testid":"brand-authority-marketing-tab",children:[e.jsx(je,{children:e.jsxs(Pe,{className:"flex items-center gap-2 text-lg",children:[e.jsx(qs,{className:"w-5 h-5 text-[#E37400]"}),e.jsxs("span",{children:[e.jsx("span",{className:"text-[#4285F4]",children:"M"}),e.jsx("span",{className:"text-[#EA4335]",children:"a"}),e.jsx("span",{className:"text-[#FBBC04]",children:"r"}),e.jsx("span",{className:"text-[#4285F4]",children:"k"}),e.jsx("span",{className:"text-[#34A853]",children:"e"}),e.jsx("span",{className:"text-[#EA4335]",children:"t"}),e.jsx("span",{className:"text-gray-900",children:"ing Analytics"})]})]})}),e.jsx(Q,{children:e.jsxs("div",{className:"border-2 border-dashed border-gray-300 rounded-md p-12 flex flex-col items-center justify-center text-center min-h-[280px]",children:[e.jsx(ni,{className:"w-10 h-10 text-gray-400 mb-3"}),e.jsx("p",{className:"text-base font-medium text-gray-700",children:"Marketing Analytics â coming soon"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1.5 max-w-md",children:"This tab is reserved for Google Analytics, Search Console, Ads, and campaign-performance widgets. Functionality will be added here."})]})})]}),e.jsxs(qi,{open:f,onOpenChange:P,children:[e.jsx(Da,{placeholder:"Search the brand authorityâ¦",value:D,onValueChange:b,"data-testid":"input-search-query"}),e.jsxs(Fa,{children:[e.jsx(Ma,{children:"No matches found."}),d.length>0&&e.jsx($a,{heading:`${d.length} result${d.length===1?"":"s"}`,children:d.map(M=>e.jsxs(Oa,{value:`${M.breadcrumb} ${M.text}`,onSelect:()=>{P(!1),b("")},className:"flex flex-col items-start gap-1 py-2","data-testid":`search-result-${M.id}`,children:[e.jsx("div",{className:"text-xs text-amber-700 font-medium",children:M.breadcrumb}),e.jsx("div",{className:"text-sm text-gray-700 line-clamp-2",children:M.text})]},M.id))})]})]})]})}function Ro(){const{user:t,login:a,logout:s,isLoading:n}=Ys(),[r,o]=i.useState("home"),[x,m]=i.useState(""),[h,u]=i.useState(""),[w,y]=i.useState(""),[j,v]=i.useState(!1),[k,F]=i.useState(!1),[,L]=Rn(),{data:c}=he({queryKey:["/api/products","admin"],queryFn:async()=>{const $=await fetch("/api/products?includeAll=true",{cache:"no-store"});if(!$.ok)throw new Error("Failed to fetch products");return $.json()}}),{data:f}=he({queryKey:["/api/orders","all"],queryFn:async()=>(await fetch("/api/orders?all=true")).json()}),{data:P}=he({queryKey:["/api/users","count"],queryFn:async()=>(await fetch("/api/users?page=1&limit=1")).json()}),{data:D}=he({queryKey:["/api/subscriptions"]}),{data:b}=he({queryKey:["/api/admin/support/unread-count"],refetchInterval:45e3,staleTime:0,enabled:!!t&&t.role==="admin"}),{data:O}=he({queryKey:["/api/store-settings","renewals_paused"],queryFn:async()=>(await fetch("/api/store-settings/renewals_paused")).json()}),g=(O==null?void 0:O.value)==="true",B=ee({mutationFn:async $=>{await ae("/api/store-settings/renewals_paused","PUT",{value:$?"true":"false"})},onSuccess:()=>{X.invalidateQueries({queryKey:["/api/store-settings","renewals_paused"]})}}),ie=async $=>{$.preventDefault(),y("");try{(await a(x,h)).role!=="admin"&&y("This account does not have admin access.")}catch{y("Invalid username or password.")}};if(n&&!t)return e.jsx("div",{className:"flex items-center justify-center min-h-screen bg-gray-50",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"})});if(!t||t.role!=="admin")return e.jsx("div",{className:"flex items-center justify-center min-h-screen bg-gray-50",children:e.jsxs(G,{className:"w-full max-w-sm",children:[e.jsxs(je,{className:"text-center",children:[e.jsx(Pe,{className:"text-2xl",children:"Admin Login"}),e.jsx(yt,{children:"Sign in to access the dashboard"})]}),e.jsx(Q,{children:e.jsxs("form",{onSubmit:ie,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{htmlFor:"username",children:"Username"}),e.jsx(E,{id:"username",value:x,onChange:$=>m($.target.value),placeholder:"Enter username",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{htmlFor:"password",children:"Password"}),e.jsx(E,{id:"password",type:"password",value:h,onChange:$=>u($.target.value),placeholder:"Enter password",required:!0})]}),w&&e.jsx("p",{className:"text-sm text-red-600",children:w}),e.jsx(C,{type:"submit",className:"w-full",children:"Sign In"})]})})]})});const xe=Array.isArray(f)?f.length:0;Array.isArray(f)&&f.filter($=>$.status==="completed"||$.status==="processing").length;const fe=Array.isArray(f)?f.filter($=>$.status==="processing").length:0,d=Array.isArray(f)?f.reduce(($,Y)=>$+parseFloat(Y.total||"0"),0):0,q=xe>0?d/xe:0,z=Array.isArray(c)?c.length:0,T=Array.isArray(c)?c.filter($=>$.isActive&&$.status==="active").length:0,M=(P==null?void 0:P.total)||0,U=new Date;U.setDate(1),U.setHours(0,0,0,0);const _=Array.isArray(f)?f.filter($=>new Date($.dateCreated)>=U):[],R=_.length,ue=_.reduce(($,Y)=>$+parseFloat(Y.total||"0"),0),te=R>0?ue/R:0,A=[{id:"home",label:"Home",icon:_n},{id:"orders",label:"Orders",icon:as,count:fe},{id:"products",label:"Products",icon:tt},{id:"collections",label:"Collections",icon:Vt},{id:"subscriptions",label:"Subscriptions",icon:Ot,count:Array.isArray(D)?D.filter($=>$.status==="active").length:0},{id:"renewals",label:"Renewals",icon:Kt},{id:"bundles",label:"Bundles",icon:Qe},{id:"coupons",label:"Coupons",icon:la},{id:"support",label:"Support",icon:Ln,count:(b==null?void 0:b.unreadConversations)||0},{id:"customers",label:"Customers",icon:ca},{id:"brand-authority",label:"Brand Authority",icon:ha},{id:"blog-import",label:"Blog Import",icon:zn,external:"/mandala-admin/blog-import"},{id:"settings",label:"Settings",icon:Wn}];return e.jsxs("div",{className:"flex min-h-screen bg-gray-50",children:[e.jsxs("aside",{className:`fixed left-0 top-0 h-full bg-gray-900 text-white z-40 transition-all duration-200 flex flex-col ${k?"w-16":"w-56"}`,children:[e.jsxs("div",{className:"p-4 border-b border-gray-700 flex items-center gap-3",children:[e.jsx("button",{onClick:()=>F(!k),className:"w-8 h-8 rounded bg-gray-700 flex items-center justify-center text-sm font-bold flex-shrink-0",children:"M"}),!k&&e.jsx("span",{className:"font-semibold text-sm truncate",children:"Mandala Naturals"})]}),e.jsx("nav",{className:"flex-1 py-2",children:A.map($=>e.jsxs("button",{onClick:()=>{$.external?L($.external):o($.id)},className:`w-full flex items-center gap-3 px-4 py-2.5 text-sm transition-colors ${r===$.id?"bg-gray-700 text-white":"text-gray-400 hover:text-white hover:bg-gray-800"}`,children:[e.jsx($.icon,{className:"w-5 h-5 flex-shrink-0"}),!k&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flex-1 text-left",children:$.label}),$.count!==void 0&&$.count>0&&e.jsx(H,{className:"bg-gray-600 text-white text-xs h-5 min-w-[20px] flex items-center justify-center",children:$.count})]})]},$.id))}),e.jsxs("div",{className:"border-t border-gray-700 p-3",children:[e.jsxs("button",{onClick:()=>L("/"),className:"w-full flex items-center gap-3 px-2 py-2 text-sm text-gray-400 hover:text-white transition-colors",children:[e.jsx(Ge,{className:"w-4 h-4 flex-shrink-0"}),!k&&e.jsx("span",{children:"View Store"})]}),e.jsxs("button",{onClick:()=>s(),className:"w-full flex items-center gap-3 px-2 py-2 text-sm text-gray-400 hover:text-red-400 transition-colors",children:[e.jsx(Yn,{className:"w-4 h-4 flex-shrink-0"}),!k&&e.jsx("span",{children:"Log Out"})]})]})]}),e.jsxs("main",{className:`flex-1 transition-all duration-200 ${k?"ml-16":"ml-56"}`,children:[e.jsx("header",{className:"sticky top-0 z-30 bg-white border-b border-gray-200 px-6 py-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"relative flex-1 max-w-md",children:[e.jsx(He,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx(E,{placeholder:"Search...",className:"pl-9 bg-gray-50 border-gray-200"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(C,{variant:g?"default":"destructive",size:"sm",className:`text-xs font-semibold ${g?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700"}`,onClick:()=>B.mutate(!g),disabled:B.isPending,children:g?e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"w-3.5 h-3.5 mr-1.5"})," Resume Renewals"]}):e.jsxs(e.Fragment,{children:[e.jsx(Tt,{className:"w-3.5 h-3.5 mr-1.5"})," Stop Renewals"]})}),g&&e.jsx(H,{variant:"outline",className:"border-red-300 bg-red-50 text-red-700 text-xs animate-pulse",children:"Renewals Paused"}),e.jsxs("span",{className:"text-sm text-gray-600",children:["Welcome, ",t.firstName||t.username]}),e.jsx("img",{src:$s,alt:"Admin",className:"w-20 h-20 rounded-full object-cover border-2 border-amber-300 shadow-sm cursor-pointer hover:border-amber-400 hover:shadow-md transition-all duration-200",onClick:()=>v(!0)})]})]})}),e.jsxs("div",{className:"p-6",children:[r==="home"&&e.jsx(Gc,{totalRevenue:d,totalOrders:xe,avgOrderValue:q,pendingOrders:fe,totalProducts:z,activeProducts:T,totalCustomers:M,ecommerceOrders:f,products:c,onNavigate:o,mtdRevenue:ue,mtdOrderCount:R,mtdAvgOrder:te}),r==="orders"&&e.jsx(Hc,{orders:f}),r==="products"&&e.jsx(ji,{}),r==="collections"&&e.jsx(fi,{}),r==="subscriptions"&&e.jsx(Xc,{}),r==="renewals"&&e.jsx(ro,{}),r==="bundles"&&e.jsx(so,{}),r==="coupons"&&e.jsx(ao,{}),r==="support"&&e.jsx(Jc,{}),r==="customers"&&e.jsx(Zc,{}),r==="brand-authority"&&e.jsx(Qc,{}),r==="settings"&&e.jsx(io,{})]})]}),j&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm",onClick:()=>v(!1),children:e.jsxs("div",{className:"relative",onClick:$=>$.stopPropagation(),children:[e.jsx("button",{onClick:()=>v(!1),className:"absolute -top-4 -right-4 z-10 w-10 h-10 rounded-full bg-white shadow-lg flex items-center justify-center hover:bg-gray-100 transition-colors",children:e.jsx(St,{className:"h-5 w-5 text-gray-700"})}),e.jsx("img",{src:$s,alt:"Admin",className:"w-80 h-80 rounded-full object-cover border-4 border-white shadow-2xl"})]})})]})}function Gc({totalRevenue:t,totalOrders:a,avgOrderValue:s,pendingOrders:n,totalProducts:r,activeProducts:o,totalCustomers:x,ecommerceOrders:m,onNavigate:h,mtdRevenue:u,mtdOrderCount:w,mtdAvgOrder:y}
107){const[j,v]=i.useState("mtd"),k=new Date().toLocaleString("en-US",{month:"long",year:"numeric",timeZone:"America/New_York"}),F=j==="mtd"?u:t,L=j==="mtd"?w:a,c=j==="mtd"?y:s;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"Dashboard"}),e.jsxs(Ne,{value:j,onValueChange:f=>v(f),children:[e.jsx(we,{className:"w-48 h-9 text-sm",children:e.jsx(Ce,{})}),e.jsxs(Se,{children:[e.jsxs(Z,{value:"mtd",children:[k," (MTD)"]}),e.jsx(Z,{value:"all",children:"All Time"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(G,{className:"border border-gray-200 shadow-sm",children:e.jsxs(Q,{className:"pt-5 pb-4 px-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-sm text-gray-500 font-medium",children:j==="mtd"?"MTD Sales":"Total Sales"}),e.jsx(Ft,{className:"w-4 h-4 text-gray-400"})]}),e.jsxs("div",{className:"text-2xl font-bold text-gray-900",children:["$",F.toLocaleString("en-US",{minimumFractionDigits:2})]}),e.jsx("div",{className:"flex items-center gap-1 mt-1 text-xs",children:j==="mtd"?e.jsxs("span",{className:"text-amber-600 font-medium",children:[L," order",L!==1?"s":""," this month"]}):e.jsxs(e.Fragment,{children:[e.jsx(si,{className:"w-3 h-3 text-green-500"}),e.jsx("span",{className:"text-green-600 font-medium",children:"Active"})]})})]})}),e.jsx(G,{className:"border border-gray-200 shadow-sm",children:e.jsxs(Q,{className:"pt-5 pb-4 px-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-sm text-gray-500 font-medium",children:"Orders"}),e.jsx(as,{className:"w-4 h-4 text-gray-400"})]}),e.jsx("div",{className:"text-2xl font-bold text-gray-900",children:L}),e.jsx("div",{className:"flex items-center gap-1 mt-1 text-xs",children:e.jsxs("span",{className:"text-amber-600 font-medium",children:[n," to fulfill"]})})]})}),e.jsx(G,{className:"border border-gray-200 shadow-sm",children:e.jsxs(Q,{className:"pt-5 pb-4 px-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-sm text-gray-500 font-medium",children:"Avg. Order Value"}),e.jsx(ti,{className:"w-4 h-4 text-gray-400"})]}),e.jsxs("div",{className:"text-2xl font-bold text-gray-900",children:["$",c.toFixed(2)]}),e.jsx("div",{className:"flex items-center gap-1 mt-1 text-xs",children:e.jsx("span",{className:"text-gray-500",children:"Per order"})})]})}),e.jsx(G,{className:"border border-gray-200 shadow-sm",children:e.jsxs(Q,{className:"pt-5 pb-4 px-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-sm text-gray-500 font-medium",children:"Customers"}),e.jsx(ca,{className:"w-4 h-4 text-gray-400"})]}),e.jsx("div",{className:"text-2xl font-bold text-gray-900",children:x}),e.jsx("div",{className:"flex items-center gap-1 mt-1 text-xs",children:e.jsx("span",{className:"text-gray-500",children:"Registered"})})]})})]}),n>0&&e.jsx(G,{className:"border border-amber-200 bg-amber-50 shadow-sm cursor-pointer hover:bg-amber-100 transition-colors",onClick:()=>h("orders"),children:e.jsxs(Q,{className:"py-3 px-5 flex items-center gap-3",children:[e.jsx(as,{className:"w-5 h-5 text-amber-600"}),e.jsxs("span",{className:"text-sm font-medium text-amber-800",children:[n," order",n!==1?"s":""," to fulfill"]}),e.jsx(Ge,{className:"w-4 h-4 text-amber-400 ml-auto"})]})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(G,{className:"border border-gray-200 shadow-sm",children:[e.jsx(je,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Pe,{className:"text-base font-semibold",children:"Recent Orders"}),e.jsx(C,{variant:"ghost",size:"sm",className:"text-xs",onClick:()=>h("orders"),children:"View all"})]})}),e.jsx(Q,{children:e.jsx("div",{className:"space-y-3",children:Array.isArray(m)&&m.length>0?m.slice(0,5).map(f=>e.jsxs("div",{className:"flex items-center justify-between py-2 border-b border-gray-100 last:border-0",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:f.orderNumber||`#${f.id}`}),e.jsx("p",{className:"text-xs text-gray-500",children:f.customerEmail})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"text-sm font-medium text-gray-900",children:["$",parseFloat(f.total||"0").toFixed(2)]}),e.jsx(H,{variant:"outline",className:`text-xs capitalize ${f.status==="completed"||f.status==="processing"?"border-green-200 bg-green-50 text-green-700":f.status==="pending"?"border-amber-200 bg-amber-50 text-amber-700":"border-red-200 bg-red-50 text-red-700"}`,children:f.status})]})]},f.id)):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:"No orders yet"})})})]}),e.jsxs(G,{className:"border border-gray-200 shadow-sm",children:[e.jsx(je,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Pe,{className:"text-base font-semibold",children:"Product Summary"}),e.jsx(C,{variant:"ghost",size:"sm",className:"text-xs",onClick:()=>h("products"),children:"View all"})]})}),e.jsx(Q,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Total Products"}),e.jsx("span",{className:"text-sm font-semibold text-gray-900",children:r})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Active Products"}),e.jsx("span",{className:"text-sm font-semibold text-green-600",children:o})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Draft Products"}),e.jsx("span",{className:"text-sm font-semibold text-amber-600",children:r-o})]}),e.jsx("div",{className:"pt-3 border-t",children:e.jsxs(C,{variant:"outline",size:"sm",className:"w-full",onClick:()=>h("products"),children:[e.jsx(tt,{className:"w-4 h-4 mr-2"}),"Manage Products"]})})]})})]})]})]})}function Hc({orders:t}){const[a,s]=i.useState("all"),[n,r]=i.useState(""),[o,x]=i.useState(null),[m,h]=i.useState("dateCreated"),[u,w]=i.useState("desc"),{toast:y}=Ee(),j=d=>{m===d?w(u==="asc"?"desc":"asc"):(h(d),w(d==="dateCreated"||d==="total"||d==="items"?"desc":"asc"))},v=({col:d})=>m!==d?e.jsx(st,{className:"w-3 h-3 opacity-40"}):u==="asc"?e.jsx(pa,{className:"w-3 h-3"}):e.jsx(hs,{className:"w-3 h-3"}),k=ee({mutationFn:async({id:d,status:q})=>{await ae(`/api/orders/${d}`,"PATCH",{status:q})},onSuccess:(d,q)=>{X.invalidateQueries({queryKey:["/api/orders"]}),y({title:`Order marked ${q.status}`,description:"Status updated silently â no customer email sent."})}}),[F,L]=i.useState(new Set),c=d=>{L(q=>{const z=new Set(q);return z.has(d)?z.delete(d):z.add(d),z})},f=ee({mutationFn:async({orderIds:d,status:q})=>ae("/api/orders/bulk-status","POST",{orderIds:d,status:q}),onSuccess:d=>{X.invalidateQueries({queryKey:["/api/orders"]}),L(new Set),y({title:`${d.updated} order${d.updated===1?"":"s"} marked ${d.status}`,description:`No customer emails sent.${d.skipped?` ${d.skipped} skipped (already ${d.status}).`:""}`})},onError:d=>{y({title:"Bulk update failed",description:d.message,variant:"destructive"})}}),P=ee({mutationFn:async({id:d,type:q})=>{const z=await fetch(`/api/orders/${d}/resend-notifications`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:q})});if(!z.ok){const T=await z.json();throw new Error(T.error||"Failed to resend")}return z.json()},onSuccess:d=>{var q;y({title:"Email sent",description:(q=d.results)==null?void 0:q.join(", ")})},onError:d=>{y({title:"Send failed",description:d.message,variant:"destructive"})}}),D=ee({mutationFn:async d=>{const q=await fetch(`/api/orders/${d}/push-to-shippingeasy`,{method:"POST"});if(!q.ok){const z=await q.json();throw new Error(z.error||"Failed to push")}return q.json()},onSuccess:()=>{X.invalidateQueries({queryKey:["/api/orders"]}),y({title:"Order pushed to ShippingEasy"})},onError:d=>{y({title:"ShippingEasy push failed",description:d.message,variant:"destructive"})}}),b=ee({mutationFn:async d=>{const q=await fetch(`/api/orders/${d}/check-tracking`,{method:"POST"});if(!q.ok){const z=await q.json();throw new Error(z.error||"Failed to check order status")}return q.json()},onSuccess:d=>{X.invalidateQueries({queryKey:["/api/orders"]}),d.trackingNumber?y({title:`ShippingEasy: ${d.seStatus||d.status}`,description:`${d.carrier}: ${d.trackingNumber}`}):d.scheduledShipDate?y({title:`ShippingEasy: ${d.seStatus||d.status}`,description:`Scheduled to ship ${d.scheduledShipDate}${d.plannedCarrier?` via ${d.plannedCarrier}${d.plannedService?" "+d.plannedService:""}`:""}`}):y({title:`ShippingEasy: ${d.seStatus||d.status}`,description:d.message})},onError:d=>{y({title:"Status check failed",description:d.message,variant:"destructive"})}}),O=d=>{if(!d.lineItems)return 0;if(typeof d.lineItems=="string")try{return(JSON.parse(d.lineItems)||[]).length}catch{return 0}return Array.isArray(d.lineItems)?d.lineItems.length:0},g=i.useMemo(()=>Array.isArray(t)?t.filter(d=>{const q=a==="all"||d.status===a,z=n===""||(d.orderNumber||"").toLowerCase().includes(n.toLowerCase())||(d.customerEmail||"").toLowerCase().includes(n.toLowerCase())||(d.customerFirstName||"").toLowerCase().includes(n.toLowerCase())||(d.customerLastName||"").toLowerCase().includes(n.toLowerCase());return q&&z}).slice().sort((d,q)=>{const z=u==="asc"?1:-1;let T,M;switch(m){case"orderNumber":return T=(d.orderNumber||`#${d.id}`).toString(),M=(q.orderNumber||`#${q.id}`).toString(),T.localeCompare(M,void 0,{numeric:!0})*z;case"customer":return T=[d.customerFirstName,d.customerLastName].filter(
107Boolean).join(" ").toLowerCase()||(d.customerEmail||"").toLowerCase(),M=[q.customerFirstName,q.customerLastName].filter(Boolean).join(" ").toLowerCase()||(q.customerEmail||"").toLowerCase(),T.localeCompare(M)*z;case"dateCreated":return T=d.dateCreated?new Date(d.dateCreated).getTime():0,M=q.dateCreated?new Date(q.dateCreated).getTime():0,(T-M)*z;case"status":return(d.status||"").localeCompare(q.status||"")*z;case"items":return(O(d)-O(q))*z;case"total":return(parseFloat(d.total||"0")-parseFloat(q.total||"0"))*z;default:return 0}}):[],[t,a,n,m,u]),ie=g.slice(0,150),xe={all:Array.isArray(t)?t.length:0,processing:Array.isArray(t)?t.filter(d=>d.status==="processing").length:0,completed:Array.isArray(t)?t.filter(d=>d.status==="completed").length:0,shipped:Array.isArray(t)?t.filter(d=>d.status==="shipped").length:0,cancelled:Array.isArray(t)?t.filter(d=>d.status==="cancelled").length:0},fe=d=>{if(!d.lineItems)return[];if(typeof d.lineItems=="string")try{return JSON.parse(d.lineItems)}catch{return[]}return Array.isArray(d.lineItems)?d.lineItems:[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"Orders"})}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:["all","processing","shipped","completed","cancelled"].map(d=>e.jsxs(C,{variant:a===d?"default":"outline",size:"sm",onClick:()=>s(d),className:"text-xs capitalize",children:[d," (",xe[d],")"]},d))}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(He,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx(E,{placeholder:"Search by order #, email, or name...",className:"pl-9",value:n,onChange:d=>r(d.target.value)})]}),F.size>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-green-300 bg-green-50 px-4 py-2.5",children:[e.jsxs("p",{className:"text-sm font-medium text-green-900",children:[F.size," order",F.size===1?"":"s"," selected"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(C,{size:"sm",className:"bg-green-600 hover:bg-green-700 text-white",disabled:f.isPending,onClick:()=>{confirm(`Mark ${F.size} order(s) as COMPLETED? 108 109No emails will be sent to customers.`)&&f.mutate({orderIds:Array.from(F),status:"completed"})},"data-testid":"button-bulk-complete",children:[e.jsx(Fs,{className:"w-4 h-4 mr-1.5"}),f.isPending?"Updatingâ¦":"Mark Completed (no emails)"]}),e.jsx(C,{size:"sm",variant:"ghost",onClick:()=>L(new Set),children:"Clear"})]})]}),e.jsx(G,{className:"border border-gray-200 shadow-sm",children:e.jsx(Q,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{className:"bg-gray-50 border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"w-10 px-3 py-3",children:e.jsx("input",{type:"checkbox",className:"w-4 h-4 rounded border-gray-300 accent-green-600 cursor-pointer",checked:ie.length>0&&ie.every(d=>F.has(d.id)),onChange:d=>{L(d.target.checked?new Set(ie.map(q=>q.id)):new Set)},title:"Select all visible orders","data-testid":"checkbox-select-all-orders"})}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-3",children:e.jsxs("button",{type:"button",onClick:()=>j("orderNumber"),className:"inline-flex items-center gap-1 hover:text-gray-900 transition-colors uppercase",children:["Order ",e.jsx(v,{col:"orderNumber"})]})}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-3",children:e.jsxs("button",{type:"button",onClick:()=>j("customer"),className:"inline-flex items-center gap-1 hover:text-gray-900 transition-colors uppercase",children:["Customer ",e.jsx(v,{col:"customer"})]})}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-3",children:e.jsxs("button",{type:"button",onClick:()=>j("dateCreated"),className:"inline-flex items-center gap-1 hover:text-gray-900 transition-colors uppercase",children:["Date ",e.jsx(v,{col:"dateCreated"})]})}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-3",children:e.jsxs("button",{type:"button",onClick:()=>j("status"),className:"inline-flex items-center gap-1 hover:text-gray-900 transition-colors uppercase",children:["Status ",e.jsx(v,{col:"status"})]})}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-3",children:e.jsxs("button",{type:"button",onClick:()=>j("items"),className:"inline-flex items-center gap-1 hover:text-gray-900 transition-colors uppercase",children:["Items ",e.jsx(v,{col:"items"})]})}),e.jsx("th",{className:"text-right text-xs font-medium text-gray-500 uppercase px-4 py-3",children:e.jsxs("button",{type:"button",onClick:()=>j("total"),className:"ml-auto inline-flex items-center gap-1 hover:text-gray-900 transition-colors uppercase",children:["Total ",e.jsx(v,{col:"total"})]})}),e.jsx("th",{className:"text-right text-xs font-medium text-gray-500 uppercase px-4 py-3",children:"Actions"})]})}),e.jsxs("tbody",{children:[g.length>0?ie.map(d=>{const q=o===d.id;return e.jsxs(i.Fragment,{children:[e.jsxs("tr",{className:`border-b last:border-0 hover:bg-gray-50 transition-colors cursor-pointer ${q?"bg-gray-50":""}`,onClick:()=>x(q?null:d.id),children:[e.jsx("td",{className:"px-3 py-3",onClick:z=>z.stopPropagation(),children:e.jsx("input",{type:"checkbox",className:"w-4 h-4 rounded border-gray-300 accent-green-600 cursor-pointer",checked:F.has(d.id),onChange:()=>c(d.id),"data-testid":`checkbox-order-${d.id}`})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:"text-sm font-medium text-blue-600",children:d.orderNumber||`#${d.id}`})}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:[d.customerFirstName,d.customerLastName].filter(
109Boolean).join(" ")||"â"}),e.jsx("p",{className:"text-xs text-gray-500",children:d.customerEmail})]})}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-600",children:d.dateCreated?new Date(d.dateCreated).toLocaleDateString():"â"}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(H,{variant:"outline",className:`text-xs capitalize ${d.status==="completed"||d.status==="shipped"?"border-green-200 bg-green-50 text-green-700":d.status==="processing"?"border-blue-200 bg-blue-50 text-blue-700":d.status==="cancelled"?"border-red-200 bg-red-50 text-red-700":"border-amber-200 bg-amber-50 text-amber-700"}`,children:d.status})}),e.jsxs("td",{className:"px-4 py-3 text-sm text-gray-600",children:[fe(d).length," item",fe(d).length!==1?"s":""]}),e.jsxs("td",{className:"px-4 py-3 text-right text-sm font-medium text-gray-900",children:["$",parseFloat(d.total||"0").toFixed(2)]}),e.jsx("td",{className:"px-4 py-3 text-right",onClick:z=>z.stopPropagation(),children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[d.status==="processing"&&e.jsxs(e.Fragment,{children:[e.jsxs(C,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs text-green-700 hover:bg-green-50",disabled:k.isPending,title:"Mark shipped (no customer email)",onClick:()=>{confirm(`Mark order ${d.orderNumber||`#${d.id}`} as SHIPPED? No email will be sent to the customer.`)&&k.mutate({id:d.id,status:"shipped"})},"data-testid":`button-mark-shipped-${d.id}`,children:[e.jsx(bt,{className:"w-3.5 h-3.5 mr-1"})," Shipped"]}),e.jsxs(C,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs text-green-700 hover:bg-green-50",disabled:k.isPending,title:"Mark completed (no customer email)",onClick:()=>{confirm(`Mark order ${d.orderNumber||`#${d.id}`} as COMPLETED? No email will be sent to the customer.`)&&k.mutate({id:d.id,status:"completed"})},"data-testid":`button-mark-completed-${d.id}`,children:[e.jsx(Fs,{className:"w-3.5 h-3.5 mr-1"})," Complete"]})]}),e.jsx(C,{variant:"ghost",size:"sm",onClick:()=>x(q?null:d.id),children:e.jsx(Ge,{className:`w-4 h-4 transition-transform ${q?"rotate-90":""}`})})]})})]}),q&&e.jsx("tr",{className:"bg-gray-50/60 border-b",children:e.jsx("td",{colSpan:8,className:"px-6 py-5",children:e.jsxs("div",{className:"space-y-4 max-w-3xl",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-gray-500",children:"Customer"}),e.jsx("p",{className:"font-medium",children:[d.customerFirstName,d.customerLastName].filter(Boolean).join(" ")||"â"}),e.jsx("p",{className:"text-xs text-gray-500",children:d.customerEmail})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-gray-500",children:"Date"}),e.jsx("p",{className:"font-medium",children:d.dateCreated?new Date(d.dateCreated).toLocaleString():"â"})]}),e.jsxs("div",{onClick:z=>z.stopPropagation(),children:[e.jsx("p",{className:"text-gray-500",children:"Status"}),e.jsxs(Ne,{defaultValue:d.status,onValueChange:z=>k.mutate({id:d.id,status:z}),children:[e.jsx(we,{className:"h-8 text-xs w-36",children:e.jsx(Ce,{})}),e.jsxs(Se,{children:[e.jsx(Z,{value:"processing",children:"Processing"}),e.jsx(Z,{value:"shipped",children:"Shipped"}),e.jsx(Z,{value:"completed",children:"Completed"}),e.jsx(Z,{value:"cancelled",children:"Cancelled"})]})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-gray-500",children:"Payment Method"}),e.jsx("p",{className:"font-medium",children:e.jsx(no,{title:d.paymentMethodTitle,fallback:d.paymentMethod})})]})]}),e.jsxs("div",{className:"rounded-lg border border-gray-200 bg-white p-3",children:[e.jsx("p",{className:"text-gray-500 text-xs uppercase tracking-wide mb-2",children:"Stripe Payment"}),e.jsx(Wc,{orderId:d.id})]}),e.jsx("div",{className:"rounded-lg border border-gray-200 bg-white p-3",onClick:z=>z.stopPropagation(),children:e.jsx(Yc,{orderId:d.id})}),d.shippingAddress&&e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"text-gray-500 mb-1",children:"Shipping Address"}),e.jsx("p",{className:"font-medium",children:d.shippingAddress}),e.jsx("p",{children:[d.shippingCity,d.shippingState,d.shippingPostcode].filter(
109Boolean).join(", ")}),e.jsx("p",{children:d.shippingCountry})]}),d.trackingNumber&&e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"text-gray-500 mb-1",children:"Tracking"}),e.jsxs("p",{className:"font-medium",children:[d.trackingCarrier,": ",d.trackingNumber]}),d.trackingUrl&&e.jsx("a",{href:d.trackingUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 text-xs hover:underline",children:"Track shipment"})]}),!d.trackingNumber&&d.scheduledShipDate&&e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"text-gray-500 mb-1",children:"ShippingEasy Schedule"}),e.jsxs("p",{className:"font-medium",children:["Ship date: ",d.scheduledShipDate,d.plannedCarrier?` · ${d.plannedCarrier}${d.plannedService?" "+d.plannedService:""}`:""]}),d.seStatus&&e.jsxs("p",{className:"text-xs text-gray-500 mt-0.5",children:["SE status: ",d.seStatus,d.shipmentWorkflowState?` · shipment: ${d.shipmentWorkflowState}`:""]})]}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"text-gray-500 mb-2",children:"Line Items"}),e.jsx("div",{className:"space-y-2",children:fe(d).map((z,T)=>e.jsxs("div",{className:"flex justify-between items-center py-1 border-b border-gray-100 last:border-0",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:z.name}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Qty: ",z.quantity]})]}),e.jsxs("p",{className:"font-medium",children:["$",parseFloat(String(z.price||"0")).toFixed(2)]})]},T))})]}),e.jsxs("div",{className:"border-t pt-3 space-y-1 text-sm",children:[parseFloat(d.discountTotal||"0")>0&&e.jsxs("div",{className:"flex justify-between text-green-600",children:[e.jsx("span",{children:"Discount"}),e.jsxs("span",{children:["-$",parseFloat(d.discountTotal).toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between font-semibold text-base",children:[e.jsx("span",{children:"Total"}),e.jsxs("span",{children:["$",parseFloat(d.total||"0").toFixed(2)]})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2 flex-wrap",onClick:z=>z.stopPropagation(),children:[e.jsxs(C,{size:"sm",variant:"outline",className:"border-blue-300 text-blue-700 hover:bg-blue-50",onClick:async()=>{try{const z=await fetch("/api/admin/view-customer-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({customerEmail:d.customerEmail})});if(!z.ok)throw new Error("Failed to generate token");const{token:T}=await z.json();window.open(`/my-account?admin_view=${T}`,"_blank")}catch{y({title:"Failed to open customer dashboard",variant:"destructive"})}},children:[e.jsx(ht,{className:"w-4 h-4 mr-1"}),"View Customer Dashboard"]}),e.jsxs(C,{size:"sm",variant:"outline",onClick:()=>P.mutate({id:d.id,type:"admin"}),disabled:P.isPending,children:[e.jsx(xt,{className:"w-4 h-4 mr-1"}),"Admin Email"]}),e.jsxs(C,{size:"sm",variant:"outline",onClick:()=>P.mutate({id:d.id,type:"customer_to_admin"}),disabled:P.isPending,children:[e.jsx(xt,{className:"w-4 h-4 mr-1"}),"Customer Email â Admin"]}),e.jsxs(C,{size:"sm",variant:"outline",onClick:()=>{window.confirm(`Send order confirmation email to ${d.customerEmail}?`)&&P.mutate({id:d.id,type:"customer"})},disabled:P.isPending,children:[e.jsx(xt,{className:"w-4 h-4 mr-1"}),"Email Customer"]}),e.jsxs(C,{size:"sm",variant:"outline",onClick:()=>{window.confirm(`${d.shippingEasyOrderId?"Re-push":"Push"} order ${d.orderNumber||d.id} to ShippingEasy?`)&&D.mutate(d.id)},disabled:D.isPending,children:[e.jsx(bt,{className:"w-4 h-4 mr-1"}),d.shippingEasyOrderId?"Re-push to ShippingEasy":"Push to ShippingEasy"]}),e.jsxs(C,{size:"sm",variant:"outline",className:"border-green-300 text-green-700 hover:bg-green-50",onClick:()=>b.mutate(d.id),disabled:b.isPending,children:[e.jsx(Ot,{className:`w-4 h-4 mr-1 ${b.isPending?"animate-spin":""}`}),b.isPending?"Checking...":"Check Order Status"]})]})]})})})]},d.id)}):e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"px-4 py-8 text-center text-sm text-gray-500",children:"No orders found"})}),g.length>ie.length&&e.jsx("tr",{children:e.jsxs("td",{colSpan:8,className:"px-4 py-3 text-center text-xs text-gray-500 bg-gray-50/50",children:["Showing ",ie.length," of ",g.length," orders â refine with search or a status filter to find others."]})})]})]})})})})]})}function Wc({orderId:t}){const{data:a,isLoading:s,isError:n}=he({queryKey:["/api/orders",t,"payment-status"],queryFn:async()=>{const x=await fetch(`/api/orders/${t}/payment-status`);if(!x.ok)throw new Error("Failed to load payment status");return x.json()}});if(s)return e.jsx("p",{className:"text-xs text-gray-500",children:"Loading payment statusâ¦"});if(n)return e.jsx("p",{className:"text-xs text-red-600",children:"Could not load Stripe payment status."});if(!(a!=null&&a.hasStripe))return e.jsx("p",{className:"text-xs text-gray-500",children:(a==null?void 0:a.message)||"No Stripe payment on this order."});const r=x=>`$${((x||0)/100).toFixed(2)}`,o=a.status==="succeeded"?"text-green-700 bg-green-50 border-green-200":a.status==="processing"||a.status==="requires_action"||a.status==="requires_confirmation"?"text-amber-700 bg-amber-50 border-amber-200":"text-red-700 bg-red-50 border-red-200";return e.jsxs("div",{className:"text-sm space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full border capitalize ${o}`,children:String(a.status||"unknown").replace(/_/g," ")}),e.jsx("span",{className:"font-medium",children:r(a.amountReceived||a.amount)}),e.jsx("span",{className:"text-gray-400 text-xs",children:a.currency}),a.refunded>0&&e.jsxs("span",{className:"text-xs text-orange-600 font-medium",children:["Refunded ",r(a.refunded)]})]}),a.card&&e.jsxs("p",{className:"text-xs text-gray-600",children:[String(a.card.brand||"").toUpperCase()," â¢â¢â¢â¢ ",a.card.last4," · exp ",String(a.card.expMonth).padStart(2,"0"),"/",a.card.expYear]}),a.failureMessage&&e.jsx("p",{className:"text-xs text-red-600",children:a.failureMessage}),e.jsxs("div",{className:"flex gap-4 text-xs",children:[a.receiptUrl&&e.jsx("a",{href:a.receiptUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline",children:"View receipt"}),a.dashboardUrl&&e.jsx("a",{href:a.dashboardUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline",children:"Open in Stripe â"})]}),e.jsx("p",{className:"text-[11px] text-gray-400 font-mono break-all",children:a.paymentIntentId})]})}function Yc({orderId:t}){const[a,s]=i.useState(!1),{data:n=[],isLoading:r}=he({queryKey:["/api/orders",t,"audits"],queryFn:async()=>{const m=await fetch(`/api/orders/${t}/audits`,{credentials:"include"});if(!m.ok)throw new Error("Failed to load order history");return m.json()},enabled:a}),o={admin:"bg-blue-50 text-blue-700 border-blue-200",system:"bg-gray-50 text-gray-700 border-gray-200"},x=m=>m==null||m===""?"â":typeof m=="object"?JSON.stringify(m):String(m);return e.jsxs("div",{children:[e.jsxs("button",{onClick:m=>{m.stopPropagation(),s(!a)},className:"flex items-center gap-2 text-sm font-bold text-gray-700 hover:text-gray-900","data-testid":`button-toggle-order-history-${t}`,children:[e.jsx(Ge,{className:`w-4 h-4 transition-transform ${a?"rotate-90":""}`}),"History ",n.length>0?`(${n.length})`:""]}),a&&e.jsx("div",{className:"mt-3",children:r?e.jsx("p",{className:"text-xs text-gray-400 py-3 text-center",children:"Loading historyâ¦"}):n.length===0?e.jsx("p",{className:"text-xs text-gray-400 py-3 text-center",children:"No history recorded yet. New changes will appear here."}):e.jsx("div",{className:"space-y-2",children:n.map(m=>{const h=m.changes&&typeof m.changes=="object"?m.changes:{},u=Object.keys(h);return e.jsxs("div",{className:"border border-gray-200 rounded-md p-3 bg-white text-xs","data-testid":`order-audit-row-${m.id}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-gray-900",children:m.action}),e.jsx(H,{variant:"outline",className:`text-[10px] capitalize ${o[m.source]||o.system}`,children:m.source}),m.actorEmail&&e.jsxs("span",{className:"text-gray-500",children:["by ",m.actorEmail]})]}),e.jsx("span",{className:"text-gray-400 whitespace-nowrap",children:new Date(m.createdAt).toLocaleStr
109ing("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})})]}),u.length>0&&e.jsx("div",{className:"space-y-1 text-gray-700",children:u.map(w=>{var y,j;return e.jsxs("div",{className:"grid grid-cols-[110px_1fr] gap-2",children:[e.jsxs("span",{className:"text-gray-400 font-medium truncate",children:[w,":"]}),e.jsxs("span",{className:"break-all",children:[x((y=h[w])==null?void 0:y.before)," â ",e.jsx("strong",{children:x((j=h[w])==null?void 0:j.after)})]})]},w)})}),m.notes&&e.jsx("div",{className:"mt-1 text-gray-500 italic",children:m.notes})]},m.id)})})})]})}function Jc(){var P;const{toast:t}=Ee(),[a,s]=i.useState(null),[n,r]=i.useState("open"),[o,x]=i.useState(""),m=i.useRef(null),h=["/api/admin/support/conversations",n],{data:u=[],isLoading:w}=he({queryKey:h,queryFn:async()=>{const D=await fetch(`/api/admin/support/conversations?status=${n}`,{credentials:"include"});if(!D.ok)throw new Error("Failed to load conversations");return D.json()},refetchInterval:15e3,staleTime:0}),y=["/api/admin/support/conversations",a,"thread"],{data:j}=he({queryKey:y,queryFn:async()=>{const D=await fetch(`/api/admin/support/conversations/${a}`,{credentials:"include"});if(!D.ok)throw new Error("Failed to load thread");return D.json()},enabled:!!a,refetchInterval:a?5e3:!1,staleTime:0}),v=()=>{X.invalidateQueries({queryKey:["/api/admin/support/conversations"]}),X.invalidateQueries({queryKey:["/api/admin/support/unread-count"]})},k=async D=>{s(D),x("");try{await ae(`/api/admin/support/conversations/${D}/read`,"POST"),v()}catch{}},F=ee({mutationFn:async()=>ae(`/api/admin/support/conversations/${a}/reply`,"POST",{message:o.trim()}),onSuccess:D=>{X.setQueryData(y,D),x(""),v()},onError:D=>t({title:"Reply failed",description:D.message,variant:"destructive"})}),L=ee({mutationFn:async({id:D,action:b})=>ae(`/api/admin/support/conversations/${D}/${b}`,"POST"),onSuccess:()=>{X.invalidateQueries({queryKey:y}),v()},onError:D=>t({title:"Failed",description:D.message,variant:"destructive"})});i.useEffect(()=>{m.current&&(m.current.scrollTop=m.current.scrollHeight)},[(P=j==null?void 0:j.messages)==null?void 0:P.length,a]);const c=D=>{if(!D)return"";const b=Math.floor((Date.now()-new Date(D).getTime())/6e4);return b<1?"just now":b<60?`${b}m ago`:b<1440?`${Math.floor(b/60)}h ago`:new Date(D).toLocaleDateString("en-US",{month:"short",day:"numeric"})},f=j==null?void 0:j.conversation;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900",children:"Support"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Customer chat conversations â bot handles status questions, you handle the rest."})]}),e.jsxs(Ne,{value:n,onValueChange:D=>{r(D),s(null)},children:[e.jsx(we,{className:"w-32 h-9 text-sm",children:e.jsx(Ce,{})}),e.jsxs(Se,{children:[e.jsx(Z,{value:"open",children:"Open"}),e.jsx(Z,{value:"closed",children:"Closed"}),e.jsx(Z,{value:"all",children:"All"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[340px_1fr] gap-4 items-start",children:[e.jsx(G,{className:"overflow-hidden",children:e.jsxs(Q,{className:"p-0 max-h-[70vh] overflow-y-auto",children:[w&&e.jsx("p",{className:"text-sm text-gray-400 text-center py-8",children:"Loadingâ¦"}),!w&&u.length===0&&e.jsxs("p",{className:"text-sm text-gray-400 text-center py-8",children:["No ",n!=="all"?n:""," conversations."]}),u.map(D=>e.jsxs("button",{onClick:()=>k(D.id),className:`w-full text-left px-4 py-3 border-b last:border-0 transition-colors hover:bg-gray-50 ${a===D.id?"bg-amber-50/60":""}`,"data-testid":`support-conversation-${D.id}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-0.5",children:[e.jsx("span",{className:"text-sm font-semibold text-gray-900 truncate",children:D.customerName||D.customerEmail||"Guest"}),e.jsx("span",{className:"text-[11px] text-gray-400 whitespace-nowrap",children:c(D.lastMessageAt)})]}),e.jsxs("div",{className:"flex items-center gap-1.5 mb-1 flex-wrap",children:[D.userId==null&&e.jsx(H,{variant:"outline",className:"text-[10px] py-0 px-1.5 border-amber-300 text-amber-700",children:"Guest"}),D.needsHuman&&D.status==="open"&&e.jsx(H,{variant:"outline",className:"text-[10px] py-0 px-1.5 border-red-300 text-red-700",children:"Needs reply"}),D.status==="closed"&&e.jsx(H,{variant:"outline",className:"text-[10px] py-0 px-1.5 text-gray-500",children:"Closed"}),D.adminUnread>
1090&&e.jsxs(H,{className:"bg-blue-600 text-white text-[10px] py-0 px-1.5",children:[D.adminUnread," new"]})]}),e.jsx("p",{className:"text-xs text-gray-500 truncate",children:D.lastMessageBody||"â"})]},D.id))]})}),e.jsx(G,{className:"overflow-hidden",children:!a||!f?e.jsx(Q,{className:"py-16 text-center text-sm text-gray-400",children:"Select a conversation to read and reply."}):e.jsxs(Q,{className:"p-0 flex flex-col max-h-[70vh]",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b bg-gray-50/60",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"text-sm font-semibold text-gray-900 truncate",children:[f.customerName||f.customerEmail||"Guest",f.userId==null&&e.jsx("span",{className:"ml-2 text-xs font-normal text-amber-700",children:"(guest â email unverified)"})]}),f.customerEmail&&e.jsx("p",{className:"text-xs text-gray-500",children:f.customerEmail})]}),e.jsx(C,{size:"sm",variant:"outline",className:"h-8 text-xs",disabled:L.isPending,onClick:()=>L.mutate({id:f.id,action:f.status==="closed"?"reopen":"close"}),children:f.status==="closed"?"Reopen":"Close conversation"})]}),e.jsx("div",{ref:m,className:"flex-1 overflow-y-auto px-4 py-3 space-y-2 min-h-[280px]",children:((j==null?void 0:j.messages)||[]).map(D=>{const b=D.senderRole==="customer"||D.senderRole==="guest";return e.jsx("div",{className:`flex ${b?"justify-start":"justify-end"}`,children:e.jsxs("div",{className:`text-sm rounded-lg px-3 py-2 max-w-[80%] whitespace-pre-wrap break-words ${b?"bg-gray-100 text-gray-900":D.senderRole==="bot"?"bg-amber-50 text-gray-700 border border-amber-100":"bg-blue-600 text-white"}`,children:[e.jsx("p",{className:`text-[10px] font-semibold uppercase tracking-wide mb-0.5 ${b?"text-gray-400":D.senderRole==="bot"?"text-amber-600":"text-blue-200"}`,children:b?D.senderRole==="guest"?"Guest":"Customer":D.senderRole==="bot"?"Bot":D.senderEmail||"Admin"}),D.body,e.jsx("p",{className:`text-[10px] mt-1 ${b?"text-gray-400":D.senderRole==="bot"?"text-amber-500":"text-blue-200"}`,children:new Date(D.createdAt).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})})]})},D.id)})}),f.status==="open"?e.jsxs("div",{className:"border-t px-4 py-3 flex gap-2",children:[e.jsx(Ze,{value:o,onChange:D=>x(D.target.value),onKeyDown:D=>{D.key==="Enter"&&!D.shiftKey&&o.trim()&&(D.preventDefault(),F.mutate())},placeholder:"Reply to the customer⦠(Enter to send, Shift+Enter for newline)",rows:2,className:"flex-1 text-sm resize-none","data-testid":"input-support-admin-reply"}),e.jsx(C,{onClick:()=>F.mutate(),disabled:!o.trim()||F.isPending,className:"self-end bg-blue-600 hover:bg-blue-700 text-white","data-testid":"button-support-admin-send",children:F.isPending?"Sendingâ¦":"Send"})]}):e.jsx("div",{className:"border-t px-4 py-3 text-xs text-gray-500 text-center",children:"Conversation is closed â reopen it to reply."})]})})]})]})}function Zc(){const[t,a]=i.useState(""),[s,n]=i.useState(""),[r,o]=i.useState("all"),[x,m]=i.useState(1),h=100,[u,w]=i.useState(null),[y,j]=i.useState(new Set),[v,k]=i.useState(!1),[F,L]=i.useState(!1),[c,f]=i.useState({email:"",firstName:"",lastName:""}),[P,D]=i.useState(""),[b,O]=i.useState(null),{toast:g}=Ee();i.useEffect(()=>{const N=setTimeout(()=>{n(t),m(1)},400);return()=>clearTimeout(N)},[t]);const[B,ie]=i.useState("newest"),{data:xe,isLoading:fe,isError:d,error:q}=he({queryKey:["/api/users","paginated",x,s,r,B],queryFn:async()=>{const N=new URLSearchParams({page:String(x),limit:String(h)});s&&N.set("search",s),r!=="all"&&N.set("welcomeFilter",r),B==="total_ordered"&&N.set("sortBy","total_ordered");const J=await fetch(`/api/users?${N}`,{credentials:"include"});if(!J.ok){const ce=await J.json().catch(()=>({}));throw new Error(ce.error||`Failed to load customers (${J.status})`)}return J.json()}}),z=(xe==null?void 0:xe.users)||[],T=(xe==null?void 0:xe.total)||0,M=Math.ceil(T/h),U=ee({mutationFn:async N=>{const J=await fetch(`/api/users/${N}/send-welcome-dashboard`,{method:"POST"});if(!J.ok){const ce=await J.json();throw new Error(ce.error||"Failed to send")}
109return J.json()},onSuccess:N=>{g({title:"Welcome email sent",description:N.message})},onError:N=>{g({title:"Send failed",description:N.message,variant:"destructive"})}}),_=ee({mutationFn:async({id:N,testToAdmins:J})=>{const ce=await fetch(`/api/users/${N}/send-payment-update-email`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({testToAdmins:!!J})});if(!ce.ok){const p=await ce.json();throw new Error(p.error||"Failed to send")}return ce.json()},onSuccess:N=>{g({title:"Payment update email sent",description:N.message})},onError:N=>{g({title:"Send failed",description:N.message,variant:"destructive"})}}),[R,ue]=i.useState(null),[te,A]=i.useState(""),[$,Y]=i.useState(""),K=ee({mutationFn:async({id:N,points:J,reason:ce})=>ae(`/api/users/${N}/points`,"POST",{points:J,reason:ce}),onSuccess:N=>{g({title:`${N.points>0?"+":""}${N.points} points ${N.points>0?"granted":"deducted"}`,description:N.balance!=null?`New balance: ${N.balance} points.`:void 0}),X.invalidateQueries({queryKey:["/api/users"]}),ue(null),A(""),Y("")},onError:N=>{g({title:"Points update failed",description:N.message,variant:"destructive"})}}),re=()=>{const N=z.filter(pe=>y.has(pe.id));if(N.length===0)return;const J=pe=>`"${String(pe??"").replace(/"/g,'""')}"`,ce=["Name,Email",...N.map(pe=>`${J([pe.firstName,pe.lastName].filter(Boolean).join(" ")||pe.username)},${J(pe.email)}`)].join(`\r 110`),p=new Blob([ce],{type:"text/csv;charset=utf-8;"}),V=URL.createObjectURL(p),me=document.createElement("a");me.href=V,me.download=`mandala-customers-${new Date().toISOString().slice(0,10)}.csv`,document.body.appendChild(me),me.click(),document.body.removeChild(me),URL.revokeObjectURL(V),g({title:"CSV downloaded",description:`${N.length} customer${N.length===1?"":"s"} exported.`})},[ne,ge]=i.useState(!1),[oe,l]=i.useState(""),[W,se]=i.useState(""),de=ee({mutationFn:async({userIds:N,points:J,reason:ce})=>ae("/api/users/bulk-points","POST",{userIds:N,points:J,reason:ce}),onSuccess:N=>{g({title:`+${N.points} points granted to ${N.granted} customer${N.granted===1?"":"s"}`,description:N.skipped?`${N.skipped} skipped.`:void 0}),X.invalidateQueries({queryKey:["/api/users"]}),ge(!1),l(""),se(""),j(new Set)},onError:N=>{g({title:"Bulk points failed",description:N.message,variant:"destructive"})}}),Me=ee({mutationFn:async N=>{const J=await fetch("/api/users/bulk-send-welcome-dashboard",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userIds:N})});if(!J.ok){const ce=await J.json();throw new Error(ce.error||"Failed to send")}return J.json()},onSuccess:N=>{g({title:"Bulk emails sent",description:`${N.sent} of ${N.total} emails sent successfully`}),j(new Set)},onError:N=>{g({title:"Bulk send failed",description:N.message,variant:"destructive"})}}),ct=N=>{j(J=>{const ce=new Set(J);return ce.has(N)?ce.delete(N):ce.add(N),ce})},I=()=>{y.size===z.length?j(new Set):j(new Set(z.map(N=>N.id)))},le=ee({mutationFn:async N=>{const J=await fetch("/api/users/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(N)});if(!J.ok){const ce=await J.json();throw new Error(ce.error||"Failed to create")}return J.json()},onSuccess:()=>{X.invalidateQueries({queryKey:["/api/users"]}),g({title:"Customer created"}),k(!1),f({email:"",firstName:"",lastName:""})},onError:N=>{g({title:"Failed",description:N.message,variant:"destructive"})}}),ve=async()=>{const N=P.trim().split(` 111`).filter(p=>p.trim());if(N.length===0)return;O({done:0,total:N.length,errors:[]});let J=0;const ce=[];for(const p of N){const V=p.split(",").map(Ye=>Ye.trim()),me=V[0],pe=V[1]||"",Wt=V[2]||"";if(!me||!me.includes("@")){ce.push(`Invalid: ${me}`),J++,O({done:J,total:N.length,errors:[...ce]});continue}try{const Ye=await fetch("/api/users/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:me,firstName:pe,lastName:Wt})});if(!Ye.ok){const ot=await Ye.json();
111ce.push(`${me}: ${ot.error}`)}}catch(Ye){ce.push(`${me}: ${Ye.message}`)}J++,O({done:J,total:N.length,errors:[...ce]})}X.invalidateQueries({queryKey:["/api/users"]}),g({title:"Bulk import complete",description:`${J-ce.length} created, ${ce.length} skipped`})},_e=ee({mutationFn:async N=>{const J=await ae("DELETE",`/api/users/${N}`);if(!J.ok){const ce=await J.json();throw new Error(ce.error||"Failed to delete customer")}},onSuccess:()=>{X.invalidateQueries({queryKey:["/api/users"]}),g({title:"Customer deleted",description:"The customer has been removed."}),w(null)},onError:N=>{g({title:"Cannot delete",description:N.message,variant:"destructive"}),w(null)}});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"Customers"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-sm text-gray-500",children:[T," total"]}),e.jsxs(C,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>L(!0),children:[e.jsx(Be,{className:"h-3.5 w-3.5"})," Bulk Import"]}),e.jsxs(C,{size:"sm",className:"bg-amber-600 hover:bg-amber-700 text-white gap-1.5",onClick:()=>k(!0),children:[e.jsx(Be,{className:"h-3.5 w-3.5"})," Add Customer"]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative max-w-sm flex-1",children:[e.jsx(He,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx(E,{placeholder:"Search customers...",className:"pl-9",value:t,onChange:N=>a(N.target.value)})]}),e.jsx("div",{className:"flex items-center gap-1 border rounded-lg p-0.5",children:[["all","All"],["not_sent","Not Contacted"],["sent","Contacted"],["unsubscribed","Unsubscribed"]].map(([N,J])=>e.jsx("button",{onClick:()=>{o(N),m(1)},className:`px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${r===N?"bg-amber-600 text-white":"text-gray-600 hover:bg-gray-100"}`,children:J},N))}),y.size>0&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(C,{size:"sm",className:"bg-amber-600 hover:bg-amber-700 text-white gap-2",onClick:()=>Me.mutate(Array.from(y)),disabled:Me.isPending,children:[e.jsx(xt,{className:"h-4 w-4"}),Me.isPending?"Sending...":`Send Welcome Email (${y.size})`]}),e.jsxs(C,{size:"sm",variant:"outline",className:"border-yellow-500/50 hover:bg-yellow-50 gap-2",style:{color:"#a16207"},onClick:()=>{l(""),se(""),ge(!0)}
111,"data-testid":"button-bulk-points",children:[e.jsx(Qe,{className:"h-4 w-4"}),`Add Points (${y.size})`]}),e.jsxs(C,{size:"sm",variant:"outline",className:"border-gray-300 text-gray-700 hover:bg-gray-50 gap-2",onClick:re,title:"Download name + email of the selected customers","data-testid":"button-download-csv",children:[e.jsx(ps,{className:"h-4 w-4"}),`Download CSV (${y.size})`]})]})]}),e.jsx(G,{className:"border border-gray-200 shadow-sm",children:e.jsx(Q,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{className:"bg-gray-50 border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3 w-10",children:e.jsx("div",{className:`w-4 h-4 border-2 rounded cursor-pointer flex items-center justify-center ${z.length>0&&y.size===z.length?"bg-amber-600 border-amber-600":"border-gray-400"}`,onClick:I,children:z.length>0&&y.size===z.length&&e.jsx(ns,{className:"h-3 w-3 text-white"})})}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-3",children:"Customer"}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-3",children:"Email"}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-3",children:"Role"}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-3",children:"Status"}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-3",children:"Joined"}),e.jsx("th",{className:"text-right text-xs font-medium text-gray-500 uppercase px-4 py-3",children:e.jsxs("button",{type:"button",onClick:()=>ie(B==="total_ordered"?"newest":"total_ordered"),className:`ml-auto inline-flex items-center gap-1 transition-colors uppercase ${B==="total_ordered"?"text-gray-900":"hover:text-gray-900"}`,title:"Sort by lifetime order total","data-testid":"button-sort-total-ordered",children:["Total Ordered ",B==="total_ordered"?e.jsx(hs,{className:"w-3 h-3"}):e.jsx(st,{className:"w-3 h-3 opacity-40"})]})}),e.jsx("th",{className:"text-right text-xs font-medium text-gray-500 uppercase px-4 py-3",children:"Actions"})]})}),e.jsx("tbody",{children:fe?e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"px-4 py-8 text-center text-sm text-gray-500",children:"Loading customers..."})}):d?e.jsx("tr",{children:e.jsxs("td",{colSpan:8,className:"px-4 py-8 text-center text-sm text-red-600",children:["Couldn't load customers: ",(q==null?void 0:q.message)||"unknown error",". Try refreshing."]})}):z.length>0?z.map(N=>{var J;return e.jsxs("tr",{className:`border-b last:border-0 hover:bg-gray-50 transition-colors ${y.has(N.id)?"bg-amber-50":""}`,children:[e.jsx("td",{className:"px-4 py-3 w-10",children:e.jsx("div",{className:`w-4 h-4 border-2 rounded cursor-pointer flex items-center justify-center ${y.has(N.id)?"bg-amber-600 border-amber-600":"border-gray-400 hover:border-amber-400"}`,onClick:()=>ct(N.id),children:y.has(N.id)&&e.jsx(ns,{className:"h-3 w-3 text-white"})})}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center text-xs font-medium text-gray-600",children:(((J=N.firstName)==null?void 0:J[0])||N.username[0]).toUpperCase()}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-medium text-gray-900",children:[N.firstName&&N.lastName?`${N.firstName} ${N.lastName}`:N.username,e.jsxs("span",{className:"ml-1.5 text-xs text-gray-400 font-normal",children:["#",N.id]})]}),e.jsxs("p",{className:"text-xs text-gray-500",children:["@",N.username]})]})]})}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-600",children:N.email}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(H,{variant:"outline",className:`text-xs capitalize ${N.role==="admin"?"border-purple-200 bg-purple-50 text-purple-700":"border-gray-200 bg-gray-50 text-gray-700"}`,children:N.role})}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(H,{variant:"outline",className:`text-xs ${N.isActive?"border-green-200 bg-green-50 text-green-700":"border-red-200 bg-red-50 text-red-700"}`,children:N.isActive?"Active":"Inactive"}),N.welcomeEmailSent&&e.jsx(H,{variant:"outline",className:"text-xs border-blue-200 bg-blue-50 text-blue-700",children:"Contacted"}),N.marketingUnsubscribed&&e.jsx(H,{variant:"outline",className:"text-xs border-orange-200 bg-orange-50 text-orange-700",children:"Unsubscribed"})]})}),e.jsx("td",{className:"px-4 py-3 text-sm text-gray-500",children:N.createdAt?new Date(N.createdAt).toLocaleDateString():"-"}),e.jsxs("td",{className:"px-4 py-3 text-right text-sm font-semibold text-gray-900",children:["$",Number(N.totalOrdered||0).toFixed(2)]}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsxs(C,{variant:"outline",size:"sm",className:"h-8 px-3 text-blue-700 border-blue-300 hover:bg-blue-50 gap-1.5",onClick:async()=>{try{const ce=await fetch("/api/admin/view-customer-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({customerEmail:N.email})});if(!ce.ok)throw new Error("Failed to generate token");const{token:p}=await ce.json();window.open(`/my-account?admin_view=${p}`,"_blank")}catch{g({title:"Failed to open customer dashboard",variant:"destructive"})}},title:"View customer's dashboard",children:[e.jsx(ht,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"View"})]}),e.jsxs(C,{variant:"outline",size:"sm",className:"h-8 px-3 text-amber-700 border-amber-300 hover:bg-amber-50 gap-1.5",onClick:()=>U.mutate(N.id),disabled:U.isPending,title:"Send welcome dashboard email",children:[e.jsx(xt,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Welcome"})]}),e.jsxs(C,{variant:"outline",size:"sm",className:"h-8 px-3 text-emerald-700 border-emerald-300 hover:bg-emerald-50 gap-1.5",onClick:()=>_.mutate({id:N.id}),disabled:_.isPending,title:"Email this customer to update payment info (keeps legacy pricing)",children:[e.jsx(ls,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Billing"})]}),e.jsx(C,{variant:"outline",size:"sm",className:"h-8 px-2 text-gray-500 border-gray-300 hover:bg-gray-50",onClick:()=>_.mutate({id:N.id,testToAdmins:!0}),disabled:_.isPending,title:"Send a test of the payment update email to the admin inboxes",children:e.jsx("span",{className:"text-xs",children:"Test"})}),e.jsxs(C,{variant:"outline",size:"sm",className:"h-8 px-3 gap-1.5 border-yellow-500/40 hover:bg-yellow-50",style:{color:"#a16207"},onClick:()=>{ue(N),A(""),Y("")}
111,title:`Grant or deduct rewards points (current: ${N.pointsBalance??0})`,"data-testid":`button-points-${N.id}`,children:[e.jsx(Qe,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Points"})]}),N.role!=="admin"&&e.jsx(C,{variant:"ghost",size:"sm",className:"h-8 px-2 text-red-500 hover:text-red-700 hover:bg-red-50",onClick:()=>w(N),children:e.jsx(Ve,{className:"h-4 w-4"})})]})})]},N.id)}):e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"px-4 py-8 text-center text-sm text-gray-500",children:"No customers found"})})})]})})})}),M>1&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-gray-500",children:["Showing ",(x-1)*h+1,"â",Math.min(x*h,T)," of ",T]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(C,{variant:"outline",size:"sm",disabled:x<=1,onClick:()=>m(N=>N-1),children:"Previous"}),e.jsxs("span",{className:"text-sm text-gray-600",children:["Page ",x," of ",M]}),e.jsx(C,{variant:"outline",size:"sm",disabled:x>=M,onClick:()=>m(N=>N+1),children:"Next"})]})]}),e.jsx(Ie,{open:v,onOpenChange:k,children:e.jsxs(De,{className:"sm:max-w-md",children:[e.jsx(Oe,{children:e.jsx(Te,{children:"Add Customer"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Email *"}),e.jsx(E,{value:c.email,onChange:N=>f(J=>({...J,email:N.target.value})),placeholder:"[email protected]"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"First Name"}),e.jsx(E,{value:c.firstName,onChange:N=>f(J=>({...J,firstName:N.target.value})),placeholder:"First"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:"Last Name"}),e.jsx(E,{value:c.lastName,onChange:N=>f(J=>({...J,lastName:N.target.value})),placeholder:"Last"})]})]}),e.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[e.jsx(C,{variant:"outline",onClick:()=>k(!1),children:"Cancel"}),e.jsx(C,{className:"bg-amber-600 hover:bg-amber-700 text-white",disabled:!c.email||le.isPending,onClick:()=>le.mutate(c),children:le.isPending?"Creating...":"Create Customer"})]})]})]})}),e.jsx(Ie,{open:F,onOpenChange:N=>{N||(L(!1),O(null),D(""))},children:e.jsxs(De,{className:"sm:max-w-lg",children:[e.jsx(Oe,{children:e.jsx(Te,{children:"Bulk Import Customers"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-gray-600",children:["Paste one customer per line in format: ",e.jsx("code",{className:"bg-gray-100 px-1 py-0.5 rounded text-xs",children:"email, first name, last name"})]}),e.jsx("textarea",{className:"w-full h-48 border rounded-md p-3 text-sm font-mono resize-none focus:outline-none focus:ring-2 focus:ring-amber-500",placeholder:`[email protected], Sonya, Curtis 112[email protected], John, Doe`,value:P,onChange:N=>D(N.target.value),disabled:!!b&&b.done<b.total}),b&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"w-full bg-gray-200 rounded-full h-2",children:e.jsx("div",{className:"bg-amber-600 h-2 rounded-full transition-all",style:{width:`${b.done/b.total*100}%`}})}),e.jsxs("p",{className:"text-sm text-gray-600",children:[b.done," / ",b.total," processed",b.errors.length>0?` (${b.errors.length} errors)`:""]}),b.errors.length>0&&e.jsx("div",{className:"max-h-24 overflow-y-auto bg-red-50 border border-red-200 rounded p-2",children:b.errors.map((N,J)=>e.jsx("p",{className:"text-xs text-red-600",children:N},J))})]}),e.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[e.jsx(C,{variant:"outline",onClick:()=>{L(!1),O(null),D("")},children:"Close"}),e.jsx(C,{className:"bg-amber-600 hover:bg-amber-700 text-white",disabled:!P.trim()||!!b&&b.done<b.total,onClick:ve,children:"Import"})]})]})]})}),e.jsx(Ie,{open:!!u,onOpenChange:N=>!N&&w(null),children:e.jsxs(De,{className:"sm:max-w-md",children:[e.jsx(Oe,{children:e.jsx(Te,{className:"text-red-600",children:"Delete Customer"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-gray-600",children:["Are you sure you want to permanently delete"," ",e.jsx("span",{className:"font-semibold text-gray-900",children:u!=null&&u.firstName&&(u!=null&&u.lastName)?`${u.firstName} ${u.lastName}`:u==null?void 0:u.email}),"? This action cannot be undone."]}),e.jsx("p",{className:"text-xs text-gray-500",children:"If this customer has orders or subscriptions, the deletion will be blocked. You can deactivate them instead."}),e.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[e.jsx(C,{variant:"outline",onClick:()=>w(null),children:"Cancel"}),e.jsx(C,{variant:"destructive",disabled:_e.isPending,onClick:()=>u&&_e.mutate(u.id),children:_e.isPending?"Deleting...":"Delete Customer"})]})]})]})}),e.jsx(Ie,{open:!!R,onOpenChange:N=>!N&&ue(null),children:e.jsxs(De,{className:"sm:max-w-md",children:[e.jsx(Oe,{children:e.jsxs(Te,{className:"flex items-center gap-2",children:[e.jsx(Qe,{className:"h-5 w-5 text-amber-600"})," Rewards Points"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-gray-600",children:[e.jsxs("p",{children:[e.jsx("span",{className:"font-semibold text-gray-900",children:R!=null&&R.firstName&&(R!=null&&R.lastName)?`${R.firstName} ${R.lastName}`:R==null?void 0:R.email})," ","(",R==null?void 0:R.email,")"]}),e.jsxs("p",{className:"mt-1",children:["Current balance:"," ",e.jsxs("span",{className:"font-semibold text-amber-700",children:[(R==null?void 0:R.points
112Balance)??0," points"]}),e.jsx("span",{className:"text-xs text-gray-400 ml-2",children:"(100 pts = $5 at checkout)"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700 block mb-1",children:"Points"}),e.jsx(E,{type:"number",value:te,onChange:N=>A(N.target.value),placeholder:"e.g. 100 to grant, -50 to deduct","data-testid":"input-points-amount"}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:"Positive grants points; negative deducts (can't go below 0)."})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700 block mb-1",children:"Reason (shown in the customer's points history)"}),e.jsx(E,{value:$,onChange:N=>Y(N.target.value),placeholder:"e.g. Goodwill for late delivery","data-testid":"input-points-reason"})]}),e.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[e.jsx(C,{variant:"outline",onClick:()=>ue(null),children:"Cancel"}),e.jsx(C,{className:"bg-amber-600 hover:bg-amber-700 text-white",disabled:K.isPending||!$.trim()||!te.trim()||!Math.trunc(Number(te)),onClick:()=>{R&&K.mutate({id:R.id,points:Math.trunc(Number(te)),reason:$.trim()})},"data-testid":"button-points-submit",children:K.isPending?"Applyingâ¦":Math.trunc(Number(te))<0?"Deduct Points":"Grant Points"})]})]})]})}),e.jsx(Ie,{open:ne,onOpenChange:ge,children:e.jsxs(De,{className:"sm:max-w-md",children:[e.jsx(Oe,{children:e.jsxs(Te,{className:"flex items-center gap-2",children:[e.jsx(Qe,{className:"h-5 w-5 text-amber-600"})," Add Points to ",y.size," Customer",y.size===1?"":"s"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600",children:"Each selected customer receives the same amount, recorded in their points history with your reason. Bulk grants are positive only â use the per-customer Points button to deduct."}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700 block mb-1",children:"Points per customer"}),e.jsx(E,{type:"number",min:1,value:oe,onChange:N=>l(N.target.value),placeholder:"e.g. 100 (= $5 at checkout)","data-testid":"input-bulk-points-amount"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700 block mb-1",children:"Reason (shown in customers' points history)"}),e.jsx(E,{value:W,onChange:N=>se(N.target.value),placeholder:"e.g. Holiday thank-you bonus","data-testid":"input-bulk-points-reason"})]}),e.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[e.jsx(C,{variant:"outline",onClick:()=>ge(!1),children:"Cancel"}),e.jsx(C,{className:"bg-amber-600 hover:bg-amber-700 text-white",disabled:de.isPending||!W.trim()||Math.trunc(Number(oe))<=0,onClick:()=>de.mutate({userIds:Array.from(y),points:Math.trunc(Number(oe)),reason:W.trim()}
112),"data-testid":"button-bulk-points-submit",children:de.isPending?"Grantingâ¦":`Grant ${Math.trunc(Number(oe))>0?`+${Math.trunc(Number(oe))} `:""}to ${y.size}`})]})]})]})})]})}function Xc(){const{toast:t}=Ee(),[a,s]=i.useState(""),[n,r]=i.useState("all"),[o,x]=i.useState("all"),[m,h]=i.useState("default"),[u,w]=i.useState(null),[y,j]=i.useState(null),[v,k]=i.useState(null),[F,L]=i.useState(!1),[c,f]=i.useState({customerEmail:"",customerFirstName:"",customerLastName:"",customerPhone:"",frequency:"monthly",status:"active",orderTotal:"",notes:"",shippingAddress:"",shippingCity:"",shippingState:"",shippingPostcode:""}),[P,D]=i.useState([]),[b,O]=i.useState(""),{data:g,isLoading:B,isError:ie}=he({queryKey:["/api/subscriptions"]}),{data:xe}=he({queryKey:["/api/products"]}),{data:fe}=he({queryKey:["/api/orders","all"],queryFn:async()=>{const p=await fetch("/api/orders?all=true");if(!p.ok)throw new Error("Failed to load orders");return p.json()}}),d=["/api/subscriptions"],q=()=>{try{return{email:JSON.parse(localStorage.getItem("currentUser")||"{}").email||null,role:"admin",source:"admin"}}catch{return{email:null,role:"admin",source:"admin"}}},z=ee({mutationFn:p=>ae(`/api/subscriptions/${p}/pause`,"POST",{_actor:q()}),onSuccess:()=>{X.invalidateQueries({queryKey:d}),t({title:"Subscription paused"})},onError:()=>t({title:"Failed to pause",variant:"destructive"})}),T=ee({mutationFn:p=>ae(`/api/subscriptions/${p}/resume`,"POST",{_actor:q()}),onSuccess:()=>{X.invalidateQueries({queryKey:d}),t({title:"Subscription resumed"})},onError:()=>t({title:"Failed to resume",variant:"destructive"})}),M=ee({mutationFn:p=>ae(`/api/subscriptions/${p}/cancel`,"POST",{_actor:q()}),onSuccess:()=>{X.invalidateQueries({queryKey:d}),t({title:"Subscription cancelled"})},onError:()=>t({title:"Failed to cancel",variant:"destructive"})}),U=ee({mutationFn:p=>ae(`/api/subscriptions/${p}/reactivate`,"POST",{_actor:q()}),onSuccess:()=>{X.invalidateQueries({queryKey:d}),t({title:"Subscription reactivated"})},onError:()=>t({title:"Failed to reactivate",variant:"destructive"})}),[_,R]=i.useState(null),ue=()=>{if(_){switch(_.type){case"cancel":M.mutate(_.subId);break;case"reactivate":U.mutate(_.subId);break;case"pause":z.mutate(_.subId);break;case"resume":T.mutate(_.subId);break}R(null)}},[te,A]=i.useState(null),[$,Y]=i.useState(!1),K=async p=>{if(confirm(`Send a renewal reminder email to ${p.customerEmail}?`))try{const V=await ae(`/api/subscriptions/${p.id}/send-renewal-reminder`,"POST");t({title:"Reminder sent",description:(V==null?void 0:V.message)||`Renewal reminder sent to ${p.customerEmail}.`})}catch(V){t({title:V.message||"Failed to send reminder",variant:"destructive"})}},re=te&&Array.isArray(te.items)?te.items.reduce((p,V)=>p+(parseFloat(V.price)||0)*(V.quantity||1),0):0,ne=te?parseFloat(te.orderTotal||"0")>0?parseFloat(te.orderTotal):re:0,ge=ne.toFixed(2),oe=async()=>{if(te){Y(!0);try{const p=await ae(`/api/subscriptions/${te.id}/charge-now`,"POST");X.invalidateQueries({queryKey:d}),t({title:"Subscription renewed successfully",description:`Charged $${p.amountCharged} to ${p.customerEmail}. Next renewal updated.`}),A(null)}catch(p){t({title:p.message||"Failed to charge",variant:"destructive"})}finally{Y(!1)}}},l=ee({mutationFn:({id:p,data:V})=>ae(`/api/subscriptions/${p}`,"PATCH",{...V,_actor:q()}),onSuccess:()=>{X.invalidateQueries({queryKey:d}),j(null),t({title:"Subscription updated"})},onError:()=>t({title:"Failed to update",variant:"destructive"})}),W=ee({mutationFn:({id:p,items:V})=>ae(`/api/subscriptions/${p}/update-items`,"POST",{items:V,_actor:q()}),onSuccess:()=>{X.invalidateQueries({queryKey:d}),t({title:"Items updated"})},onError:()=>t({title:"Failed to update items",variant:"destructive"})}),se=ee({mutationFn:p=>ae("/api/subscriptions","POST",p),onSuccess:()=>{X.invalidateQueries({queryKey:d}),L(!1),D([]),O(""),t({title:"Subscription created"})},onError:()=>t({title:"Failed to create subscription",variant:"destructive"})}),de=Array.isArray(g)?g.filter(p=>{if(n!=="all"&&p.status!==n||o!=="all"&&p.frequency!==o)return!1;if(a==="")return!0;const V=a.toLowerCase();return p.customerEmail.toLowerCase().includes(V)||p.customerFirstName.toLowerCase().includes(V)||p.customerLastName.toLowerCase().includes(V)||p.customerPhone&&p.customerPhone.includes(V)}
112).sort((p,V)=>{const me=p.nextPaymentDate?new Date(p.nextPaymentDate).getTime():null,pe=V.nextPaymentDate?new Date(V.nextPaymentDate).getTime():null;return m==="renewal_asc"?(me??1/0)-(pe??1/0):m==="renewal_desc"?me===null&&pe===null?0:me===null?1:pe===null?-1:pe-me:m==="status_asc"?(p.status||"").localeCompare(V.status||""):m==="status_desc"?(V.status||"").localeCompare(p.status||""):0}):[],Me=p=>{h(p==="renewal"?m==="renewal_asc"?"renewal_desc":"renewal_asc":m==="status_asc"?"status_desc":"status_asc")},ct=({col:p})=>{const V=p==="renewal"?"renewal_asc":"status_asc";return m!==V&&m!==(p==="renewal"?"renewal_desc":"status_desc")?e.jsx(st,{className:"w-3 h-3 opacity-40"}):m===V?e.jsx(pa,{className:"w-3 h-3"}):e.jsx(hs,{className:"w-3 h-3"})},I=Array.isArray(g)?g.filter(p=>p.status==="active").length:0,le=Array.isArray(g)?g.filter(p=>p.status==="paused").length:0,ve=Array.isArray(g)?g.filter(p=>p.status==="cancelled").length:0,_e=p=>{const V={active:"border-green-200 bg-green-50 text-green-700",paused:"border-amber-200 bg-amber-50 text-amber-700",cancelled:"border-red-200 bg-red-50 text-red-700",expired:"border-gray-200 bg-gray-50 text-gray-700"};return V[p]||V.expired},{data:N}=he({queryKey:["/api/subscription-frequencies"]}),J=p=>{const V=N==null?void 0:N.find(pe=>pe.value===p);return V?V.label:{weekly:"Weekly",biweekly:"Bi-weekly",monthly:"Monthly",every_4_weeks:"Every 4 weeks",every_6_weeks:"Every 6 weeks",every_8_weeks:"Every 8 weeks"}[p]||p},ce=p=>{if(!p)return"Missing";
112const V="America/New_York",me=new Date(p).toLocaleDateString("en-CA",{timeZone:V}).split("-").map(Number),pe=new Date().toLocaleDateString("en-CA",{timeZone:V}).split("-").map(Number),Wt=me[0]*365+me[1]*30+me[2],Ye=pe[0]*365+pe[1]*30+pe[2],ot=Wt-Ye,Et=new Date(p).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:V});return new Date(p).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric",timeZone:V}),ot<0?`Overdue (${Et})`:ot===0?`Today (${Et})`:ot<=7?`In ${ot} days (${Et})`:Et};return B?e.jsxs("div",{className:"space-y-6",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"Subscriptions"}),e.jsx("div",{className:"space-y-3",children:[1,2,3].map(p=>e.jsx("div",{className:"h-16 bg-gray-100 rounded-lg animate-pulse"},p))})]}):ie?e.jsxs("div",{className:"space-y-6",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"Subscriptions"}),e.jsx(G,{className:"border border-red-200 bg-red-50",children:e.jsx(Q,{className:"py-6 text-center text-sm text-red-600",children:"Failed to load subscriptions. Please try refreshing the page."})})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"Subscriptions"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Manage recurring orders and subscription plans"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(H,{variant:"outline",className:"border-green-200 bg-green-50 text-green-700 px-3 py-1",children:[I," active"]}),le>0&&e.jsxs(H,{variant:"outline",className:"border-amber-200 bg-amber-50 text-amber-700 px-3 py-1",children:[le," paused"]}),ve>0&&e.jsxs(H,{variant:"outline",className:"border-red-200 bg-red-50 text-red-700 px-3 py-1",children:[ve," cancelled"]}),e.jsxs(C,{size:"sm",onClick:()=>L(!0),className:"bg-amber-600 hover:bg-amber-700 text-white",children:[e.jsx(Be,{className:"h-4 w-4 mr-1"})," New Subscription"]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(He,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx(E,{placeholder:"Search by name, email, or phone...",className:"pl-9",value:a,onChange:p=>s(p.target.value)})]}),e.jsx("div",{className:"flex items-center gap-1 bg-gray-100 rounded-lg p-1",children:["all","active","paused","cancelled"].map(p=>e.jsx("button",{onClick:()=>r(p),className:`px-3 py-1.5 text-xs font-medium rounded-md transition-colors capitalize ${n===p?"bg-white text-gray-900 shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:p},p))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium text-gray-500",children:"Frequency:"}),e.jsxs(Ne,{value:o,onValueChange:x,children:[e.jsx(we,{className:"h-8 w-[160px] text-xs",children:e.jsx(Ce,{})}),e.jsxs(Se,{children:[e.jsx(Z,{value:"all",children:"All Frequencies"}),(N||[]).map(p=>e.jsx(Z,{value:p.value,children:p.label},p.id))]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium text-gray-500",children:"Sort:"}),e.jsxs(Ne,{value:m,onValueChange:h,children:[e.jsx(we,{className:"h-8 w-[180px] text-xs",children:e.jsx(Ce,{})}),e.jsxs(Se,{children:[e.jsx(Z,{value:"default",children:"Default"}),e.jsx(Z,{value:"renewal_asc",children:"Next Renewal (soonest)"}),e.jsx(Z,{value:"renewal_desc",children:"Next Renewal (latest)"})]})]})]})]}),e.jsx(G,{className:"border border-gray-200 shadow-sm",children:e.jsx(Q,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{className:"bg-gray-50 border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-3",children:"Customer"}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-3",children:"Plan"}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-3",children:e.jsxs("button",{type:"button",onClick:()=>Me("status"),className:"inline-flex items-center gap-1 hover:text-gray-900 transition-colors uppercase",children:["Status ",e.jsx(ct,{col:"status"})]})}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-3",children:"Total"}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-3",children:e.jsxs("button",{type:"button",onClick:()=>Me("renewal"),className:"inline-flex items-center gap-1 hover:text-gray-900 transition-colors uppercase",children:["Next Renewal ",e.jsx(ct,{col:"renewal"})]})}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-3",children:"Actions"}),e.jsx("th",{className:"w-10"})]})}),e.jsx("tbody",{children:de.length>0?de.map(p=>{const V=u===p.id;return e.jsx(to,{sub:p,isExpanded:V,onToggle:()=>w(V?null:p.id),getStatusBadge:_e,getFrequencyLabel:J,formatNextRenewal:ce,onPause:()=>R({type:"pause",subId:p.id,subName:`${p.customerFirstName} ${p.customerLastName}`}),onResume:()=>R({type:"resume",subId:p.id,subName:`${p.customerFirstName} ${p.customerLastName}`}),onCancel:()=>R({type:"cancel",subId:p.id,subName:`${p.customerFirstName} ${p.customerLastName}`}),onReactivate:()=>R({type:"reactivate",subId:p.id,subName:`${p.customerFirstName} ${p.customerLastName}`}),onChargeNow:()=>A(p),onSendRenewalReminder:()=>K(p),onEdit:()=>{j(p.id),k({...p})},onUpdateItems:me=>W.mutate({id:p.id,items:me}),onSetNextDate:me=>l.mutate({id:p.id,data:{nextPaymentDate:me?new Date(me):null}}),isUpdatingDate:l.isPending,products:xe||[],allOrders:fe||[],isActionPending:z.isPending||T.isPending||M.isPending||U.isPending||$},p.id)}):e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"px-4 py-8 text-center text-sm text-gray-500",children:"No subscriptions foun
112d"})})})]})})})}),e.jsx(Ie,{open:y!==null,onOpenChange:p=>{p||j(null)},children:e.jsxs(De,{className:"max-w-lg",children:[e.jsx(Oe,{children:e.jsx(Te,{children:"Edit Subscription"})}),v&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"First Name"}),e.jsx(E,{value:v.customerFirstName,onChange:p=>k({...v,customerFirstName:p.target.value}),className:"h-8 text-sm"})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Last Name"}),e.jsx(E,{value:v.customerLastName,onChange:p=>k({...v,customerLastName:p.target.value}),className:"h-8 text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Email"}),e.jsx(E,{value:v.customerEmail,onChange:p=>k({...v,customerEmail:p.target.value}),className:"h-8 text-sm"})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Phone"}),e.jsx(E,{value:v.customerPhone||"",onChange:p=>k({...v,customerPhone:p.target.value}),className:"h-8 text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Frequency"}),e.jsxs(Ne,{value:v.frequency,onValueChange:p=>k({...v,frequency:p}),children:[e.jsx(we,{className:"h-8 text-sm",children:e.jsx(Ce,{})}),e.jsx(Se,{children:(N||[]).filter(p=>p.isActive).map(p=>e.jsx(Z,{value:p.value,children:p.label},p.id))})]})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Status"}),e.jsxs(Ne,{value:v.status,onValueChange:p=>k({...v,status:p}),children:[e.jsx(we,{className:"h-8 text-sm",children:e.jsx(Ce,{})}),e.jsxs(Se,{children:[e.jsx(Z,{value:"active",children:"Active"}),e.jsx(Z,{value:"paused",children:"Paused"}),e.jsx(Z,{value:"cancelled",children:"Cancelled"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Order Total"}),e.jsx(E,{type:"number",step:"0.01",value:v.orderTotal||"",onChange:p=>k({...v,orderTotal:p.target.value}),className:"h-8 text-sm"})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Next Payment Date"}),e.jsx(E,{type:"date",value:v.nextPaymentDate?new Date(v.nextPaymentDate).toISOString().split("T")[0]:"",onChange:p=>k({...v,nextPaymentDate:p.target.value?new Date(p.target.value):null}),className:"h-8 text-sm"})]})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Notes"}),e.jsx(E,{value:v.notes||"",onChange:p=>k({...v,notes:p.target.value}),className:"h-8 text-sm"})]}),e.jsx("h4",{className:"text-xs font-semibold text-gray-500 uppercase",children:"Shipping"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Address"}),e.jsx(E,{value:v.shippingAddress||"",onChange:p=>k({...v,shippingAddress:p.target.value}),className:"h-8 text-sm"})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"City"}),e.jsx(E,{value:v.shippingCity||"",onChange:p=>k({...v,shippingCity:p.target.value}),className:"h-8 text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"State"}),e.jsx(E,{value:v.shippingState||"",onChange:p=>k({...v,shippingState:p.target.value}),className:"h-8 text-sm"})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Zip"}),e.jsx(E,{value:v.shippingPostcode||"",onChange:p=>k({...v,shippingPostcode:p.target.value}),className:"h-8 text-sm"})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Country"}),e.jsx(E,{value:v.shippingCountry||"US",onChange:p=>k({...v,shippingCountry:p.target.value}),className:"h-8 text-sm"})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(C,{variant:"outline",size:"sm",onClick:()=>j(null),children:"Cancel"}),e.jsx(C,{size:"sm",onClick:()=>{const{id:p,createdAt:V,updatedAt:me,...pe}=v;l.mutate({id:y,data:pe})},disabled:l.isPending,className:"bg-green-600 hover:bg-green-700 text-white",children:l.isPending?"Saving...":"Save Changes"})]})]})]})}),e.jsx(Ie,{open:F,onOpenChange:L,children:e.jsxs(De,{className:"max-w-2xl",children:[e.jsx(Oe,{children:e.jsx(Te,{children:"Create New Subscription"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"First Name *"}),e.jsx(E,{value:c.customerFirstName,onChange:p=>f({...c,customerFirstName:p.target.value}),className:"h-8 text-sm"})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Last Name *"}),e.jsx(E,{value:c.customerLastName,onChange:p=>f({...c,customerLastName:p.target.value}),className:"h-8 text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Email *"}),e.jsx(E,{value:c.customerEmail,onChange:p=>f({...c,customerEmail:p.target.value}),className:"h-8 text-sm"})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Phone"}),e.jsx(E,{value:c.customerPhone,onChange:p=>f({...c,customerPhone:p.target.value}),className:"h-8 text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Frequency"}),e.jsxs(Ne,{value:c.frequency,onValueChange:p=>f({...c,frequency:p}),children:[e.jsx(we,{className:"h-8 text-sm",children:e.jsx(Ce,{})}),e.jsx(Se,{children:(N||[]).filter(p=>p.isActive).map(p=>e.jsx(Z,{value:p.value,children:p.label},p.id))})]})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Order Total"}),e.jsx(E,{type:"number",step:"0.01",value:c.orderTotal,onChange:p=>f({...c,orderTotal:p.target.value}),className:"h-8 text-sm",placeholder:"Auto-calculated"})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Status"}),e.jsxs(Ne,{value:c.status,onValueChange:p=>f({...c,status:p}),children:[e.jsx(we,{className:"h-8 text-sm",children:e.jsx(Ce,{})}),e.jsxs(Se,{children:[e.jsx(Z,{value:"active",children:"Active"}),e.jsx(Z,{value:"paused",children:"Paused"})]})]})]})]}),e.jsxs("div",{className:"border-t pt-3",children:[e.jsx(S,{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Subscription Items"}),e.jsxs("div",{className:"space-y-2 mt-2",children:[P.map((p,V)=>e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50 rounded border px-3 py-2",children:[e.jsx("span",{className:"text-sm text-gray-700 flex-1",children:p.name}),e.jsx(E,{type:"number",min:1,value:p.quantity,onChange:me=>{const pe=[...P];pe[V]={...pe[V],quantity:Math.max(1,parseInt(me.target.value)||1)},D(pe)},className:"h-7 w-16 text-sm"}),e.jsxs("span",{className:"text-sm text-gray-600",children:["$",p.price]}),e.jsx(C,{variant:"ghost",size:"sm",onClick:()=>D(P.filter((me,pe)=>pe!==V)),className:"h-7 w-7 p-0",children:e.jsx(Ve,{className:"h-3.5 w-3.5 text-red-500"})})]},V)),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ne,{value:b,onValueChange:O,children:[e.jsx(we,{className:"h-8 text-sm flex-1",children:e.jsx(Ce,{placeholder:"Add a product..."})}),e.jsx(Se,{children:(xe||[]).filter(p=>p.isActive).map(p=>e.jsxs(Z,{value:p.id.toString(),children:[p.name," â $",p.price]},p.id))})]}),e.jsx(C,{size:"sm",variant:"outline",onClick:()=>
112{if(!b)return;const p=(xe||[]).find(V=>V.id===parseInt(b));p&&(D([...P,{productId:p.id,name:p.name,price:p.price,quantity:1}]),O(""))},disabled:!b,className:"h-8",children:e.jsx(Be,{className:"h-3.5 w-3.5"})})]}),P.length>0&&e.jsxs("p",{className:"text-xs text-gray-500",children:["Subtotal: $",P.reduce((p,V)=>p+parseFloat(V.price)*V.quantity,0).toFixed(2)]})]})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs",children:"Notes"}),e.jsx(E,{value:c.notes,onChange:p=>f({...c,notes:p.target.value}),className:"h-8 text-sm",placeholder:"Optional notes..."})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(C,{variant:"outline",size:"sm",onClick:()=>{L(!1),D([]),O("")},children:"Cancel"}),e.jsx(C,{size:"sm",onClick:()=>{const p=new Date;p.setMonth(p.getMonth()+1);const V=P.reduce((me,pe)=>me+parseFloat(pe.price)*pe.quantity,0);se.mutate({...c,orderTotal:c.orderTotal||V.toFixed(2)||"0.00",nextPaymentDate:p,items:P})},disabled:se.isPending||!c.customerEmail||!c.customerFirstName||!c.customerLastName,className:"bg-amber-600 hover:bg-amber-700 text-white",children:se.isPending?"Creating...":"Create Subscription"})]})]})]})}),e.jsx(Ie,{open:!!te,onOpenChange:p=>{p||A(null)},children:e.jsxs(De,{className:"max-w-md",children:[e.jsx(Oe,{children:e.jsxs(Te,{className:"flex items-center gap-2 text-amber-700",children:[e.jsx(Kt,{className:"h-5 w-5"})," Renew Subscription"]})}),te&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-amber-50 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-amber-800 mb-2",children:"Warning: This will charge the customer's card immediately."}),e.jsx("p",{className:"text-xs text-amber-700",children:"Make sure the customer has agreed to this renewal before proceeding."})]}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-500",children:"Customer"}),e.jsxs("span",{className:"font-medium text-gray-900",children:[te.customerFirstName," ",te.customerLastName]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-500",children:"Email"}),e.jsx("span",{className:"text-gray-700",children:te.customerEmail})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-500",children:"Items"}),e.jsx("span",{className:"text-gray-700",children:Array.isArray(te.items)?te.items.map(p=>`${p.name} x${p.quantity}`).join(", "):"N/A"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-500",children:"Stripe Customer"}),e.jsx("span",{className:"text-xs font-mono text-gray-600",children:te.stripeCustomerId||"Not linked"})]}),e.jsxs("div",{className:"border-t pt-3 flex justify-between",children:[e.jsx("span",{className:"font-semibold text-gray-900",children:"Amount to charge"}),e.jsxs("span",{className:"text-xl font-bold text-green-700",children:["$",ge]})]})]}),!te.stripeCustomerId&&e.jsx("div",{className:"rounded-lg border border-red-200 bg-red-50 p-3",children:e.jsx("p",{className:"text-xs text-red-700 font-medium",children:"This customer has no Stripe account linked. The charge cannot be processed."})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(C,{variant:"outline",size:"sm",onClick:()=>A(null),disabled:$,children:"Cancel"}),e.jsx(C,{size:"sm",onClick:oe,disabled:$||!te.stripeCustomerId||ne<=0,className:"bg-green-600 hover:bg-green-700 text-white",children:$?"Processing...":`Charge $${ge}`})]})]})]})}),e.jsx(Ie,{open:!!_,onOpenChange:p=>{p||R(null)},children:e.jsxs(De,{className:"max-w-sm",children:[e.jsx(Oe,{children:e.jsxs(Te,{className:"capitalize",children:[_==null?void 0:_.type," Subscription?"]})}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Are you sure you want to ",e.jsx("span",{className:"font-semibold",children:_==null?void 0:_.type})," the subscription for ",e.jsx("span",{className:"font-semibold",children:_==null?void 0:_.subName}),"?"]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(C,{variant:"outline",size:"sm",onClick:()=>R(null),children:"No, Go Back"}),e.jsxs(C,{size:"sm",onClick:ue,className:(_==null?void 0:_.type)==="cancel"?"bg-red-600 hover:bg-red-700 text-white":(_==null?void 0:_.type)==="reactivate"?"bg-green-600 hover:bg-green-700 text-white":"bg-amber-600 hover:bg-amber-700 text-white",children:["Yes, ",(_==null?void 0:_.type)==="cancel"?"Cancel It":(_==null?void 0:_.type)==="reactivate"?"Reactivate":(_==null?void 0:_.type)==="pause"?"Pause It":"Resume It"]})]})]})}),e.jsx(eo,{})]})}function eo(){const{toast:t}=Ee(),[a,s]=i.useState(null),[n,r]=i.useState({label:"",value:"",discountPercent:0,sortOrder:0,isActive:!0}),[o,x]=i.useState(!1),[m,h]=i.useState({label:"",value:"",discountPercent:0,sortOrder:0,isActive:!0}),u=["/api/subscription-frequencies"],{data:w,isLoading:y}=he({queryKey:u}),j=ee({mutationFn:F=>ae("/api/subscription-frequencies","POST",F),onSuccess:()=>{X.invalidateQueries({queryKey:u}),x(!1),h({label:"",value:"",discountPercent:0,sortOrder:0,isActive:!0}),t({title:"Frequency option added"})},onError:()=>t({title:"Failed to add",variant:"destructive"})}),v=ee({mutationFn:({id:F,data:L})=>ae(`/api/subscription-frequencies/${F}`,"PATCH",L),onSuccess:()=>{X.invalidateQueries({queryKey:u}),s(null),t({title:"Frequency updated"})},onError:()=>t({title:"Failed to update",variant:"destructive"})}),k=ee({mutationFn:F=>ae(`/api/subscription-frequencies/${F}`,"DELETE"),onSuccess:()=>{X.invalidateQueries({queryKey:u}),t({title:"Frequency deleted"})},onError:()=>t({title:"Failed to delete",variant:"destructive"})});return e.jsxs(G,{className:"border border-gray-200 shadow-sm",children:[e.jsx(je,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Pe,{className:"text-lg",children:"Subscription Frequency Options"}),e.jsx(yt,{children:"Set the delivery frequencies and discount percentages shown to customers"})]}),!o&&e.jsxs(C,{size:"sm",onClick:()=>x(!0),className:"bg-amber-600 hover:bg-amber-700 text-white",children:[e.jsx(Be,{className:"h-4 w-4 mr-1"})," Add Option"]})]})}),e.jsx(Q,{className:"p-0",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{className:"bg-gray-50 border-y",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-2",children:"Label"}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-2",children:"Value (key
112)"}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-2",children:"Discount %"}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-2",children:"Sort"}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-2",children:"Active"}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 uppercase px-4 py-2",children:"Actions"})]})}),e.jsxs("tbody",{children:[o&&e.jsxs("tr",{className:"border-b bg-amber-50/40",children:[e.jsx("td",{className:"px-4 py-2",children:e.jsx(E,{value:m.label,onChange:F=>h({...m,label:F.target.value}),placeholder:"Every 2 weeks",className:"h-8 text-sm"})}),e.jsx("td",{className:"px-4 py-2",children:e.jsx(E,{value:m.value,onChange:F=>h({...m,value:F.target.value}),placeholder:"every_2_weeks",className:"h-8 text-sm"})}),e.jsx("td",{className:"px-4 py-2",children:e.jsx(E,{type:"number",value:m.discountPercent,onChange:F=>h({...m,discountPercent:parseInt(F.target.value)||0}),className:"h-8 text-sm w-20"})}),e.jsx("td",{className:"px-4 py-2",children:e.jsx(E,{type:"number",value:m.sortOrder,onChange:F=>h({...m,sortOrder:parseInt(F.target.value)||0}),className:"h-8 text-sm w-16"})}),e.jsx("td",{className:"px-4 py-2",children:e.jsx("button",{onClick:()=>h({...m,isActive:!m.isActive}),className:`w-8 h-5 rounded-full transition-colors ${m.isActive?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${m.isActive?"translate-x-3.5":"translate-x-0.5"}`})})}),e.jsx("td",{className:"px-4 py-2",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(C,{size:"sm",variant:"ghost",onClick:()=>j.mutate(m),disabled:!m.label||!m.value||j.isPending,className:"h-7 px-2 text-green-600 hover:text-green-700",children:e.jsx(Ke,{className:"h-3.5 w-3.5"})}),e.jsx(C,{size:"sm",variant:"ghost",onClick:()=>x(!1),className:"h-7 px-2 text-gray-500",children:e.jsx(Tt,{className:"h-3.5 w-3.5"})})]})})]}),y?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-6 text-center text-sm text-gray-400",children:"Loading..."})}):!(w!=null&&w.length)&&!o?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-6 text-center text-sm text-gray-400",children:"No frequency options configured"})}):(w||[]).map(F=>e.jsx("tr",{className:"border-b hover:bg-gray-50/50",children:a===F.id?e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-4 py-2",children:e.jsx(E,{value:n.label,onChange:L=>r({...n,label:L.target.value}),className:"h-8 text-sm"})}),e.jsx("td",{className:"px-4 py-2",children:e.jsx(E,{value:n.value,onChange:L=>r({...n,value:L.target.value}),className:"h-8 text-sm"})}),e.jsx("td",{className:"px-4 py-2",children:e.jsx(E,{type:"number",value:n.discountPercent,onChange:L=>r({...n,discountPercent:parseInt(L.target.value)||0}),className:"h-8 text-sm w-20"})}),e.jsx("td",{className:"px-4 py-2",children:e.jsx(E,{type:"number",value:n.sortOrder,onChange:L=>r({...n,sortOrder:parseInt(L.target.value)||0}),className:"h-8 text-sm w-16"})}),e.jsx("td",{className:"px-4 py-2",children:e.jsx("button",{onClick:()=>r({...n,isActive:!n.isActive}),className:`w-8 h-5 rounded-full transition-colors ${n.isActive?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${n.isActive?"translate-x-3.5":"translate-x-0.5"}`})})}),e.jsx("td",{className:"px-4 py-2",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(C,{size:"sm",variant:"ghost",onClick:()=>v.mutate({id:F.id,data:n}),disabled:v.isPending,className:"h-7 px-2 text-green-600",children:e.jsx(Ke,{className:"h-3.5 w-3.5"})}),e.jsx(C,{size:"sm",variant:"ghost",onClick:()=>s(null),className:"h-7 px-2 text-gray-500",children:e.jsx(Tt,{className:"h-3.5 w-3.5"})})]})})]}):e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-4 py-2 text-sm font-medium",children:F.label}),e.jsx("td",{className:"px-4 py-2 text-sm text-gray-500 font-mono",children:F.value}),e.jsx("td",{className:"px-4 py-2 text-sm",children:e.jsxs(H,{variant:"outline",className:"border-green-200 bg-green-50 text-green-700",children:[F.discountPercent,"% off"]})}),e.jsx("td",{className:"px-4 py-2 text-sm text-gray-500",children:F.sortOrder}),e.jsx("td",{className:"px-4 py-2",children:e.jsx(H,{variant:"outline",className:F.isActive?"border-green-200 bg-green-50 text-green-700":"border-gray-200 bg-gray-50 text-gray-500",children:F.isActive?"Active":"Inactive"})}),e.jsx("td",{className:"px-4 py-2",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(C,{size:"sm",variant:"ghost",onClick:()=>{s(F.id),r({label:F.label,value:F.value,discountPercent:F.discountPercent,sortOrder:F.sortOrder??0,isActive:F.isActive})},className:"h-7 px-2 text-blue-600",children:e.jsx(ze,{className:"h-3.5 w-3.5"})}),e.jsx(C,{size:"sm",variant:"ghost",onClick:()=>k.mutate(F.id),disabled:k.isPending,className:"h-7 px-2 text-red-500",children:e.jsx(Ve,{className:"h-3.5 w-3.5"})})]})})]})},F.id))]})]})})]})}function to({sub:t,isExpanded:a,onToggle:s,getStatusBadge:n,getFrequencyLabel:r,formatNextRenewal:o,onPause:x,onResume:m,onCancel:h,onReactivate:u,onChargeNow:w,onSendRenewalReminder:y,onEdit:j,onUpdateItems:v,onSetNextDate:k,isUpdatingDate:F,products:L,allOrders:c,isActionPending:f}){const{toast:P}=Ee(),[D,b]=i.useState(!1),[O,g]=i.useState([]),[B,ie]=i.useState(""),[xe,fe]=i.useState(!1),[d,q]=i.useState(!1),[z,T]=i.useState(!1),[M,U]=i.useState(""),{data:_=[],isLoading:R}=he({queryKey:["/api/subscriptions",t.id,"audits"],enabled:a&&d}),ue=()=>{const I=t.nextPaymentDate?new Date(t.nextPaymentDate).toISOString().split("T")[0]:"";U(I),T(!0)},te=()=>{k(M||null),T(!1)},A=t.matchedUserId,[$,Y]=i.useState(!1),K=async()=>
112{if(A){Y(!0);try{const I=await fetch(`/api/users/${A}/send-payment-update-email`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({testToAdmins:!1})}),le=await I.json().catch(()=>({}));if(!I.ok)throw new Error(le.error||"Failed to send");P({title:"Billing update email sent",description:le.message||`Sent to ${t.customerEmail}`})}catch(I){P({title:"Send failed",description:I.message,variant:"destructive"})}finally{Y(!1)}}},re=()=>{g(Array.isArray(t.items)?[...t.items]:[]),b(!0)},ne=()=>{if(!B)return;const I=L.find(le=>le.id===parseInt(B));I&&(g([...O,{productId:I.id,name:I.name,price:I.price,quantity:1}]),ie(""))},ge=I=>{g(O.filter((le,ve)=>ve!==I))},oe=(I,le)=>{const ve=[...O];ve[I]={...ve[I],quantity:Math.max(1,le)},g(ve)},l=Array.isArray(t.items)?t.items:[],W=l.reduce((I,le)=>I+parseFloat(le.price||0)*(le.quantity||1),0),se=parseFloat(t.orderTotal||"0")>0?parseFloat(t.orderTotal).toFixed(2):W>0?W.toFixed(2):"0.00",de=c.filter(I=>I.subscriptionId===t.id).sort((I,le)=>new Date(le.dateCreated||0).getTime()-new Date(I.dateCreated||0).getTime()),Me=de.length>0?de:c.filter(I=>{var le,ve;return((le=I.customerEmail)==null?void 0:le.toLowerCase())===((ve=t.customerEmail)==null?void 0:ve.toLowerCase())}).sort((I,le)=>new Date(le.dateCreated||0).getTime()-new Date(I.dateCreated||0).getTime()),ct=async()=>{try{const I=await fetch("/api/admin/view-customer-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({customerEmail:t.customerEmail})});if(!I.ok)throw new Error("Failed to generate token");const{token:le}=await I.json();window.open(`/my-account?admin_view=${le}`,"_blank")}catch{P({title:"Failed to open customer dashboard",variant:"destructive"})}};return e.jsxs(e.Fragment,{children:[e.jsxs("tr",{className:`border-b hover:bg-gray-50 transition-colors cursor-pointer ${a?"bg-gray-50":""}`,onClick:s,children:[e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"w-8 h-8 rounded-full bg-amber-100 flex items-center justify-center text-xs font-medium text-amber-700",children:[t.customerFirstName[0],t.customerLastName[0]]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-medium text-gray-900",children:[t.customerFirstName," ",t.customerLastName]}),e.jsx("p",{className:"text-xs text-gray-500",children:t.customerEmail}),t.matchedUserId&&e.jsxs("p",{className:"text-xs text-gray-400",children:["Customer #",t.matchedUserId]})]})]})}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{children:[e.jsx("span",{className:"text-sm font-semibold text-amber-700",children:r(t.frequency)}),l.length>0&&e.jsxs("p",{className:"text-xs text-gray-500",children:[l.length," item",l.length!==1?"s":""]})]})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(H,{variant:"outline",className:`text-xs capitalize ${n(t.status)}`,children:t.status})}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("span",{className:"text-sm font-semibold text-gray-900",children:["$",se]})}),e.jsx("td",{className:"px-4 py-3",onClick:I=>I.stopPropagation(),children:z?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(E,{type:"date",value:M,onChange:I=>U(I.target.value),className:"h-8 text-xs w-[140px]",disabled:F,"data-testid":`input-next-renewal-${t.id}`}),e.jsx(C,{size:"sm",variant:"ghost",className:"h-7 px-2 text-green-600",onClick:te,disabled:F,title:"Save","data-testid":`button-save-next-renewal-${t.id}`,children:e.jsx(Ke,{className:"h-3.5 w-3.5"})}),e.jsx(C,{size:"sm",variant:"ghost",className:"h-7 px-2 text-gray-500",onClick:()=>T(!1),disabled:F,title:"Cancel","data-testid":`button-cancel-next-renewal-${t.id}`,children:e.jsx(St,{className:"h-3.5 w-3.5"})})]}):e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("p",{className:`text-sm font-medium ${t.nextPaymentDate?"text-gray-900":"text-amber-600 italic"}`,children:o(t.nextPaymentDate)}),e.jsx(C,{size:"sm",variant:"ghost",className:"h-7 px-2 text-blue-600",onClick:ue,title:"Set next renewal date","data-testid":`button-edit-next-renewal-${t.id}`,children:e.jsx(ze,{className:"h-3.5 w-3.5"})})]})}),e.jsx("td",{className:"px-4 py-3",onClick:I=>I.stopPropagation(),children:e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[t.status==="active"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:x,disabled:f,title:"Pause this subscription",className:"inline-flex items-center gap-1 h-7 px-2.5 rounded-full border border-amber-300 text-amber-700 bg-amber-50/50 hover:bg-amber-100 text-xs font-medium transition-colors disabled:opacity-50 whitespace-nowrap",children:[e.jsx(Jn,{className:"h-3 w-3"})," Pause"]}),e.jsxs("button",{onClick:w,disabled:f,title:"Charge the renewal now",className:"inline-flex items-center gap-1 h-7 px-2.5 rounded-full border border-green-300 text-green-700 bg-green-50/50 hover:bg-green-100 text-xs font-medium transition-colors disabled:opacity-50 whitespace-nowrap",children:[e.jsx(Kt,{className:"h-3 w-3"})," Charge"]})]}),t.status==="paused"&&e.jsxs("button",{onClick:m,disabled:f,title:"Resume this subscription",className:"inline-flex items-center gap-1 h-7 px-2.5 rounded-full border border-green-300 text-green-700 bg-green-50/50 hover:bg-green-100 text-xs font-medium transition-colors disabled:opacity-50 whitespace-nowrap",children:[e.jsx(is,{className:"h-3 w-3"})," Resume"]}),t.status==="cancelled"&&e.jsxs("button",{onClick:u,disabled:f,title:"Reactivate this subscription",className:"inline-flex items-center gap-1 h-7 px-2.5 rounded-full border border-green-300 text-green-700 bg-green-50/50 hover:bg-green-100 text-xs font-medium transition-colors disabled:opacity-50 whitespace-nowrap",children:[e.jsx(is,{className:"h-3 w-3"})," Reactivate"]}),e.jsxs("button",{onClick:j,title:"Edit subscription details",className:"inline-flex items-center gap-1 h-7 px-2.5 rounded-full border border-gray-300 text-gray-600 bg-gray-50/50 hover:bg-gray-100 text-xs font-medium transition-colors whitespace-nowrap",children:[e.jsx(ze,{className:"h-3 w-3"})," Edit"]})]})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(Ge,{className:`w-4 h-4 text-gray-400 transition-transform ${a?"rotate-90":""}`})})]}),a&&e.jsx("tr",{className:"bg-white border-b",onClick:I=>I.stopPropagation(),children:e.jsx("td",{colSpan:7,className:"p-0",children:e.jsx("div",{className:"border-t border-gray-200",onClick:I=>I.stopPropagation(),children:e.jsxs("div",{className:"px-6 py-5",children:[e.jsxs("h3",{className:"text-lg font-semibold text-gray-800 mb
112-4",children:["Subscription #",t.id," details"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-6 pb-5 border-b border-gray-200",children:[e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center justify-between mb-3",children:e.jsx("h4",{className:"text-sm font-bold text-gray-700",children:"General"})}),e.jsxs("div",{className:"space-y-2 text-sm text-gray-600",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Customer:"}),e.jsxs("p",{className:"font-medium text-gray-800",children:[t.customerFirstName," ",t.customerLastName," (",t.customerEmail,")",t.matchedUserId&&e.jsxs("span",{className:"ml-2 text-xs text-gray-400 font-normal",children:["ID #",t.matchedUserId]})]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Subscription status:"}),e.jsx("div",{className:"mt-1",children:e.jsx(H,{variant:"outline",className:`text-xs capitalize ${n(t.status)}`,children:t.status})})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Frequency:"}),e.jsx("p",{className:"font-medium text-amber-700",children:r(t.frequency)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Started:"}),e.jsx("p",{children:t.startDate?new Date(t.startDate).toLocaleDateString("en-US",{month:"long",day:"numeric",year:"numeric"}):"N/A"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Next renewal:"}),e.jsx("p",{className:"font-medium",children:o(t.nextPaymentDate)})]}),t.stripeSubscriptionId&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Stripe ID:"}),e.jsx("p",{className:"text-xs font-mono",children:t.stripeSubscriptionId})]}),t.wooCommerceId&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"WooCommerce:"}),e.jsxs("p",{children:["#",t.wooCommerceId]})]})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h4",{className:"text-sm font-bold text-gray-700",children:"Billing"}),e.jsx("button",{onClick:I=>{I.stopPropagation(),j()},className:"text-gray-400 hover:text-gray-600",children:e.jsx(ze,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"space-y-1 text-sm text-gray-600",children:[(t.billingAddress||t.shippingAddress)&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-gray-500",children:"Address:"}),e.jsxs("p",{children:[t.customerFirstName," ",t.customerLastName]}),e.jsx("p",{children:t.billingAddress||t.shippingAddress}),e.jsx("p",{children:[t.billingCity||t.shippingCity,t.billingState||t.shippingState,t.billingPostcode||t.shippingPostcode].filter(Boolean).join(", ")})]}),e.jsxs("div",{className:"pt-2",children:[e.jsx("span",{className:"text-gray-500",children:"Email address:"}),e.jsx("p",{className:"text-blue-600",children:t.customerEmail})]}),t.customerPhone&&e.jsxs("div",{className:"pt-1",children:[e.jsx("span",{className:"text-gray-500",children:"Phone:"}),e.jsx("p",{children:t.customerPhone})]}),e.jsxs("div",{className:"pt-1",children:[e.jsx("span",{className:"text-gray-500",children:"Payment Method:"}),e.jsxs("p",{className:"flex items-center gap-1",children:[e.jsx(ls,{className:"w-3.5 h-3.5 text-gray-400"}),t.paymentMethod||"Credit/Debit Card"]})]})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h4",{className:"text-sm font-bold text-gray-700",children:"Shipping"}),e.jsx("button",{onClick:I=>{I.stopPropagation(),j()},className:"text-gray-400 hover:text-gray-600",children:e.jsx(ze,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"space-y-1 text-sm text-gray-600",children:[e.jsx("p",{className:"text-gray-500",children:"Address:"}),e.jsxs("p",{children:[t.customerFirstName," ",t.customerLastName]}),t.shippingAddress&&e.jsx("p",{children:t.shippingAddress}),e.jsx("p",{children:[t.shippingCity,t.shippingState,t.shippingPostcode].filter(Boolean).join(", ")}),t.customerPhone&&e.jsxs("div",{className:"pt-2",children:[e.jsx("span",{className:"text-gray-500",children:"Phone:"}),e.jsx("p",{children:t.customerPhone})]})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center justify-between mb-3",children:e.jsx("h4",{className:"text-sm font-bold text-gray-700",children:"Actions"})}),e.jsxs("div",{className:"flex flex-col items-start gap-2",children:[t.status==="active"&&e.jsxs("button",{onClick:y,disabled:f,title:"Send renewal reminder email (no charge)",className:"inline-flex items-center gap-1 h-7 px-2.5 rounded-full border border-blue-300 text-blue-700 bg-blue-50/50 hover:bg-blue-100 text-xs font-medium transition-colors disabled:opacity-50 whitespace-nowrap",children:[e.jsx(xt,{className:"h-3 w-3"})," Remind"]}),e.jsxs("button",{onClick:K,disabled:$||!A,title:A?"Email this customer to update payment info (keeps legacy pricing)":"No customer account for this email â add one in the Customers tab first",className:"inline-flex items-center gap-1 h-7 px-2.5 rounded-full border border-emerald-300 text-emerald-700 bg-emerald-50/50 hover:bg-emerald-100 text-xs font-medium transition-colors disabled:opacity-50 whitespace-nowrap",children:[e.jsx(ls,{className:"h-3 w-3"})," ",$?"Sendingâ¦":"Billing Email"]}),e.jsxs("button",{onClick:ct,title:"Open this customer's dashboard (read-only)",className:"inline-flex items-center gap-1 h-7 px-2.5 rounded-full border border-blue-300 text-blue-600 bg-blue-50/50 hover:bg-blue-100 text-xs font-medium transition-colors whitespace-nowrap",children:[e.jsx(ht,{className:"h-3 w-3"})," View"]}
112),t.status!=="cancelled"&&e.jsxs("button",{onClick:h,disabled:f,title:"Cancel this subscription",className:"inline-flex items-center gap-1 h-7 px-2.5 rounded-full border border-red-300 text-red-600 bg-red-50/50 hover:bg-red-100 text-xs font-medium transition-colors disabled:opacity-50 whitespace-nowrap",children:[e.jsx(Tt,{className:"h-3 w-3"})," Cancel"]})]})]})]}),t.notes&&e.jsx("div",{className:"py-3 border-b border-gray-200",children:e.jsxs("p",{className:"text-xs text-gray-500 italic",children:["Note: ",t.notes]})}),e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("div",{}),D?e.jsxs("div",{className:"flex gap-1",children:[e.jsx(C,{variant:"outline",size:"sm",onClick:()=>b(!1),className:"h-7 text-xs",children:"Cancel"}),e.jsxs(C,{size:"sm",onClick:()=>{v(O),b(!1)},className:"h-7 text-xs bg-green-600 hover:bg-green-700 text-white",children:[e.jsx(Ke,{className:"h-3 w-3 mr-1"})," Save Items"]})]}):e.jsxs(C,{variant:"outline",size:"sm",onClick:re,className:"h-7 text-xs",children:[e.jsx(ze,{className:"h-3 w-3 mr-1"})," Edit Items"]})]}),D?e.jsxs("div",{className:"space-y-2",children:[O.map((I,le)=>e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50 rounded border px-3 py-2",children:[e.jsx("span",{className:"text-sm text-gray-700 flex-1",children:I.name||`Product #${I.productId}`}),e.jsx(E,{type:"number",min:1,value:I.quantity,onChange:ve=>oe(le,parseInt(ve.target.value)||1),className:"h-7 w-16 text-sm"}),e.jsxs("span",{className:"text-sm text-gray-600",children:["$",I.price]}),e.jsx(C,{variant:"ghost",size:"sm",onClick:()=>ge(le),className:"h-7 w-7 p-0",children:e.jsx(Ve,{className:"h-3.5 w-3.5 text-red-500"})})]},le)),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ne,{value:B,onValueChange:ie,children:[e.jsx(we,{className:"h-8 text-sm flex-1",children:e.jsx(Ce,{placeholder:"Add a product..."})}),e.jsx(Se,{children:L.filter(I=>I.isActive).map(I=>e.jsxs(Z,{value:I.id.toString(),children:[I.name," â $",I.price]},I.id))})]}),e.jsx(C,{size:"sm",variant:"outline",onClick:ne,disabled:!B,className:"h-8",children:e.jsx(Be,{className:"h-3.5 w-3.5"})})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-200",children:[e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 py-2 pl-1",children:"Item"}),e.jsx("th",{className:"text-right text-xs font-medium text-gray-500 py-2",children:"Price"}),e.jsx("th",{className:"text-center text-xs font-medium text-gray-500 py-2 w-16",children:"Qty"}),e.jsx("th",{className:"text-right text-xs font-medium text-gray-500 py-2 pr-1",children:"Total"})]})}),e.jsx("tbody",{children:l.length>0?l.map((I,le)=>{const ve=L.find(N=>N.id===(I.productId||I.product_id)||N.name.toLowerCase()===(I.name||"").toLowerCase()),_e=(parseFloat(I.price)*(I.quantity||1)).toFixed(2);return e.jsxs("tr",{className:"border-b border-gray-100",children:[e.jsx("td",{className:"py-3 pl-1",children:e.jsxs("div",{className:"flex items-center gap-3",children:[ve!=null&&ve.featuredImage?e.jsx("img",{src:ve.featuredImage,alt:I.name,className:"w-10 h-10 rounded object-cover border border-gray-200"}):e.jsx("div",{className:"w-10 h-10 rounded bg-amber-50 border border-gray-200 flex items-center justify-center",children:e.jsx(tt,{className:"w-4 h-4 text-amber-400"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-blue-600",children:I.name||`Product #${I.productId}`}),I.sku&&e.jsxs("p",{className:"text-xs text-gray-400",children:["SKU: ",I.sku]}),I.variantTitle&&e.jsx("p",{className:"text-xs text-gray-400",children:I.variantTitle})]})]})}),e.jsxs("td",{className:"text-right text-sm text-gray-700 py-3",children:["$",parseFloat(I.price).toFixed(2)]}),e.jsxs("td",{className:"text-center text-sm text-gray-500 py-3",children:["à ",I.quantity||1]}),e.jsxs("td",{className:"text-right text-sm font-medium text-gray-900 py-3 pr-1",children:["$",_e]})]},le)}):e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"py-4 text-center text-xs text-gray-400",children:"No items in this subscription yet."})})})]}),l.length>0&&e.jsx("div",{className:"flex justify-end mt-3",children:e.jsxs("div",{className:"w-64 space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-500",children:"Items Subtotal:"}),e.jsxs("span",{className:"font-semibold text-gray-900",children:["$",l.reduce((I,le)=>I+parseFloat(le.price)*(le.quantity||1),0).toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-gray-500",children:"Shipping:"}),e.jsx("span",{className:"text-gray-900",children:"$0.00"})]}),e.jsxs("div",{className:"flex justify-between text-sm pt-1.5 border-t border-gray-200",children:[e.jsx("span",{className:"font-bold text-gray-700",children:"Order Total (Locked):"}),e.jsxs("span",{className:"font-bold text-gray-900",children:["$",se]})]}),t.lockedPrices&&Object.keys(t.lockedPrices).length>0&&e.jsx("div",{className:"text-xs text-amber-700 bg-amber-50 rounded px-2 py-1 mt-1",children:"Grandfathered pricing â active subscribers keep their original rate"})]})})]})]}),e.jsxs("div",{className:"mt-5 border-t border-gray-200 pt-4",children:[e.jsxs("button",{onClick:()=>fe(!xe),className:"flex items-center gap-2 text-sm font-bold text-gray-700 hover:text-gray-900",children:[e.jsx(Ge,{className:`w-4 h-4 transition-transform ${xe?"rotate-90":""}`}),de.length>0?`Subscription Orders (${de.length})`:`Customer Orders (${Me.length})`]}),xe&&e.jsx("div",{className:"mt-3",children:Me.length>0?e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-200",children:[e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 py-2 pl-1",children:"Order"}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 py-2",children:"Date"}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 py-2",children:"Status"}),e.jsx("th",{className:"text-left text-xs font-medium text-gray-500 py-2",children:"Items"}),e.jsx("th",{className:"text-right text-xs font-medium text-gray-500 py-2 pr-1",children:"Total"})]})}),e.jsx("tbody",{children:Me.slice(0,20).map(I=>{const le=Array.isArray(I.lineItems)?I.lineItems:[],ve={completed:"bg-green-50 text-green-700 border-green-200",shipped:"bg-emerald-50 text-emerald-700 border-emerald-200",processing:"bg-amber-50 text-amber-700 border-amber-200",failed:"bg-red-50 text-red-700 border-red-200"};return e.jsxs("tr",{className:"border-b border-gray-100 hover:bg-gray-50",children:[e.jsxs("td",{className:"py-2 pl-1 text-sm font-medium text-blue-600",children:["#",I.orderNumber||I.id]}),e.jsx("td",{className:"py-2 text-sm text-gray-600",children:I.dateCreated?new Date(I.dateCreated).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"â"}),e.jsx("td",{className:"py-2",children:e.jsx(H,{variant:"outline",className:`text-xs capitalize ${ve[I.status]||"bg-gray-50 text-gray-600 border-gray-200"}`,children:I.status})}),e.jsx("td",{className:"py-2 text-xs text-gray-500 max-w-[200px] truncate",children:le.map(_e=>`${_e.name} Ã${_e.quantity}`).join(", ")||"â"}),e.jsxs("td",{className:"py-2 pr-1 text-sm font-semibold text-gray-900 text-right",children:["$",parseFloat(I.total||"0").toFixed(2)]})]},I.id)})})]}):e.jsx("p",{className:"text-xs text-gray-400 py-3 text-center",children:"No orders found for this customer."})})]}),e.jsxs("div",{className:"mt-5 border-t border-gray-200 pt-4",children:[e.jsxs("button",{onClick:()=>q(!d),className:"flex items-center gap-2 text-sm font-bold text-gray-700 hover:text-gray-900","data-testid":`button-toggle-history-${t.id}`,children:[e.jsx(Ge,{className:`w-4 h-4 transition-transform ${d?"rotate-90":""}`}),"History ",_.length>0?`(${_.length})`:""]}),d&&e.jsx("div",{className:"mt-3",children:R?e.jsx("p",{className:"text-xs text-gray-400 py-3 text-center",children:"Loading historyâ¦"}):_.length===0?e.jsx("p",{className:"text-xs text-gray-400 py-3 text-center",children:"No history recorded yet. New mutations will appear here."}):e.jsx("div",{className:"space-y-2",children:_.map(I=>{const le=Array.isArray(I.beforeItems)?I.beforeItems:typeof I.beforeItems=="string"?JSON.parse(I.beforeItems):[],ve=Array.isArray(I.afterItems)?I.afterItems:typeof I.afterItems=="string"?JSON.parse(I.afterItems):[],_e=JSON.stringify(le)!==JSON.stringify(ve),N=I.beforeTotal!==I.afterTotal&&I.beforeTotal!=null&&I.afterTotal!=null,J=I.beforeStatus!==I.afterStatus&&I.beforeStatus!=null,ce={admin:"bg-blue-50 text-blue-700 border-blue-200",customer:"bg-green-50 text-green-700 border-green-200",webhook:"bg-purple-50 text-purple-700 border-purple-200",system:"bg-gray-50 text-gray-700 border-gray-200"},p=V=>V.length===0?"â":V.map(me=>`${me.quantity||1}à ${me.name}`).join(", ");return e.jsxs("div",{className:"border border-gray-200 rounded-md p-3 bg-white text-xs","data-testid":`audit-row-${I.id}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-gray-900",children:I.action}),e.jsx(H,{variant:"outline",className:`text-[10px] capitalize ${ce[I.source]||ce.system}`,children:I.source}),I.actorEmail&&e.jsxs("span",{className:"text-gray-500",children:["by ",I.actorEmail]})]}),e.jsx("span",{className:"text-gray-400 whitespace-nowrap",children:new Date(I.createdAt).toLocaleStr
112ing("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})})]}),(_e||N||J)&&e.jsxs("div",{className:"space-y-1 text-gray-700",children:[_e&&e.jsxs("div",{className:"grid grid-cols-[60px_1fr] gap-2",children:[e.jsx("span",{className:"text-gray-400 font-medium",children:"Items:"}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-red-700",children:[e.jsx("span",{className:"text-gray-400",children:"â"})," ",p(le)]}),e.jsxs("div",{className:"text-green-700",children:[e.jsx("span",{className:"text-gray-400",children:"+"})," ",p(ve)]})]})]}),N&&e.jsxs("div",{className:"grid grid-cols-[60px_1fr] gap-2",children:[e.jsx("span",{className:"text-gray-400 font-medium",children:"Total:"}),e.jsxs("span",{children:["$",I.beforeTotal," â ",e.jsxs("strong",{children:["$",I.afterTotal]})]})]}),J&&e.jsxs("div",{className:"grid grid-cols-[60px_1fr] gap-2",children:[e.jsx("span",{className:"text-gray-400 font-medium",children:"Status:"}),e.jsxs("span",{children:[I.beforeStatus," â ",e.jsx("strong",{children:I.afterStatus})]})]})]}),I.notes&&e.jsx("div",{className:"mt-1 text-gray-500 italic",children:I.notes})]},I.id)})})})]})]})})})})]})}function so(){const{toast:t}=Ee(),[a,s]=i.useState(!1),[n,r]=i.useState(null),[o,x]=i.useState({name:"",sizeLabel:"",itemCount:3,bundlePrice:"",compareAtPrice:"",description:"",imageUrl:"",isActive:!0,sortOrder:0,allowDuplicates:!0,maxPerItem:"",productIds:[]}),{data:m,isLoading:h}=he({queryKey:["/api/bundle-configs"]}),{data:u}=he({queryKey:["/api/products"]}),w=ee({mutationFn:c=>ae("/api/bundle-configs","POST",c),onSuccess:()=>{X.invalidateQueries({queryKey:["/api/bundle-configs"]}),t({title:"Bundle config created"}),v()},onError:c=>{t({title:"Error",description:c.message,variant:"destructive"})}}),y=ee({mutationFn:({id:c,data:f})=>ae(`/api/bundle-configs/${c}`,"PATCH",f),onSuccess:()=>{X.invalidateQueries({queryKey:["/api/bundle-configs"]}),t({title:"Bundle config updated"}),v()},onError:c=>{t({title:"Error",description:c.message,variant:"destructive"})}}),j=ee({mutationFn:c=>ae(`/api/bundle-configs/${c}`,"DELETE"),onSuccess:()=>{X.invalidateQueries({queryKey:["/api/bundle-configs"]}),t({title:"Bundle config deleted"})}}),v=()=>{x({name:"",sizeLabel:"",itemCount:3,bundlePrice:"",compareAtPrice:"",description:"",imageUrl:"",isActive:!0,sortOrder:0,allowDuplicates:!0,maxPerItem:"",productIds:[]}),s(!1),r(null)},k=async c=>{var D,b;const P=await(await fetch(`/api/bundle-configs/${c.id}`)).json();x({name:c.name,sizeLabel:c.sizeLabel,itemCount:c.itemCount,bundlePrice:c.bundlePrice,compareAtPrice:c.compareAtPrice||"",description:c.description||"",imageUrl:c.imageUrl||"",isActive:c.isActive,sortOrder:c.sortOrder||0,allowDuplicates:c.allowDuplicates,maxPerItem:((D=c.maxPerItem)==null?void 0:D.toString())||"",productIds:((b=P.eligibleProducts)==null?void 0:b.map(O=>O.productId))||[]}),r(c.id),s(!0)},F=()=>{const c={name:o.name,sizeLabel:o.sizeLabel,itemCount:o.itemCount,bundlePrice:o.bundlePrice,compareAtPrice:o.compareAtPrice||null,description:o.description||null,imageUrl:o.imageUrl||null,isActive:o.isActive,sortOrder:o.sortOrder,allowDuplicates:o.allowDuplicates,maxPerItem:o.maxPerItem?parseInt(o.maxPerItem):null,productIds:o.productIds};n?y.mutate({id:n,data:c}):w.mutate(c)},L=(u||[]).filter(c=>c.type==="simple"&&c.isActive);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"Bundle Configs"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:'Manage "Build Your Own Bundle" box sizes and pricing'})]}),e.jsxs(C,{onClick:()=>{v(),s(!0)},style:{backgroundColor:"hsl(30, 65%, 45%)",color:"white"},children:[e.jsx(Be,{className:"h-4 w-4 mr-2"}),"New Bundle Config"]})]}),a&&e.jsxs(G,{className:"mb-6 border-amber-200",children:[e.jsx(je,{children:e.jsxs(Pe,{className:"text-lg",children:[n?"Edit":"New"," Bundle Config"]})}),e.jsxs(Q,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{children:"Name"}),e.jsx(E,{value:o.name,onChange:c=>x({...o,name:c.target.value}),placeholder:"3 Bar Bundle"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{children:"Size Label"}),e.jsx(E,{value:o.sizeLabel,onChange:c=>x({...o,sizeLabel:c.target.value}),placeholder:"Pick any 3 bars"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{children:"Item Count"}),e.jsx(E,{type:"number",value:o.itemCount,onChange:c=>x({...o,itemCount:parseInt(c.target.value)||0})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{children:"Bundle Price ($)"}),e.jsx(E,{value:o.bundlePrice,onChange:c=>x({...o,bundlePrice:c.target.value}),placeholder:"25.00"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{children:"Compare At Price ($)"}),e.jsx(E,{value:o.compareAtPrice,onChange:c=>x({...o,compareAtPrice:c.target.value}),placeholder:"29.55"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{children:"Sort Order"}),e.jsx(E,{type:"number",value:o.sortOrder,onChange:c=>x({...o,sortOrder:parseInt(c.target.value)||0})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{children:"Image URL"}),e.jsx(E,{value:o.imageUrl,onChange:c=>x({...o,imageUrl:c.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{children:"Max Per Item (optional)"}),e.jsx(E,{value:o.maxPerItem,onChange:c=>x({...o,maxPerItem:c.target.value}),placeholder:"Leave empty for no limit"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{children:"Description"}),e.jsx(E,{value:o.description,onChange:c=>x({...o,description:c.target.value}),placeholder:"Choose any 3 bars and save!"})]}),e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",checked:o.isActive,onChange:c=>x({...o,isActive:c.target.checked}),className:"rounded"}),"Active"]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",checked:o.allowDuplicates,onChange:c=>x({...o,allowDuplicates:c.target.checked}),className:"rounded"}),"Allow Duplicates"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{children:"Eligible Products (leave empty = all simple products)"}),e.jsx("div",{className:"border rounded-lg p-3 max-h-48 overflow-y-auto space-y-1",children:L.map(c=>e.jsxs("label",{className:"flex items-center gap-2 text-sm py-1 px-2 rounded hover:bg-gray-50",children:[e.jsx("input",{type:"checkbox",checked:o.productIds.includes(c.id),onChange:f=>{f.target.checked?x({...o,productIds:[...o.productIds,c.id]}):x({...o,productIds:o.productIds.filter(P=>P!==c.id)})},className:"rounded"}),c.name," â $",parseFloat(c.price).toFixed(2)]},c.id))})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(C,{onClick:F,style:{backgroundColor:"hsl(30, 65%, 45%)",color:"white"},children:[e.jsx(Ke,{className:"h-4 w-4 mr-2"}),n?"Update":"Create"]}),e.jsx(C,{variant:"outline",onClick:v,children:"Cancel"})]})]})]}),h?e.jsx("div",{className:"text-center py-12",children:e.jsx("div",{className:"animate-spin w-8 h-8 border-4 border-amber-600 border-t-transparent roun
112ded-full mx-auto"})}):!m||m.length===0?e.jsx(G,{className:"text-center py-12",children:e.jsxs(Q,{children:[e.jsx(Qe,{className:"h-12 w-12 text-gray-300 mx-auto mb-3"}),e.jsx("p",{className:"text-gray-500",children:"No bundle configs yet. Create your first one above!"})]})}):e.jsx("div",{className:"space-y-3",children:m.map(c=>e.jsx(G,{className:"hover:shadow-md transition-shadow",children:e.jsx(Q,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-14 h-14 rounded-lg bg-amber-100 flex items-center justify-center flex-shrink-0",children:c.imageUrl?e.jsx("img",{src:c.imageUrl,alt:c.name,className:"w-full h-full object-cover rounded-lg"}):e.jsx(Qe,{className:"h-7 w-7 text-amber-600"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold text-gray-900",children:c.name}),e.jsx(H,{variant:c.isActive?"default":"secondary",children:c.isActive?"Active":"Inactive"})]}),e.jsxs("p",{className:"text-sm text-gray-500",children:[c.sizeLabel," â ",c.itemCount," items"]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsxs("span",{className:"font-bold text-amber-700",children:["$",parseFloat(c.bundlePrice).toFixed(2)]}),c.compareAtPrice&&e.jsxs("span",{className:"text-sm text-gray-400 line-through",children:["$",parseFloat(c.compareAtPrice).toFixed(2)]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(C,{variant:"outline",size:"sm",onClick:()=>k(c),children:[e.jsx(ze,{className:"h-3.5 w-3.5 mr-1"}),"Edit"]}),e.jsx(C,{variant:"outline",size:"sm",className:"text-red-500 hover:text-red-700 hover:bg-red-50",onClick:()=>{confirm("Delete this bundle config?")&&j.mutate(c.id)},children:e.jsx(Ve,{className:"h-3.5 w-3.5"})})]})]})})},c.id))})]})}function ao(){const{toast:t}=Ee(),{data:a}=he({queryKey:["/api/products","coupon-products"],queryFn:async()=>(await fetch("/api/products?includeAll=true",{cache:"no-store"})).json()}),{data:s,isLoading:n}=he({queryKey:["/api/coupons"]}),[r,o]=i.useState(!1),[x,m]=i.useState(null),[h,u]=i.useState({code:"",type:"percent",value:"",freeProductId:"",minimumOrder:"",useLimitPerCustomer:"1",totalUseLimit:"",isActive:!0,freeShipping:!1,expiresAt:""}),w=()=>{u({code:"",type:"percent",value:"",freeProductId:"",minimumOrder:"",useLimitPerCustomer:"1",totalUseLimit:"",isActive:!0,freeShipping:!1,expiresAt:""})},y=ee({mutationFn:async c=>{const f=await fetch("/api/coupons",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!f.ok){const P=await f.json();throw new Error(P.error)}return f.json()},onSuccess:()=>{X.invalidateQueries({queryKey:["/api/coupons"]}),o(!1),w(),t({title:"Coupon created"})},onError:c=>t({title:c.message,variant:"destructive"})}),j=ee({mutationFn:async({id:c,data:f})=>{const P=await fetch(`/api/coupons/${c}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)});if(!P.ok){const D=await P.json();throw new Error(D.error)}return P.json()},onSuccess:()=>{X.invalidateQueries({queryKey:["/api/coupons"]}),m(null),w(),t({title:"Coupon updated"})},onError:c=>t({title:c.message,variant:"destructive"})}),v=ee({mutationFn:async c=>{const f=await fetch(`/api/coupons/${c}`,{method:"DELETE"});if(!f.ok)throw new Error("Failed");return f.json()},onSuccess:()=>{X.invalidateQueries({queryKey:["/api/coupons"]}),t({title:"Coupon deleted"})}}),k=()=>{const c={code:h.code,type:h.type,value:h.type==="free_item"?"0":h.value,isActive:h.isActive,freeShipping:h.freeShipping};h.freeProductId&&(c.freeProductId=parseInt(h.freeProductId)),h.minimumOrder&&(c.minimumOrder=h.minimumOrder),h.useLimitPerCustomer&&(c.useLimitPerCustomer=parseInt(h.useLimitPerCustomer)),h.totalUseLimit&&(c.totalUseLimit=parseInt(h.totalUseLimit)),h.expiresAt&&(c.expiresAt=new Date(h.expiresAt).toISOString()),x?j.mutate({id:x.id,data:c}):y.mutate(c)},F=c=>{var f,P,D;m(c),u({code:c.code,type:c.type,value:c.value,freeProductId:((f=c.freeProductId)==null?void 0:f.toString())||"",minimumOrder:c.minimumOrder||"",useLimitPerCustomer:((P=c.useLimitPerCustomer)==null?void 0:P.toString())||"1",totalUseLimit:((D=c.totalUseLimit)==null?void 0:D.toString())||"",isActive:c.isActive,freeShipping:c.freeShipping||!1,expiresAt:c.expiresAt?new Date(c.expiresAt).toISOString().split("T")[0]:""}),o(!0)},L=c=>c==="percent"?"% Off":c==="fixed"?"$ Off":c==="free_item"?"Free Item":c;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900",children:"Coupon Codes"}),e.jsxs("p",{className:"text-sm text-gray-500 mt-1",children:[(s==null?void 0:s.length)||0," total coupons"]})]}),e.jsxs(C,{onClick:()=>{w(),m(null),o(!0)},className:"bg-amber-600 hover:bg-amber-700 text-white",children:[e.jsx(Be,{className:"h-4 w-4 mr-2"})," New Coupon"]})]}),r&&e.jsxs(G,{className:"border border-amber-200 bg-amber-50/30",children:[e.jsx(je,{className:"pb-3",children:e.jsx(Pe,{className:"text-lg",children:x?"Edit Coupon":"Create Coupon"})}),e.jsxs(Q,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(S,{className:"text-xs font-medium",children:"Code"}),e.jsx(E,{value:h.code,onChange:c=>u({...h,code:c.target.value.toUpperCase()}),placeholder:"SAVE20",className:"uppercase"})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs font-medium",children:"Type"}),e.jsxs(Ne,{value:h.type,onValueChange:c=>u({...h,type:c}),children:[e.jsx(we,{children:e.jsx(Ce,{})}),e.jsxs(Se,{children:[e.jsx(Z,{value:"percent",children:"% Off"}),e.jsx(Z,{value:"fixed",children:"$ Off"}),e.jsx(Z,{value:"free_item",children:"Free Item"})]})]})]}),h.type!=="free_item"?e.jsxs("div",{children:[e.jsxs(S,{className:"text-xs font-medium",children:["Value ",h.type==="percent"?"(%)":"($)"]}),e.jsx(E,{type:"number",value:h.value,onChange:c=>u({...h,value:c.target.value}),placeholder:h.type==="percent"?"20":"5.00"})]}):e.jsxs("div",{children:[e.jsx(S,{className:"text-xs font-medium",children:"Free Product"}),e.jsxs(Ne,{value:h.freeProductId,onValueChange:c=>u({...h,freeProductId:c}),children:[e.jsx(we,{children:e.jsx(Ce,{placeholder:"Select product"})}),e.jsx(Se,{children:(a||[]).filter(c=>c.isActive).map(c=>e.jsx(Z,{value:c.id.toString(),children:c.name},c.id))})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx(S,{className:"text-xs font-medium",children:"Min. Order ($)"}),e.jsx(E,{type:"number",value:h.minimumOrder,onChange:c=>u({...h,minimumOrder:c.target.value}),placeholder:"0"})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs font-medium",children:"Limit / Customer"}),e.jsx(E,{type:"number",value:h.useLimitPerCustomer,onChange:c=>u({...h,useLimitPerCustomer:c.target.value}),placeholder:"1"})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs font-medium",children:"Total Use Limit"}),e.jsx(E,{type:"number",value:h.totalUseLimit,onChange:c=>u({...h,totalUseLimit:c.target.value}),placeholder:"Unlimited"})]}),e.jsxs("div",{children:[e.jsx(S,{className:"text-xs font-medium",children:"Expires"}),e.jsx(E,{type:"date",value:h.expiresAt,onChange:c=>u({...h,expiresAt:c.target.value})})]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",checked:h.isActive,onChange:c=>u({...h,isActive:c.target.checked}),className:"rounded border-gray-300"}),"Active"]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",checked:h.freeShipping,onChange:c=>u({...h,freeShipping:c.target.checked}),className:"rounded border-gray-300"}),"ð Free Shipping"]}),e.jsx("div",{className:"flex-1"}),e.jsx(C,{variant:"outline",size:"sm",onClick:()=>{o(!1),m(null),w()},children:"Cancel"}),e.jsxs(C,{size:"sm",className:"bg-amber-600 hover:bg-amber-700 text-white",onClick:k,disabled:!h.code||h.type!=="free_item"&&!h.value,children:[e.jsx(Ke,{className:"h-3.5 w-3.5 mr-1"}),x?"Update":"Create"]})]})]})]}),n?e.jsx("div",{className:"text-center py-12 text-gray-400",children:"Loading coupons..."}):s!=null&&s.length?e.jsx(G,{children:e.jsx(Q,{className:"p-0",children: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 bg-gray-50",children:[e.jsx("th",{className:"text-left px-4 py-3 font-medium text-gray-600",children:"Code"}),e.jsx("th",{className:"text-left px-4 py-3 font-medium text-gray-600",children:"Type"}),e.jsx("th",{className:"text-left px-4 py-3 font-medium text-gray-600",children:"Value"}),e.jsx("th",{className:"text-left px-4 py-3 font-medium text-gray-600",children:"Min. Order"}),e.jsx("th",{className:"text-left px-4 py-3 font-medium text-gray-600",children:"Limit/Customer"}),e.jsx("th",{className:"text-left px-4 py-3 font-medium text-gray-600",children:"Used"}),e.jsx("th",{className:"text-left px-4 py-3 font-medium text-gray-600",children:"Status"}),e.jsx("th",{className:"text-left px-4 py-3 font-medium text-gray-600",children:"Expires"}),e.jsx("th",{className:"text-right px-4 py-3 font-medium text-gray-600",children:"Actions"})]})}),e.jsx("tbody",{children:s.map(c=>e.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono font-bold text-amber-700",children:c.code}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(H,{variant:"outline",className:"text-xs",children:L(c.type)})}),e.jsx("td",{className:"px-4 py-3",children:c.type==="percent"?`${c.value}%`:c.type==="fixed"?`$${parseFloat(c.value).toFixed(2)}`:"Free Item"}),e.jsx("td",{className:"px-4 py-3",children:c.minimumOrder?`$${parseFloat(c.minimumOrder).toFixed(2)}`:"â"}),e.jsx("td",{className:"px-4 py-3",children:c.useLimitPerCustomer||"â"}),e.jsxs("td",{className:"px-4 py-3",children:[c.timesUsed,c.totalUseLimit?` / ${c.totalUseLimit}`:""]}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(H,{className:c.isActive?"bg-green-100 text-green-800":"bg-gray-100 text-gray-600",children:c.isActive?"Active":"Inactive"}),c.freeShipping&&e.jsx(H,{className:"bg-blue-100 text-blue-700 text-xs",children:"ð Free Ship"})]})}),e.jsx("td",{className:"px-4 py-3 text-gray-500",children:c.expiresAt?new Date(c.expiresAt).toLocaleDateString():"Never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(C,{variant:"ghost",size:"sm",onClick:()=>F(c),children:e.jsx(ze,{className:"h-3.5 w-3.5"})}),e.jsx(C,{variant:"ghost",size:"sm",className:"text-red-500 hover:text-red-700",onClick:()=>{confirm("Delete this coupon?")&&v.mutate(c.id)},children:e.jsx(Ve,{className:"h-3.5 w-3.5"})})]})})]},c.id))})]})})})}):e.jsx(G,{className:"border-dashed",children:e.jsxs(Q,{className:"py-12 text-center text-gray-500",children:[e.jsx(la,{className:"h-10 w-10 mx-auto mb-3 text-gray-300"}),e.jsx("p",{className:"font-medium",children:"No coupons yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Create your first coupon code to offer discounts."})]})})]})}function ro(){const[t,a]=i.useState(""),[s,n]=i.useState(0),[r,o]=i.useState(!1),[x,m]=i.useState(null),{toast:h}=Ee(),{data:u,refetch:w}=he({queryKey:["/api/admin/renewal-preview"]}),y=async()=>{try{const k=await(await fetch("/api/admin/renewal-logs?limit=300")).json();a(k.logs||""),n(k.totalLines||0)}catch(v){console.error("Failed to fetch logs:",v)}};i.useEffect(()=>{y()},[]);const j=async()=>
112{if(confirm("This will attempt to charge all active subscriptions that are due. Continue?")){o(!0);try{const k=await(await fetch("/api/admin/run-renewals",{method:"POST"})).json();m(k),h({title:"Renewal Run Complete",description:`${k.succeeded||0} succeeded, ${k.failed||0} failed, ${k.skipped||0} skipped`}),y(),w()}catch(v){h({title:"Error",description:v.message||"Failed to run renewals",variant:"destructive"})}finally{o(!1)}}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900",children:"Subscription Renewals"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Auto-runs daily at 9:00 AM EST. You can also trigger manually below."})]}),e.jsx(C,{onClick:j,disabled:r,className:"bg-amber-700 hover:bg-amber-800 text-white",children:r?e.jsxs(e.Fragment,{children:[e.jsx(Ot,{className:"w-4 h-4 mr-2 animate-spin"}),"Running..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Kt,{className:"w-4 h-4 mr-2"}),"Run Renewals Now"]})})]}),x&&e.jsx(G,{className:"border-green-200 bg-green-50",children:e.jsx(Q,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[e.jsx("span",{className:"font-semibold text-green-800",children:"Last Run:"}),e.jsxs("span",{className:"text-green-700",children:[x.total," total"]}),e.jsxs("span",{className:"text-green-700",children:[x.succeeded," succeeded"]}),e.jsxs("span",{className:"text-red-600",children:[x.failed," failed"]}),e.jsxs("span",{className:"text-amber-600",children:[x.skipped," skipped"]})]})})}),e.jsxs(G,{children:[e.jsx(je,{children:e.jsxs(Pe,{className:"text-lg flex items-center gap-2",children:[e.jsx(ia,{className:"w-5 h-5"}),"Due for Renewal (",(u==null?void 0:u.dueCount)||0,")"]})}),e.jsx(Q,{children:u&&u.subscriptions.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-gray-50 border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-3 py-2 font-medium text-gray-500",children:"ID"}),e.jsx("th",{className:"text-left px-3 py-2 font-medium text-gray-500",children:"Customer"}),e.jsx("th",{className:"text-left px-3 py-2 font-medium text-gray-500",children:"Amount"}),e.jsx("th",{className:"text-left px-3 py-2 font-medium text-gray-500",children:"Frequency"}),e.jsx("th",{className:"text-left px-3 py-2 font-medium text-gray-500",children:"Due Date"}),e.jsx("th",{className:"text-left px-3 py-2 font-medium text-gray-500",children:"Stripe"})]})}),e.jsx("tbody",{children:u.subscriptions.map(v=>e.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[e.jsxs("td",{className:"px-3 py-2",children:["#",v.id]}),e.jsxs("td",{className:"px-3 py-2",children:[e.jsx("div",{children:v.name}),e.jsx("div",{className:"text-xs text-gray-400",children:v.email})]}),e.jsxs("td",{className:"px-3 py-2 font-medium",children:["$",parseFloat(v.amount||"0").toFixed(2)]}),e.jsx("td",{className:"px-3 py-2 capitalize",children:v.frequency}),e.jsx("td",{className:"px-3 py-2 text-xs",children:v.nextPaymentDate?new Date(v.nextPaymentDate).toLocaleDateString():"â"}),e.jsx("td",{className:"px-3 py-2",children:v.hasStripeCustomer?e.jsx(H,{variant:"outline",className:"text-green-700 border-green-300 bg-green-50 text-xs",children:"Ready"}):e.jsx(H,{variant:"outline",className:"text-red-600 border-red-300 bg-red-50 text-xs",children:"No Stripe ID"})})]},v.id))})]})}):e.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:"No subscriptions currently due for renewal."})})]}),e.jsxs(G,{children:[e.jsxs(je,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Pe,{className:"text-lg flex items-center gap-2",children:[e.jsx(rs,{className:"w-5 h-5"}),"Renewal Logs (",s," entries)"]}),e.jsxs(C,{variant:"outline",size:"sm",onClick:y,children:[e.jsx(Ot,{className:"w-3.5 h-3.5 mr-1"})," Refresh"]})]}),e.jsx(Q,{children:e.jsx("div",{className:"bg-gray-900 text-gray-100 rounded-lg p-4 max-h-96 overflow-y-auto font-mono text-xs whitespace-pre-wrap",children:t||"No logs yet. Logs will appear after the first renewal run."})})]})]})}function no({title:t,fallback:a}
112){if(t==="Apple Pay")return e.jsxs("span",{className:"inline-flex items-center gap-1.5","data-testid":"badge-apple-pay",children:[e.jsx("svg",{viewBox:"0 0 384 512",className:"h-4 w-4 shrink-0",fill:"currentColor","aria-hidden":"true",children:e.jsx("path",{d:"M318.7 268.7c-.2-36.7 16.4-64.4 50-84.8-18.8-26.9-47.2-41.7-84.7-44.6-35.5-2.8-74.3 20.7-88.5 20.7-15 0-49.4-19.7-76.4-19.7C63.3 141.2 4 184.8 4 273.5q0 39.3 14.4 81.2c12.8 36.7 59 126.7 107.2 125.2 25.2-.6 43-17.9 75.8-17.9 31.8 0 48.3 17.9 76.4 17.9 48.6-.7 90.4-82.5 102.6-119.3-65.2-30.7-61.7-90-61.7-91.9zm-56.6-164.2c27.3-32.4 24.8-61.9 24-72.5-24.1 1.4-52 16.4-67.9 34.9-17.5 19.8-27.8 44.3-25.6 71.9 26.1 2 49.9-11.4 69.5-34.3z"})}),"Apple Pay"]});if(t==="Google Pay")return e.jsxs("span",{className:"inline-flex items-center gap-1.5","data-testid":"badge-google-pay",children:[e.jsxs("svg",{viewBox:"0 0 48 48",className:"h-4 w-4 shrink-0","aria-hidden":"true",children:[e.jsx("path",{fill:"#EA4335",d:"M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"}),e.jsx("path",{fill:"#4285F4",d:"M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"}),e.jsx("path",{fill:"#FBBC05",d:"M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"}),e.jsx("path",{fill:"#34A853",d:"M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"})]}),"Google Pay"]});const s=t||(a==="stripe"?"Credit Card":a)||"â";return e.jsx("span",{children:s})}function io(){const{toast:t}=Ee(),[a,s]=i.useState(""),{data:n,isLoading:r}=he({queryKey:["/api/store-settings","free_shipping_threshold"],queryFn:async()=>(await fetch("/api/store-settings/free_shipping_threshold")).json()});i.useEffect(()=>{n!=null&&n.value&&s(n.value)},[n]);const o=ee({mutationFn:async P=>await ae("/api/store-settings/free_shipping_threshold","PUT",{value:P}),onSuccess:()=>{X.invalidateQueries({queryKey:["/api/store-settings","free_shipping_threshold"]}),t({title:"Saved",description:"Free shipping threshold updated."})},onError:()=>{t({title:"Error",description:"Failed to save setting.",variant:"destructive"})}}),{data:x}=he({queryKey:["/api/products","settings-promo"],queryFn:async()=>(await fetch("/api/products?includeAll=true",{cache:"no-store"})).json()}),{data:m}=he({queryKey:["/api/store-settings","free_product_promo"],queryFn:async()=>(await fetch("/api/store-settings/free_product_promo")).json()}),h={enabled:!1,minAmount:0,freeProductId:null,excludedProductIds:[]},[u,w]=i.useState(h);i.useEffect(()=>{if(m!=null&&m.value)try{const P=JSON.parse(m.value);w({...h,...P})}catch{w(h)}},[m]);const y=ee({mutationFn:async P=>await ae("/api/store-settings/free_product_promo","PUT",{value:JSON.stringify(P)}),onSuccess:()=>{X.invalidateQueries({queryKey:["/api/store-settings","free_product_promo"]}),t({title:"Saved",description:"Free product promo updated."})},onError:()=>{t({title:"Error",description:"Failed to save promo.",variant:"destructive"})}}),[j,v]=i.useState({standard:"100",large:"200",threshold:"99"}),{data:k}=he({queryKey:["/api/store-settings","points_redemption_caps"],queryFn:async()=>(await fetch("/api/store-settings/points_redemption_caps")).json()});i.useEffect(()=>{if(k!=null&&k.value)try{const P=JSON.parse(k.value);v({standard:String(P.standard??"100"),large:String(P.large??"200"),threshold:String(P.threshold??"99")})}catch{}},[k]);const F=ee({mutationFn:async()=>{const P=JSON.stringify({standard:Math.trunc(Number(j.standard)),large:Math.trunc(Number(j.large)),threshold:Number(j.threshold)});return await ae("/api/store-settings/points_redemption_caps","PUT",{value:P})},onSuccess:()=>{X.invalidateQueries({queryKey:["/api/store-settings","points_redemption_caps"]}),t({title:"Saved",description:"Rewards redemption caps updated â checkout uses them immediately."})},onError:()=>{t({title:"Error",description:"Failed to save redemption caps.",variant:"destructive"})}}),L=Math.trunc(Number(j.standard))>0&&Math.trunc(Number(j.large))>=Math.trunc(Number(j.standard))&&Number(j.threshold)>=0,c=(x||[]).filter(P=>P.isActive),f=c.find(P=>P.id===u.freeProductId);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900",children:"Store Settings"}),e.jsx("p",{className:"text-gray-500 mt-1",children:"Configure global store options"})]}),e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(Pe,{className:"text-lg flex items-center gap-2",children:[e.jsx(bt,{className:"w-5 h-5"}),"Free Shipping"]}),e.jsx(yt,{children:"Set the order amount threshold for free shipping. Customers will see a progress bar in their cart showing how close they are."})]}),e.jsxs(Q,{children:[e.jsxs("div",{className:"flex items-end gap-3 max-w-sm",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(S,{htmlFor:"free-shipping",children:"Minimum order amount ($)"}),e.jsxs("div",{className:"relative mt-1.5",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 text-sm",children:"$"}),e.jsx(E,{id:"free-shipping",type:"number",step:"0.01",min:"0",value:a,onChange:P=>s(P.target.value),className:"pl-7",placeholder:"59.00",disabled:r})]})]}),e.jsxs(C,{onClick:()=>o.mutate(a),disabled:o.isPending||!a,className:"bg-gray-900 text-white hover:bg-gray-800",children:[e.jsx(Ke,{className:"w-4 h-4 mr-1.5"}),o.isPending?"Saving...":"Save"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Set to 0 to disable the free shipping progress bar."})]})]}),e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(Pe,{className:"text-lg flex items-center gap-2",children:[e.jsx(Qe,{className:"w-5 h-5"}),"Free Product Promo"]}),e.jsx(yt,{children:"Automatically give customers a free product when their cart reaches a minimum amount. You can exclude specific products from the qualifying total."})]}),e.jsxs(Q,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(S,{htmlFor:"promo-enabled",className:"font-medium",children:"Enable Promo"}),e.jsx("button",{id:"promo-enabled",onClick:()=>w({...u,enabled:!u.enabled}),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${u.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${u.enabled?"translate-x-6":"translate-x-1"}`})}),e.jsx("span",{className:`text-sm font-medium ${u.enabled?"text-green-600":"text-gray-400"}`,children:u.enabled?"Active":"Disabled"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(S,{children:"Minimum Cart Amount ($)"}),e.jsxs("div",{className:"relative mt-1.5",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 text-sm",children:"$"}),e.jsx(E,{type:"number",step:"0.01",min:"0",value:u.minAmount||"",onChange:P=>w({...u,minAmount:parseFloat(P.target.value)||0}),className:"pl-7",placeholder:"50.00"})]})]}),e.jsxs("div",{children:[e.jsx(S,{children:"Free Product"}),e.jsxs(Ne,{value:u.freeProductId?String(u.freeProductId):"",onValueChange:P=>w({...u,freeProductId:parseInt(P)}),children:[e.jsx(we,{className:"mt-1.5",children:e.jsx(Ce,{placeholder:"Select a product..."})}),e.jsx(Se,{children:c.map(P=>e.jsxs(Z,{value:String(P.id),children:[P.name," ($",parseFloat(P.price).toFixed(2),")"]},P.id))})]})]})]}),f&&e.jsxs("div",{className:"bg-green-50 border border-green-200 rounded-lg px-3 py-2 text-sm text-green-800",children:["Customers spending $",u.minAmount.toFixed(2),"+ will receive a free ",e.jsx("strong",{children:f.name})," ($",parseFloat(f.price).toFixed(2)," value)"]}),e.jsxs("div",{children:[e.jsx(S,{className:"mb-2 block",children:"Excluded Products"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"These products will NOT count toward the minimum c
112art amount for this promo."}),e.jsx("div",{className:"border rounded-lg max-h-48 overflow-y-auto",children:c.map(P=>{const D=u.excludedProductIds.includes(P.id);return e.jsxs("label",{className:`flex items-center gap-2 px-3 py-1.5 text-sm cursor-pointer hover:bg-gray-50 border-b last:border-b-0 ${D?"bg-red-50":""}`,children:[e.jsx("input",{type:"checkbox",checked:D,onChange:()=>{const b=D?u.excludedProductIds.filter(O=>O!==P.id):[...u.excludedProductIds,P.id];w({...u,excludedProductIds:b})},className:"rounded border-gray-300"}),e.jsx("span",{className:D?"text-red-700 line-through":"",children:P.name}),e.jsxs("span",{className:"text-xs text-muted-foreground ml-auto",children:["$",parseFloat(P.price).toFixed(2)]})]},P.id)})}),u.excludedProductIds.length>0&&e.jsxs("p",{className:"text-xs text-red-600 mt-1",children:[u.excludedProductIds.length," product(s) excluded from qualifying total"]})]}),e.jsxs(C,{onClick:()=>y.mutate(u),disabled:y.isPending,className:"bg-gray-900 text-white hover:bg-gray-800",children:[e.jsx(Ke,{className:"w-4 h-4 mr-1.5"}),y.isPending?"Saving...":"Save Promo Settings"]})]})]}),e.jsxs(G,{children:[e.jsxs(je,{children:[e.jsxs(Pe,{className:"text-lg flex items-center gap-2",children:[e.jsx(Qe,{className:"w-5 h-5"}),"Rewards Redemption Caps"]}),e.jsx(yt,{children:"How many points a customer can redeem on a single order. Orders at or under the threshold use the standard cap; larger orders use the higher cap. 100 pts = $5 at checkout."})]}),e.jsxs(Q,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(S,{children:"Order threshold ($)"}),e.jsxs("div",{className:"relative mt-1.5",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 text-sm",children:"$"}),e.jsx(E,{type:"number",min:"0",step:"1",value:j.threshold,onChange:P=>v({...j,threshold:P.target.value}),className:"pl-7","data-testid":"input-caps-threshold"})]}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:"Orders above this subtotal get the higher cap."})]}),e.jsxs("div",{children:[e.jsx(S,{children:"Cap up to threshold (pts)"}),e.jsx(E,{type:"number",min:"1",step:"100",value:j.standard,onChange:P=>v({...j,standard:P.target.value}),className:"mt-1.5","data-testid":"input-caps-standard"}),e.jsxs("p",{className:"text-xs text-gray-400 mt-1",children:["= $",(Math.trunc(Number(j.standard))/20||0).toFixed(2)," max discount"]})]}),e.jsxs("div",{children:[e.jsx(S,{children:"Cap above threshold (pts)"}),e.jsx(E,{type:"number",min:"1",step:"100",value:j.large,onChange:P=>v({...j,large:P.target.value}),className:"mt-1.5","data-testid":"input-caps-large"}),e.jsxs("p",{className:"text-xs text-gray-400 mt-1",children:["= $",(Math.trunc(Number(j.large))/20||0).toFixed(2)," max discount"]})]})]}),!L&&e.jsx("p",{className:"text-xs text-red-600",children:"Caps must be positive, the above-threshold cap must be ⥠the standard cap, and the threshold can't be negative."}),e.jsxs(C,{onClick:()=>F.mutate(),disabled:F.isPending||!L,className:"bg-gray-900 text-white hover:bg-gray-800","data-testid":"button-save-caps",children:[e.jsx(Ke,{className:"w-4 h-4 mr-1.5"}),F.isPending?"Saving...":"Save Redemption Caps"]})]})]})]})}export{Ro 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.