@cedros/pay-react 1.1.21 → 1.1.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{AISettingsSection-BXWZcMQT.js → AISettingsSection-BtOxEweU.js} +1 -1
- package/dist/{AISettingsSection-8eDaxYp8.mjs → AISettingsSection-p3iikbSw.mjs} +2 -2
- package/dist/{AutosaveIndicator-DW4IPbZ5.js → AutosaveIndicator-C-CH-obR.js} +1 -1
- package/dist/{AutosaveIndicator-3S7EvXip.mjs → AutosaveIndicator-CWbb-VXf.mjs} +1 -1
- package/dist/{FAQSection-r6eKjfdO.js → FAQSection-DQpF7hVx.js} +1 -1
- package/dist/{FAQSection-Dg-I7Z-N.mjs → FAQSection-byh7zfqI.mjs} +1 -1
- package/dist/{MessagingSection-Cld5Q7ZM.js → MessagingSection-B6EHvjDw.js} +1 -1
- package/dist/{MessagingSection-D39EuOLN.mjs → MessagingSection-CK208brx.mjs} +2 -2
- package/dist/{PaymentSettingsSection-CEGHN6VI.mjs → PaymentSettingsSection-B9H253x1.mjs} +1 -1
- package/dist/{PaymentSettingsSection-B-MRsh1K.js → PaymentSettingsSection-Cmmuhmd4.js} +1 -1
- package/dist/{SettingsSection-CPFOuoZG.mjs → SettingsSection-DDLMaEPo.mjs} +1 -1
- package/dist/{SettingsSection-ZrzfLBlS.js → SettingsSection-DrzGdvHH.js} +1 -1
- package/dist/{SingleCategorySettings-DhHGIGwB.mjs → SingleCategorySettings-BU98SRFV.mjs} +56 -56
- package/dist/SingleCategorySettings-DqcXe-q4.js +3 -0
- package/dist/{StorefrontSection-DGVcJu1T.js → StorefrontSection-DTpZ_GgO.js} +1 -1
- package/dist/{StorefrontSection-f54ySA6i.mjs → StorefrontSection-Dr2ciBVg.mjs} +2 -2
- package/dist/{SubscriptionsSection-F2IiU2jv.mjs → SubscriptionsSection-CU3Ce8r9.mjs} +1 -1
- package/dist/{SubscriptionsSection-fzbL5DGC.js → SubscriptionsSection-CYJpArJ8.js} +1 -1
- package/dist/crypto-only.js +1 -1
- package/dist/crypto-only.mjs +1 -1
- package/dist/{index-bqhsxBTY.mjs → index-CufXF9Yd.mjs} +18 -18
- package/dist/{index-7YUxR4u5.js → index-IZ4WcMd7.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{sections-CiAMjlPd.mjs → sections-Bc6ARlND.mjs} +1 -1
- package/dist/{sections-Dh0qFSUW.js → sections-CR7NRsjq.js} +1 -1
- package/package.json +1 -1
- package/dist/SingleCategorySettings-DxjCafCk.js +0 -3
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";const s=require("react/jsx-runtime"),k=require("react"),zf=require("@solana/wallet-adapter-react"),Je=require("./CedrosContext-D-lnoEkR.js"),Ff=require("@cedros/login-react"),oi=require("./index-WcOlBYZJ.js"),Zo=require("react-dom"),Uf=require("./styles-BWrLnaUW.js");function Tc(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const m=Tc(k),ps=Tc(Zo);function lr(e){return new Date(e).toLocaleString()}const Y={products:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M20 7.5v9l-4 2.25M4 7.5v9l4 2.25"}),s.jsx("path",{d:"m20 7.5-8-4.5-8 4.5"}),s.jsx("path",{d:"m12 12 8-4.5M12 12v9.5M12 12 4 7.5"})]}),transactions:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"})}),coupons:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z"}),s.jsx("path",{d:"M13 5v2M13 17v2M13 11v2"})]}),refunds:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),s.jsx("path",{d:"M3 3v5h5"}),s.jsx("path",{d:"M12 7v5l4 2"})]}),settings:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),wallet:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}),s.jsx("path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"})]}),chevronRight:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"m9 18 6-6-6-6"})}),loading:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"cedros-admin__spinner",children:s.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),refresh:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}),s.jsx("path",{d:"M21 3v5h-5"}),s.jsx("path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}),s.jsx("path",{d:"M8 16H3v5"})]}),check:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M20 6 9 17l-5-5"})}),subscriptions:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M12 2v2M12 20v2M2 12H4M20 12h2"})]}),trash:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"})}),plus:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M12 5v14M5 12h14"})}),chevronDown:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"m6 9 6 6 6-6"})}),chevronUp:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"m18 15-6-6-6 6"})}),storefront:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M3 9h18v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V9Z"}),s.jsx("path",{d:"m3 9 2.45-4.9A2 2 0 0 1 7.24 3h9.52a2 2 0 0 1 1.8 1.1L21 9"}),s.jsx("path",{d:"M12 3v6"})]}),arrowUp:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"m5 12 7-7 7 7"}),s.jsx("path",{d:"M12 19V5"})]}),arrowDown:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"m5 12 7 7 7-7"}),s.jsx("path",{d:"M12 5v14"})]}),delete:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"}),s.jsx("path",{d:"M10 11v6M14 11v6"})]}),close:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M18 6 6 18M6 6l12 12"})}),edit:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),s.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),faq:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),s.jsx("path",{d:"M12 17h.01"})]}),chat:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"m3 21 1.9-5.7a8.5 8.5 0 1 1 3.8 3.8z"})}),globe:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}),s.jsx("path",{d:"M2 12h20"})]}),ai:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M12 2a4 4 0 0 1 4 4v2a4 4 0 0 1-8 0V6a4 4 0 0 1 4-4Z"}),s.jsx("path",{d:"M10 10v.5"}),s.jsx("path",{d:"M14 10v.5"}),s.jsx("path",{d:"M12 14v2"}),s.jsx("path",{d:"M8 18h8"}),s.jsx("path",{d:"M6 18a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2"}),s.jsx("path",{d:"M6 12v6"}),s.jsx("path",{d:"M18 12v6"})]}),notifications:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"}),s.jsx("path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0"})]}),eye:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),eyeOff:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24"}),s.jsx("path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"}),s.jsx("path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"}),s.jsx("line",{x1:"2",x2:"22",y1:"2",y2:"22"})]}),creditCard:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),s.jsx("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),mail:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),s.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),server:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2"}),s.jsx("rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2"}),s.jsx("line",{x1:"6",x2:"6.01",y1:"6",y2:"6"}),s.jsx("line",{x1:"6",x2:"6.01",y1:"18",y2:"18"})]}),calendarRepeat:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",ry:"2"}),s.jsx("line",{x1:"16",x2:"16",y1:"2",y2:"6"}),s.jsx("line",{x1:"8",x2:"8",y1:"2",y2:"6"}),s.jsx("line",{x1:"3",x2:"21",y1:"10",y2:"10"}),s.jsx("path",{d:"M11 14h1.5a1.5 1.5 0 0 1 0 3H11v2"}),s.jsx("path",{d:"M16 14v3a1 1 0 0 0 1 1h1"})]}),brain:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"}),s.jsx("path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"}),s.jsx("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),s.jsx("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),s.jsx("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),s.jsx("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),s.jsx("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),s.jsx("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),s.jsx("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]})};function jr({message:e,onRetry:t}){return e?s.jsxs("div",{className:"cedros-admin__error-banner",children:[s.jsx("span",{children:e}),t&&s.jsxs("button",{type:"button",className:"cedros-admin__error-banner-retry",onClick:t,children:[Y.refresh," Retry"]})]}):null}function Sr({stats:e,isLoading:t=!1,onRefresh:n}){return s.jsxs("div",{className:"cedros-admin__stats-bar",children:[s.jsx("div",{className:"cedros-admin__stats-bar-grid",children:e.map((r,o)=>s.jsxs("div",{className:"cedros-admin__stats-bar-item",children:[s.jsx("span",{className:"cedros-admin__stats-bar-label",children:r.label}),s.jsx("span",{className:`cedros-admin__stats-bar-value ${r.variant?`cedros-admin__stats-bar-value--${r.variant}`:""}`,children:t?s.jsx("span",{className:"cedros-admin__skeleton cedros-admin__skeleton--value"}):r.value}),r.description&&s.jsx("span",{className:"cedros-admin__stats-bar-desc",children:r.description})]},o))}),n&&s.jsx("button",{type:"button",className:"cedros-admin__stats-bar-refresh",onClick:n,disabled:t,title:"Refresh stats",children:t?Y.loading:Y.refresh})]})}function Bf({serverUrl:e,productId:t,apiKey:n,authManager:r}){const[o,a]=k.useState(null),[i,c]=k.useState(!1),[l,d]=k.useState(!1),[f,u]=k.useState(null),h=k.useCallback(async()=>{if(t){c(!0),u(null);try{let x;if(r?.isAuthenticated())x=await r.fetchWithAuth(`/admin/products/${t}/variations`);else{const p={"Content-Type":"application/json"};n&&(p["X-API-Key"]=n);const v=await fetch(`${e}/admin/products/${t}/variations`,{headers:p});if(!v.ok)throw new Error(`Failed to fetch variations: ${v.status}`);x=await v.json()}x.variationConfig||(x.variationConfig={variationTypes:[]}),x.variants||(x.variants=[]),a(x)}catch(x){const p=x instanceof Error?x.message:"Failed to fetch variations";u(p),a({productId:t,variationConfig:{variationTypes:[]},variants:[]})}finally{c(!1)}}},[e,t,n,r]),g=k.useCallback(async x=>{if(!t)return null;d(!0),u(null);try{let p;if(r?.isAuthenticated())p=await r.fetchWithAuth(`/admin/products/${t}/variations`,{method:"PUT",body:JSON.stringify(x)});else{const v={"Content-Type":"application/json"};n&&(v["X-API-Key"]=n);const _=await fetch(`${e}/admin/products/${t}/variations`,{method:"PUT",headers:v,body:JSON.stringify(x)});if(!_.ok)throw new Error(`Failed to save variations: ${_.status}`);p=await _.json()}return a({productId:t,variationConfig:p.variationConfig,variants:p.variants}),{variantsCreated:p.variantsCreated}}catch(p){const v=p instanceof Error?p.message:"Failed to save variations";return u(v),null}finally{d(!1)}},[e,t,n,r]),y=k.useCallback(async x=>{if(!t||x.length===0)return!1;d(!0),u(null);try{if(r?.isAuthenticated())await r.fetchWithAuth(`/admin/products/${t}/variants/inventory`,{method:"PUT",body:JSON.stringify({updates:x})});else{const p={"Content-Type":"application/json"};n&&(p["X-API-Key"]=n);const v=await fetch(`${e}/admin/products/${t}/variants/inventory`,{method:"PUT",headers:p,body:JSON.stringify({updates:x})});if(!v.ok)throw new Error(`Failed to update inventory: ${v.status}`)}if(o){const p=new Map(x.map(v=>[v.variantId,v]));a({...o,variants:o.variants.map(v=>{const _=p.get(v.id);return _?{...v,inventoryQuantity:_.inventoryQuantity,inventoryStatus:_.inventoryStatus??v.inventoryStatus}:v})})}return!0}catch(p){const v=p instanceof Error?p.message:"Failed to update inventory";return u(v),!1}finally{d(!1)}},[e,t,n,r,o]);return{data:o,isLoading:i,error:f,fetch:h,save:g,bulkUpdateInventory:y,isSaving:l}}function ai(){return`var_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Vf({value:e,onChange:t,maxTypes:n=5,maxValuesPerType:r=20,disabled:o=!1}){const[a,i]=k.useState(null),[c,l]=k.useState(""),[d,f]=k.useState({}),u=e.variationTypes,h=k.useCallback(()=>{if(!c.trim()||u.length>=n)return;const w={id:ai(),name:c.trim(),displayOrder:u.length,values:[]};t({variationTypes:[...u,w]}),l(""),i(w.id)},[c,u,n,t]),g=k.useCallback(w=>{t({variationTypes:u.filter(b=>b.id!==w).map((b,j)=>({...b,displayOrder:j}))}),a===w&&i(null)},[u,t,a]),y=k.useCallback((w,b)=>{t({variationTypes:u.map(j=>j.id===w?{...j,name:b}:j)})},[u,t]),x=k.useCallback((w,b)=>{const j=u.findIndex(C=>C.id===w);if(j===-1||b==="up"&&j===0||b==="down"&&j===u.length-1)return;const R=[...u],I=b==="up"?j-1:j+1;[R[j],R[I]]=[R[I],R[j]],t({variationTypes:R.map((C,E)=>({...C,displayOrder:E}))})},[u,t]),p=k.useCallback(w=>{const b=(d[w]||"").trim();if(!b)return;const j=u.find(I=>I.id===w);if(!j||j.values.length>=r)return;const R={id:ai(),label:b};t({variationTypes:u.map(I=>I.id===w?{...I,values:[...I.values,R]}:I)}),f(I=>({...I,[w]:""}))},[u,d,r,t]),v=k.useCallback((w,b)=>{t({variationTypes:u.map(j=>j.id===w?{...j,values:j.values.filter(R=>R.id!==b)}:j)})},[u,t]),_=k.useCallback((w,b,j)=>{t({variationTypes:u.map(R=>R.id===w?{...R,values:R.values.map(I=>I.id===b?{...I,label:j}:I)}:R)})},[u,t]);return s.jsxs("div",{className:"cedros-admin__variation-editor",children:[s.jsxs("div",{className:"cedros-admin__variation-editor-header",children:[s.jsx("h4",{className:"cedros-admin__field-label",style:{marginBottom:0},children:"Variation Types"}),s.jsxs("span",{style:{fontSize:12,opacity:.7},children:[u.length,"/",n," types"]})]}),u.length===0?s.jsx("div",{className:"cedros-admin__variation-empty",children:'No variation types defined. Add types like "Size" or "Color" to create product variants.'}):s.jsx("div",{className:"cedros-admin__variation-type-list",children:u.map((w,b)=>s.jsxs("div",{className:"cedros-admin__variation-type-item",children:[s.jsxs("div",{className:"cedros-admin__variation-type-header",children:[s.jsxs("div",{className:"cedros-admin__variation-type-controls",children:[s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>x(w.id,"up"),disabled:o||b===0,title:"Move up",children:Y.arrowUp}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>x(w.id,"down"),disabled:o||b===u.length-1,title:"Move down",children:Y.arrowDown})]}),s.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__variation-type-name",value:w.name,onChange:j=>y(w.id,j.target.value),disabled:o,placeholder:"Type name"}),s.jsxs("span",{className:"cedros-admin__variation-value-count",children:[w.values.length," values"]}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>i(a===w.id?null:w.id),children:a===w.id?"Collapse":"Edit values"}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>g(w.id),disabled:o,title:"Remove type",children:Y.delete})]}),a===w.id&&s.jsxs("div",{className:"cedros-admin__variation-values",children:[s.jsxs("div",{className:"cedros-admin__variation-values-header",children:[s.jsxs("span",{style:{fontSize:12,fontWeight:600},children:['Values for "',w.name,'"']}),s.jsxs("span",{style:{fontSize:11,opacity:.7},children:[w.values.length,"/",r]})]}),w.values.length===0?s.jsx("div",{className:"cedros-admin__variation-empty",style:{padding:"8px 0"},children:'No values yet. Add values like "Small", "Medium", "Large".'}):s.jsx("div",{className:"cedros-admin__variation-value-list",children:w.values.map(j=>s.jsxs("div",{className:"cedros-admin__variation-value-item",children:[s.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:j.label,onChange:R=>_(w.id,j.id,R.target.value),disabled:o}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon cedros-admin__button--danger",onClick:()=>v(w.id,j.id),disabled:o,title:"Remove value",children:Y.close})]},j.id))}),w.values.length<r&&s.jsxs("div",{className:"cedros-admin__variation-add-value",children:[s.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:d[w.id]||"",onChange:j=>f(R=>({...R,[w.id]:j.target.value})),placeholder:"Add value...",disabled:o,onKeyDown:j=>{j.key==="Enter"&&(j.preventDefault(),p(w.id))}}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary cedros-admin__button--sm",onClick:()=>p(w.id),disabled:o||!d[w.id]?.trim(),children:"Add"})]})]})]},w.id))}),u.length<n&&s.jsxs("div",{className:"cedros-admin__variation-add-type",children:[s.jsx("input",{type:"text",className:"cedros-admin__input",value:c,onChange:w=>l(w.target.value),placeholder:"New variation type (e.g., Size, Color)",disabled:o,onKeyDown:w=>{w.key==="Enter"&&(w.preventDefault(),h())}}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary",onClick:h,disabled:o||!c.trim(),children:"Add Type"})]})]})}function Pc({value:e,onChange:t,options:n,placeholder:r="Filter",disabled:o}){const[a,i]=k.useState(!1),c=k.useRef(null),d=n.find(f=>f.value===e)?.label||r;return k.useEffect(()=>{const f=u=>{c.current&&!c.current.contains(u.target)&&i(!1)};if(a)return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[a]),k.useEffect(()=>{const f=u=>{u.key==="Escape"&&i(!1)};if(a)return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[a]),s.jsxs("div",{className:"cedros-admin__dropdown",ref:c,children:[s.jsxs("button",{type:"button",className:"cedros-admin__dropdown-trigger",onClick:()=>!o&&i(!a),"aria-expanded":a,"aria-haspopup":"listbox",disabled:o,children:[s.jsx("span",{children:d}),s.jsx("span",{className:`cedros-admin__dropdown-chevron ${a?"cedros-admin__dropdown-chevron--open":""}`,children:Y.chevronDown})]}),a&&s.jsx("div",{className:"cedros-admin__dropdown-menu",role:"listbox",children:n.map(f=>s.jsxs("button",{type:"button",className:`cedros-admin__dropdown-item ${f.value===e?"cedros-admin__dropdown-item--selected":""}`,onClick:()=>{f.disabled||(t(f.value),i(!1))},role:"option","aria-selected":f.value===e,disabled:f.disabled,children:[f.label,f.value===e&&s.jsx("span",{className:"cedros-admin__dropdown-check",children:Y.check})]},f.value))})]})}function At({value:e,onChange:t,options:n,label:r,description:o,disabled:a,className:i,style:c}){const[l,d]=k.useState(!1),f=k.useRef(null),h=n.find(g=>g.value===e)?.label||"Select...";return k.useEffect(()=>{const g=y=>{f.current&&!f.current.contains(y.target)&&d(!1)};if(l)return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[l]),k.useEffect(()=>{const g=y=>{y.key==="Escape"&&d(!1)};if(l)return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[l]),s.jsxs("div",{className:`cedros-admin__field ${i||""}`,style:c,children:[s.jsx("label",{className:"cedros-admin__field-label",children:r}),s.jsxs("div",{className:"cedros-admin__dropdown cedros-admin__dropdown--form",ref:f,children:[s.jsxs("button",{type:"button",className:"cedros-admin__dropdown-trigger cedros-admin__dropdown-trigger--form",onClick:()=>!a&&d(!l),"aria-expanded":l,"aria-haspopup":"listbox",disabled:a,children:[s.jsx("span",{children:h}),s.jsx("span",{className:`cedros-admin__dropdown-chevron ${l?"cedros-admin__dropdown-chevron--open":""}`,children:Y.chevronDown})]}),l&&s.jsx("div",{className:"cedros-admin__dropdown-menu cedros-admin__dropdown-menu--form",role:"listbox",children:n.map(g=>s.jsxs("button",{type:"button",className:`cedros-admin__dropdown-item ${g.value===e?"cedros-admin__dropdown-item--selected":""}`,onClick:()=>{g.disabled||(t(g.value),d(!1))},role:"option","aria-selected":g.value===e,disabled:g.disabled,children:[g.label,g.value===e&&s.jsx("span",{className:"cedros-admin__dropdown-check",children:Y.check})]},g.value))})]}),o&&s.jsx("p",{className:"cedros-admin__field-description",children:o})]})}function ii(){return`variant_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Wf(e){if(e.length===0)return[];const t=[...e].sort((r,o)=>r.displayOrder-o.displayOrder),n=(r,o)=>{if(r>=t.length){const c=o.valueIds.sort().join("|"),l=Object.values(o.options).join(" / ");return[{key:c,title:l,optionValueIds:[...o.valueIds],options:{...o.options}}]}const a=t[r],i=[];for(const c of a.values)i.push(...n(r+1,{valueIds:[...o.valueIds,c.id],options:{...o.options,[a.name]:c.label}}));return i};return n(0,{valueIds:[],options:{}})}function Hf(e){return e.optionValueIds?.length?[...e.optionValueIds].sort().join("|"):Object.entries(e.options).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${t}:${n}`).join("|")}function Zf({variationConfig:e,variants:t,onChange:n,defaultPrice:r=0,currencySymbol:o="$",maxVariants:a=100,disabled:i=!1}){const c=k.useMemo(()=>Wf(e.variationTypes),[e.variationTypes]),l=k.useMemo(()=>{const x=new Map;for(const p of t)x.set(Hf(p),p);return x},[t]),{existingRows:d,possibleRows:f}=k.useMemo(()=>{const x=[],p=[];for(const v of c){const _=l.get(v.key);_?x.push({combo:v,variant:_}):p.push(v)}return{existingRows:x,possibleRows:p}},[c,l]),u=k.useCallback((x,p)=>{n(t.map(v=>v.id===x?{...v,...p}:v))},[t,n]),h=k.useCallback(x=>{n(t.filter(p=>p.id!==x))},[t,n]),g=k.useCallback(x=>{if(t.length>=a)return;const p={id:ii(),title:x.title,options:x.options,optionValueIds:x.optionValueIds,price:r,inventoryQuantity:0,inventoryStatus:"in_stock",autoGenerated:!1};n([...t,p])},[t,n,a,r]),y=k.useCallback(()=>{const x=a-t.length,v=f.slice(0,x).map(_=>({id:ii(),title:_.title,options:_.options,optionValueIds:_.optionValueIds,price:r,inventoryQuantity:0,inventoryStatus:"in_stock",autoGenerated:!0}));n([...t,...v])},[t,n,f,a,r]);return e.variationTypes.length===0?s.jsx("div",{className:"cedros-admin__variant-grid-empty",children:"Add variation types above to create product variants."}):c.length===0?s.jsx("div",{className:"cedros-admin__variant-grid-empty",children:"Add values to your variation types to create product variants."}):s.jsxs("div",{className:"cedros-admin__variant-grid",children:[s.jsxs("div",{className:"cedros-admin__variant-grid-header",children:[s.jsx("h4",{className:"cedros-admin__field-label",style:{marginBottom:0},children:"Variants"}),s.jsxs("span",{style:{fontSize:12,opacity:.7},children:[t.length,"/",a," variants (",c.length," ","possible)"]})]}),f.length>0&&t.length<a&&s.jsxs("div",{className:"cedros-admin__variant-grid-actions",children:[s.jsxs("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary",onClick:y,disabled:i,children:["Generate All (",Math.min(f.length,a-t.length),")"]}),s.jsx("span",{style:{fontSize:11,opacity:.7},children:"Creates variants with default price and 0 inventory"})]}),s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table cedros-admin__variant-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Variant"}),s.jsx("th",{style:{width:100},children:"Price"}),s.jsx("th",{style:{width:80},children:"Qty"}),s.jsx("th",{style:{width:100},children:"SKU"}),s.jsx("th",{style:{width:100},children:"Status"}),s.jsx("th",{style:{width:80},children:"Actions"})]})}),s.jsxs("tbody",{children:[d.map(({combo:x,variant:p})=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[s.jsx("span",{style:{fontWeight:600},children:x.title}),s.jsx("span",{style:{fontSize:11,opacity:.6},children:Object.entries(x.options).map(([v,_])=>`${v}: ${_}`).join(", ")})]})}),s.jsx("td",{children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[s.jsx("span",{children:o}),s.jsx("input",{type:"number",className:"cedros-admin__input cedros-admin__input--sm",value:p.price??"",onChange:v=>u(p.id,{price:v.target.value===""?void 0:parseFloat(v.target.value)||0}),disabled:i,min:"0",step:"0.01",style:{width:70}})]})}),s.jsx("td",{children:s.jsx("input",{type:"number",className:"cedros-admin__input cedros-admin__input--sm",value:p.inventoryQuantity??"",onChange:v=>u(p.id,{inventoryQuantity:v.target.value===""?void 0:parseInt(v.target.value)||0}),disabled:i,min:"0",style:{width:60}})}),s.jsx("td",{children:s.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:p.sku??"",onChange:v=>u(p.id,{sku:v.target.value||void 0}),disabled:i,placeholder:"SKU",style:{width:80}})}),s.jsx("td",{children:s.jsx(Pc,{value:p.inventoryStatus??"in_stock",onChange:v=>u(p.id,{inventoryStatus:v}),options:[{value:"in_stock",label:"In stock"},{value:"low",label:"Low"},{value:"out_of_stock",label:"Out of stock"},{value:"backorder",label:"Backorder"}],disabled:i})}),s.jsx("td",{children:s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon cedros-admin__button--danger",onClick:()=>h(p.id),disabled:i,title:"Remove variant",children:Y.trash})})]},p.id)),f.length>0&&t.length<a&&s.jsxs(s.Fragment,{children:[s.jsx("tr",{className:"cedros-admin__variant-separator",children:s.jsx("td",{colSpan:6,children:s.jsxs("span",{style:{fontSize:11,opacity:.6},children:["Uncreated combinations (",f.length,")"]})})}),f.slice(0,10).map(x=>s.jsxs("tr",{className:"cedros-admin__variant-possible",children:[s.jsx("td",{children:s.jsx("span",{style:{opacity:.6},children:x.title})}),s.jsx("td",{colSpan:4,style:{opacity:.5},children:"Not created"}),s.jsx("td",{children:s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>g(x),disabled:i,title:"Create variant",children:Y.plus})})]},x.key)),f.length>10&&s.jsx("tr",{className:"cedros-admin__variant-more",children:s.jsxs("td",{colSpan:6,style:{textAlign:"center",opacity:.6},children:["+",f.length-10," more combinations"]})})]})]})]})})]})}function qf({serverUrl:e,productId:t,productTitle:n,defaultPrice:r=0,currencySymbol:o="$",apiKey:a,authManager:i,onClose:c}){const{data:l,isLoading:d,error:f,fetch:u,save:h,isSaving:g}=Bf({serverUrl:e,productId:t,apiKey:a,authManager:i}),[y,x]=k.useState({variationTypes:[]}),[p,v]=k.useState([]),[_,w]=k.useState(!1),[b,j]=k.useState(!1);k.useEffect(()=>{u()},[u]),k.useEffect(()=>{l&&(x(l.variationConfig),v(l.variants),w(!1))},[l]);const R=k.useCallback(E=>{x(E),w(!0),j(!1)},[]),I=k.useCallback(E=>{v(E),w(!0),j(!1)},[]),C=k.useCallback(async()=>{const E=new Set((l?.variants??[]).map(D=>D.id)),O=p.filter(D=>!E.has(D.id)),F=p.filter(D=>E.has(D.id)),M=(l?.variants??[]).filter(D=>!p.some(H=>H.id===D.id)).map(D=>D.id);await h({variationConfig:y,createVariants:O.map(D=>({optionValueIds:D.optionValueIds??[],inventoryQuantity:D.inventoryQuantity,sku:D.sku,price:D.price})),updateVariants:F.map(D=>({id:D.id,inventoryQuantity:D.inventoryQuantity,sku:D.sku,price:D.price,inventoryStatus:D.inventoryStatus})),deleteVariantIds:M.length>0?M:void 0})&&(w(!1),j(!0),setTimeout(()=>j(!1),3e3))},[y,p,l?.variants,h]);return d?s.jsxs("div",{className:"cedros-admin__variations-editor",children:[s.jsxs("div",{className:"cedros-admin__variations-editor-header",children:[s.jsx("h3",{className:"cedros-admin__section-title",children:n?`Variations: ${n}`:"Product Variations"}),c&&s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:c,children:Y.close})]}),s.jsxs("div",{className:"cedros-admin__loading",children:[Y.loading," Loading variations..."]})]}):s.jsxs("div",{className:"cedros-admin__variations-editor",children:[s.jsxs("div",{className:"cedros-admin__variations-editor-header",children:[s.jsx("h3",{className:"cedros-admin__section-title",children:n?`Variations: ${n}`:"Product Variations"}),s.jsxs("div",{className:"cedros-admin__variations-editor-actions",children:[b&&s.jsxs("span",{className:"cedros-admin__success-text",children:[Y.check," Saved"]}),_&&s.jsx("span",{className:"cedros-admin__unsaved-text",children:"Unsaved changes"}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--primary",onClick:C,disabled:g||!_,children:g?"Saving...":"Save Changes"}),c&&s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:c,children:Y.close})]})]}),f&&s.jsx("div",{className:"cedros-admin__error-banner",children:f}),s.jsxs("div",{className:"cedros-admin__variations-editor-content",children:[s.jsx("div",{className:"cedros-admin__variations-editor-section",children:s.jsx(Vf,{value:y,onChange:R,disabled:g})}),y.variationTypes.length>0&&s.jsx("div",{className:"cedros-admin__variations-editor-section",children:s.jsx(Zf,{variationConfig:y,variants:p,onChange:I,defaultPrice:r,currencySymbol:o,disabled:g})})]})]})}function Rc({serverUrl:e,apiKey:t,pageSize:n=20,authManager:r}){const[o,a]=k.useState([]),[i,c]=k.useState(!0),[l,d]=k.useState(!1),[f,u]=k.useState(!1),[h,g]=k.useState(null),[y,x]=k.useState(null),[p,v]=k.useState(null),[_,w]=k.useState(null),[b,j]=k.useState({id:"",title:"",slug:"",imageUrl:"",description:"",productType:"one_time",priceUsd:"",fiatCurrency:"usd",cryptoToken:"USDC",inventoryStatus:"in_stock",compareAtUsd:"",tagsCsv:"",categoryIdsCsv:"",checkoutEmail:"required",checkoutName:"optional",checkoutPhone:"none",checkoutShippingAddress:!1,checkoutBillingAddress:!1,fulfillmentType:"shipping",fulfillmentNotes:"",shippingCountriesCsv:"",inventoryQuantity:""}),R=A=>{const N=A.tagsCsv.split(",").map(q=>q.trim()).filter(Boolean),Z=A.categoryIdsCsv.split(",").map(q=>q.trim()).filter(Boolean),te={email:A.checkoutEmail,name:A.checkoutName,phone:A.checkoutPhone,shippingAddress:A.checkoutShippingAddress,billingAddress:A.checkoutBillingAddress},re=A.fulfillmentType==="shipping"?"physical":"digital",de={title:A.title,slug:A.slug||A.id,shipping_profile:re,inventory_status:A.inventoryStatus,checkout_requirements:JSON.stringify(te),fulfillment_type:A.fulfillmentType};A.imageUrl&&(de.image_url=A.imageUrl);const W=A.compareAtUsd?Math.round(Number(A.compareAtUsd)*100):0;W&&(de.compare_at_amount_cents=String(W)),N.length&&(de.tags=JSON.stringify(N)),Z.length&&(de.category_ids=JSON.stringify(Z)),A.fulfillmentNotes&&(de.fulfillment_notes=A.fulfillmentNotes);const Q=A.shippingCountriesCsv.split(",").map(q=>q.trim().toUpperCase()).filter(Boolean);return Q.length&&(de.shippingCountries=Q.join(","),de.shipping_countries=Q.join(",")),de},I=A=>A.metadata?.title||A.description||A.id,C=A=>A.metadata?.image_url,E=k.useCallback(async()=>{try{w(null);let A;if(r?.isAuthenticated())A=await r.fetchWithAuth(`/admin/products?limit=${n}`);else{const N={"Content-Type":"application/json"};t&&(N["X-API-Key"]=t);const Z=await fetch(`${e}/admin/products?limit=${n}`,{headers:N});if(!Z.ok)throw new Error(`Failed to fetch products: ${Z.status}`);A=await Z.json()}a(A.products||[])}catch{a([]),w("Failed to load products")}finally{c(!1)}},[e,t,n,r]);k.useEffect(()=>{E()},[E]);const O=async A=>{if(A.preventDefault(),!(!b.id||!b.description)){if(g(null),b.fulfillmentType==="shipping"&&b.checkoutShippingAddress&&!b.shippingCountriesCsv.split(",").map(Z=>Z.trim()).filter(Boolean).length){g("Shipping countries are required when collecting shipping address. Example: US,CA");return}u(!0);try{const{productType:N}=b,Z=b.inventoryQuantity===""?void 0:Number.isFinite(Number(b.inventoryQuantity))?Number(b.inventoryQuantity):void 0,te=Number(b.priceUsd)||0,re=Math.round(te*100),de=Math.round(te*1e6),W={id:b.id,description:b.description,fiatAmountCents:re,fiatCurrency:b.fiatCurrency,cryptoAtomicAmount:de,cryptoToken:b.cryptoToken,...Z!==void 0?{inventoryQuantity:Z}:{},metadata:{...N?{product_type:N}:{},...R(b)}};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/products",{method:"POST",body:JSON.stringify(W)});else{const Q={"Content-Type":"application/json"};t&&(Q["X-API-Key"]=t);const q=await fetch(`${e}/admin/products`,{method:"POST",headers:Q,body:JSON.stringify(W)});if(!q.ok)throw new Error(`Failed to create product: ${q.status}`)}j({id:"",title:"",slug:"",imageUrl:"",description:"",productType:"one_time",priceUsd:"",fiatCurrency:"usd",cryptoToken:"USDC",inventoryStatus:"in_stock",compareAtUsd:"",tagsCsv:"",categoryIdsCsv:"",checkoutEmail:"required",checkoutName:"optional",checkoutPhone:"none",checkoutShippingAddress:!1,checkoutBillingAddress:!1,fulfillmentType:"shipping",fulfillmentNotes:"",shippingCountriesCsv:"",inventoryQuantity:""}),d(!1),E()}catch(N){g(N instanceof Error?N.message:"Failed to create product")}finally{u(!1)}}},F=A=>`$${(A/100).toFixed(2)}`,M=A=>{switch(A){case"subscription":return"Subscription";case"pay_per_access":return"Pay per access";case"one_time":return"One-time purchase";default:return"One-time purchase"}},U=k.useMemo(()=>{const A=o.filter(Z=>Z.active).length,N=o.reduce((Z,te)=>{const re=te.variations?.length??0;return Z+(re>0?re:1)},0);return{activeCount:A,totalSkus:N}},[o]),D=A=>{v(N=>!N||N.key!==A?{key:A,direction:"asc"}:{key:A,direction:N.direction==="asc"?"desc":"asc"})},H=A=>!p||p.key!==A?s.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Y.chevronUp}):s.jsx("span",{className:"cedros-admin__sort-icon",children:p.direction==="asc"?Y.chevronUp:Y.chevronDown}),z=k.useMemo(()=>{if(!p)return o;const A=p.direction==="asc"?1:-1,N=Z=>{switch(p.key){case"product":return I(Z);case"type":return M(Z.metadata?.product_type);case"price":return Z.fiatAmountCents??0;case"status":return Z.active?1:0;case"id":default:return Z.id}};return[...o].sort((Z,te)=>{const re=N(Z),de=N(te);return typeof re=="number"&&typeof de=="number"?(re-de)*A:String(re).localeCompare(String(de),void 0,{sensitivity:"base"})*A})},[o,p]);return s.jsxs("div",{className:"cedros-admin__page",children:[s.jsx(jr,{message:_,onRetry:E}),s.jsx(Sr,{stats:[{label:"Total Products",value:o.length},{label:"Active",value:U.activeCount,variant:U.activeCount>0?"success":"muted"},{label:"Total SKUs",value:U.totalSkus}],isLoading:i}),s.jsxs("div",{className:"cedros-admin__section-header",children:[s.jsx("h3",{className:"cedros-admin__section-title",children:"Paywall Products"}),s.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:()=>{g(null),d(!l)},children:[l?Y.close:Y.plus,l?"Cancel":"Add Product"]})]}),l&&s.jsxs("form",{onSubmit:O,className:"cedros-admin__add-form",children:[h&&s.jsx("div",{style:{marginBottom:"0.75rem",color:"#B42318",fontWeight:600},children:h}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Product ID"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:b.id,onChange:A=>j(N=>({...N,id:A.target.value})),placeholder:"e.g., premium-article",required:!0})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Product name"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:b.title,onChange:A=>j(N=>({...N,title:A.target.value})),placeholder:"e.g., Cedros Hoodie"})]})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Slug"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:b.slug,onChange:A=>j(N=>({...N,slug:A.target.value})),placeholder:"e.g., cedros-hoodie (defaults to ID)"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Primary image URL"}),s.jsx("input",{type:"url",className:"cedros-admin__input",value:b.imageUrl,onChange:A=>j(N=>({...N,imageUrl:A.target.value})),placeholder:"https://..."})]})]}),s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Short description"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:b.description,onChange:A=>j(N=>({...N,description:A.target.value})),placeholder:"e.g., Midweight fleece with relaxed fit",required:!0})]})}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsx(At,{value:b.productType,onChange:A=>j(N=>({...N,productType:A})),options:[{value:"one_time",label:"One-time purchase"},{value:"pay_per_access",label:"Pay per access"},{value:"subscription",label:"Subscription"}],label:"Product Type"}),s.jsx(At,{value:b.fulfillmentType,onChange:A=>{const N=A;j(Z=>({...Z,fulfillmentType:N,checkoutShippingAddress:N==="shipping"?Z.checkoutShippingAddress:!1}))},options:[{value:"shipping",label:"Physical (shipped)"},{value:"digital_download",label:"Digital download"},{value:"service",label:"Service"}],label:"Fulfillment"})]}),b.fulfillmentType==="shipping"&&s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsx(At,{value:b.inventoryStatus,onChange:A=>j(N=>({...N,inventoryStatus:A})),options:[{value:"in_stock",label:"In stock"},{value:"low",label:"Low"},{value:"out_of_stock",label:"Out of stock"},{value:"backorder",label:"Backorder"}],label:"Inventory status"}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Inventory quantity (tracked)"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:b.inventoryQuantity,onChange:A=>j(N=>({...N,inventoryQuantity:A.target.value===""?"":parseInt(A.target.value)||0})),placeholder:"Leave blank for untracked",min:"0"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Compare-at price (USD)"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:b.compareAtUsd===""?"":b.compareAtUsd,onChange:A=>j(N=>({...N,compareAtUsd:A.target.value===""?"":parseFloat(A.target.value)||0})),placeholder:"e.g., 78.00",min:"0",step:"0.01"})]})]}),s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Price (USD)"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:b.priceUsd===""?"":b.priceUsd,onChange:A=>j(N=>({...N,priceUsd:A.target.value===""?"":parseFloat(A.target.value)||0})),placeholder:"e.g., 5.00",min:"0",step:"0.01",required:!0})]})}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Tags (comma-separated)"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:b.tagsCsv,onChange:A=>j(N=>({...N,tagsCsv:A.target.value})),placeholder:"e.g., core, new, gift"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Category IDs (comma-separated)"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:b.categoryIdsCsv,onChange:A=>j(N=>({...N,categoryIdsCsv:A.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"})]})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsx(At,{value:b.checkoutEmail,onChange:A=>j(N=>({...N,checkoutEmail:A})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Email"}),s.jsx(At,{value:b.checkoutName,onChange:A=>j(N=>({...N,checkoutName:A})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Name"}),s.jsx(At,{value:b.checkoutPhone,onChange:A=>j(N=>({...N,checkoutPhone:A})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Phone"})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[b.fulfillmentType==="shipping"&&s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Checkout: Shipping address"}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:b.checkoutShippingAddress,onChange:A=>j(N=>({...N,checkoutShippingAddress:A.target.checked}))}),"Collect shipping address"]})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Checkout: Billing address"}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:b.checkoutBillingAddress,onChange:A=>j(N=>({...N,checkoutBillingAddress:A.target.checked}))}),"Collect billing address"]})]})]}),s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Fulfillment notes"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:b.fulfillmentNotes,onChange:A=>j(N=>({...N,fulfillmentNotes:A.target.value})),placeholder:b.fulfillmentType==="shipping"?"e.g., Ships within 3-5 business days":"e.g., Downloadable from your account after purchase"})]})}),b.fulfillmentType==="shipping"&&b.checkoutShippingAddress&&s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Shipping countries"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:b.shippingCountriesCsv,onChange:A=>j(N=>({...N,shippingCountriesCsv:A.target.value})),placeholder:"e.g., US,CA"}),s.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"ISO 2-letter country codes, comma-separated. Required for shipping address collection."})]})}),s.jsx("div",{className:"cedros-admin__form-actions",children:s.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:f,children:f?"Creating...":"Create Product"})})]}),i?s.jsxs("div",{className:"cedros-admin__loading",children:[Y.loading," Loading products..."]}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":p?.key==="id"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>D("id"),children:["ID",H("id")]})}),s.jsx("th",{"aria-sort":p?.key==="product"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>D("product"),children:["Product",H("product")]})}),s.jsx("th",{"aria-sort":p?.key==="type"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>D("type"),children:["Type",H("type")]})}),s.jsx("th",{"aria-sort":p?.key==="price"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>D("price"),children:["Price",H("price")]})}),s.jsx("th",{"aria-sort":p?.key==="status"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>D("status"),children:["Status",H("status")]})}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:z.map(A=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:A.id})}),s.jsx("td",{children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[C(A)?s.jsx("img",{src:C(A),alt:"",style:{width:28,height:28,borderRadius:6,objectFit:"cover"}}):s.jsx("div",{style:{width:28,height:28,borderRadius:6,background:"rgba(0,0,0,0.06)"}}),s.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[s.jsx("span",{style:{fontWeight:600},children:I(A)}),s.jsx("span",{style:{opacity:.8},children:A.description})]})]})}),s.jsx("td",{children:M(A.metadata?.product_type)}),s.jsx("td",{children:F(A.fiatAmountCents)}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge ${A.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:A.active?"Active":"Inactive"})}),s.jsx("td",{children:s.jsx("div",{style:{display:"flex",gap:"0.25rem"},children:s.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>x(A),children:"Variations"})})})]},A.id))})]})}),y&&s.jsx("div",{className:"cedros-admin__modal-overlay",onClick:()=>x(null),children:s.jsx("div",{className:"cedros-admin__modal cedros-admin__modal--lg",onClick:A=>A.stopPropagation(),children:s.jsx(qf,{serverUrl:e,productId:y.id,productTitle:I(y),defaultPrice:y.fiatAmountCents/100,apiKey:t,authManager:r,onClose:()=>x(null)})})})]})}function Oc({serverUrl:e,apiKey:t,pageSize:n=20,authManager:r}){const[o,a]=k.useState([]),[i,c]=k.useState(null),[l,d]=k.useState(!0),[f,u]=k.useState(!0),[h,g]=k.useState(null),[y,x]=k.useState(""),[p,v]=k.useState(null),_=k.useCallback(async()=>{u(!0);try{g(null);let C;if(r?.isAuthenticated())C=await r.fetchWithAuth("/admin/stats");else{const E={"Content-Type":"application/json"};t&&(E["X-API-Key"]=t);const O=await fetch(`${e}/admin/stats`,{headers:E});if(!O.ok)throw new Error(`Failed to fetch stats: ${O.status}`);C=await O.json()}c(C)}catch{c(null),g("Failed to load payment stats")}finally{u(!1)}},[e,t,r]);k.useEffect(()=>{_()},[_]);const w=k.useCallback(async()=>{try{g(null);let C;const E=new URLSearchParams({limit:n.toString()});y&&E.set("method",y);const O=`/admin/transactions?${E}`;if(r?.isAuthenticated())C=await r.fetchWithAuth(O);else{const F={"Content-Type":"application/json"};t&&(F["X-API-Key"]=t);const M=await fetch(`${e}${O}`,{headers:F});if(!M.ok)throw new Error(`Failed to fetch transactions: ${M.status}`);C=await M.json()}a(C.transactions||[])}catch{a([]),g("Failed to load transactions")}finally{d(!1)}},[e,t,n,y,r]);k.useEffect(()=>{w()},[w]);const b=(C,E="USD")=>new Intl.NumberFormat("en-US",{style:"currency",currency:E}).format(C),j=C=>{v(E=>!E||E.key!==C?{key:C,direction:"asc"}:{key:C,direction:E.direction==="asc"?"desc":"asc"})},R=C=>!p||p.key!==C?s.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Y.chevronUp}):s.jsx("span",{className:"cedros-admin__sort-icon",children:p.direction==="asc"?Y.chevronUp:Y.chevronDown}),I=k.useMemo(()=>{if(!p)return o;const C=p.direction==="asc"?1:-1,E=O=>{switch(p.key){case"resource":return O.resourceId;case"method":return O.method;case"amount":return O.amount;case"status":return O.status;case"date":return new Date(O.paidAt).getTime();case"id":default:return O.id}};return[...o].sort((O,F)=>{const M=E(O),U=E(F);return typeof M=="number"&&typeof U=="number"?(M-U)*C:String(M).localeCompare(String(U),void 0,{sensitivity:"base"})*C})},[o,p]);return s.jsxs("div",{className:"cedros-admin__page",children:[s.jsx(jr,{message:h,onRetry:()=>{_(),w()}}),s.jsx(Sr,{stats:[{label:"Revenue",value:b(i?.totalRevenue??0)},{label:"Orders",value:i?.totalTransactions??0},{label:"Card",value:b(i?.revenueByMethod.stripe??0),description:`${i?.transactionsByMethod.stripe??0} orders`},{label:"Crypto",value:b(i?.revenueByMethod.x402??0),description:`${i?.transactionsByMethod.x402??0} orders`},{label:"Credits",value:b(i?.revenueByMethod.credits??0),description:`${i?.transactionsByMethod.credits??0} orders`}],isLoading:f,onRefresh:_}),s.jsxs("div",{className:"cedros-admin__section-header",children:[s.jsx("h3",{className:"cedros-admin__section-title",children:"Transaction History"}),s.jsx(Pc,{value:y,onChange:x,options:[{value:"",label:"All"},{value:"stripe",label:"Card"},{value:"x402",label:"Crypto"},{value:"credits",label:"Credits"}]})]}),l?s.jsxs("div",{className:"cedros-admin__loading",children:[Y.loading," Loading transactions..."]}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":p?.key==="id"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("id"),children:["ID",R("id")]})}),s.jsx("th",{"aria-sort":p?.key==="resource"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("resource"),children:["Resource",R("resource")]})}),s.jsx("th",{"aria-sort":p?.key==="method"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("method"),children:["Method",R("method")]})}),s.jsx("th",{"aria-sort":p?.key==="amount"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("amount"),children:["Amount",R("amount")]})}),s.jsx("th",{"aria-sort":p?.key==="status"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("status"),children:["Status",R("status")]})}),s.jsx("th",{"aria-sort":p?.key==="date"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("date"),children:["Date",R("date")]})})]})}),s.jsx("tbody",{children:I.map(C=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:C.id})}),s.jsx("td",{children:C.resourceId}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${C.method}`,children:C.method})}),s.jsxs("td",{children:["$",C.amount.toFixed(2)," ",C.currency.toUpperCase()]}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${C.status}`,children:C.status})}),s.jsx("td",{children:lr(C.paidAt)})]},C.id))})]})})]})}function Mc({serverUrl:e,apiKey:t,pageSize:n=20,authManager:r}){const[o,a]=k.useState([]),[i,c]=k.useState(!0),[l,d]=k.useState(!1),[f,u]=k.useState(!1),[h,g]=k.useState(null),[y,x]=k.useState(null),[p,v]=k.useState({code:"",discountType:"percentage",discountValue:0,usageLimit:void 0,expiresAt:"",scope:"all_products",productIdsCsv:"",categoryIdsCsv:"",paymentMethod:"any",autoApply:!1,appliesAt:"both",startsAt:"",minimumAmountUsd:"",usageLimitPerCustomer:void 0,firstPurchaseOnly:!1}),_=k.useCallback(async()=>{try{x(null);let E;const O=`/admin/coupons?limit=${n}`;if(r?.isAuthenticated())E=await r.fetchWithAuth(O);else{const F={"Content-Type":"application/json"};t&&(F["X-API-Key"]=t);const M=await fetch(`${e}${O}`,{headers:F});if(!M.ok)throw new Error(`Failed to fetch coupons: ${M.status}`);E=await M.json()}a(E.coupons||[])}catch(E){Je.getLogger().error("[CouponsSection] Failed to fetch coupons:",E,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),a([]),x("Failed to load coupons")}finally{c(!1)}},[e,t,n,r]);k.useEffect(()=>{_()},[_]);const w=async E=>{if(E.preventDefault(),!(!p.code||p.discountValue<=0)){u(!0);try{const O=p.minimumAmountUsd?Math.round(Number(p.minimumAmountUsd)*100):void 0,F=p.productIdsCsv.split(",").map(D=>D.trim()).filter(Boolean),M=p.categoryIdsCsv.split(",").map(D=>D.trim()).filter(Boolean),U={code:p.code,discountType:p.discountType,discountValue:p.discountValue,usageLimit:p.usageLimit,active:!0,usageCount:0,scope:p.scope,...F.length?{productIds:F}:{},...M.length?{categoryIds:M}:{},...p.paymentMethod!=="any"?{paymentMethod:p.paymentMethod}:{},...p.autoApply?{autoApply:!0}:{},...p.appliesAt!=="both"?{appliesAt:p.appliesAt}:{},...p.startsAt?{startsAt:p.startsAt}:{},...p.expiresAt?{expiresAt:p.expiresAt}:{},...O?{minimumAmountCents:O}:{},...p.usageLimitPerCustomer?{usageLimitPerCustomer:p.usageLimitPerCustomer}:{},...p.firstPurchaseOnly?{firstPurchaseOnly:!0}:{}};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/coupons",{method:"POST",body:JSON.stringify(U)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const H=await fetch(`${e}/admin/coupons`,{method:"POST",headers:D,body:JSON.stringify(U)});if(!H.ok)throw new Error(`Failed to create coupon: ${H.status}`)}v({code:"",discountType:"percentage",discountValue:0,usageLimit:void 0,expiresAt:"",scope:"all_products",productIdsCsv:"",categoryIdsCsv:"",paymentMethod:"any",autoApply:!1,appliesAt:"both",startsAt:"",minimumAmountUsd:"",usageLimitPerCustomer:void 0,firstPurchaseOnly:!1}),d(!1),_()}catch(O){Je.getLogger().error("[CouponsSection] Failed to add coupon:",O,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),x("Failed to create coupon")}finally{u(!1)}}},b=o.filter(E=>E.active).length,j=o.reduce((E,O)=>E+(O.usageCount??0),0),R=E=>{g(O=>!O||O.key!==E?{key:E,direction:"asc"}:{key:E,direction:O.direction==="asc"?"desc":"asc"})},I=E=>!h||h.key!==E?s.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Y.chevronUp}):s.jsx("span",{className:"cedros-admin__sort-icon",children:h.direction==="asc"?Y.chevronUp:Y.chevronDown}),C=k.useMemo(()=>{if(!h)return o;const E=h.direction==="asc"?1:-1,O=F=>{switch(h.key){case"discount":return F.discountValue??0;case"usage":return F.usageCount??0;case"status":return F.active?1:0;case"code":default:return F.code}};return[...o].sort((F,M)=>{const U=O(F),D=O(M);return typeof U=="number"&&typeof D=="number"?(U-D)*E:String(U).localeCompare(String(D),void 0,{sensitivity:"base"})*E})},[o,h]);return s.jsxs("div",{className:"cedros-admin__page",children:[s.jsx(jr,{message:y,onRetry:_}),s.jsx(Sr,{stats:[{label:"Total Coupons",value:o.length},{label:"Active",value:b,variant:b>0?"success":"muted"},{label:"Redemptions",value:j}],isLoading:i}),s.jsxs("div",{className:"cedros-admin__section-header",children:[s.jsx("h3",{className:"cedros-admin__section-title",children:"Discount Coupons"}),s.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:()=>d(!l),children:[l?Y.close:Y.plus,l?"Cancel":"Add Coupon"]})]}),l&&s.jsxs("form",{onSubmit:w,className:"cedros-admin__add-form",children:[s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Coupon Code"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:p.code,onChange:E=>v(O=>({...O,code:E.target.value.toUpperCase()})),placeholder:"e.g., SAVE20",required:!0})]}),s.jsx(At,{value:p.discountType,onChange:E=>v(O=>({...O,discountType:E})),options:[{value:"percentage",label:"Percentage (%)"},{value:"fixed",label:"Fixed Amount ($)"}],label:"Discount Type"})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsxs("label",{className:"cedros-admin__field-label",children:["Discount Value ",p.discountType==="percentage"?"(%)":"($)"]}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:p.discountValue||"",onChange:E=>v(O=>({...O,discountValue:parseFloat(E.target.value)||0})),placeholder:p.discountType==="percentage"?"e.g., 20":"e.g., 10.00",min:"0",step:p.discountType==="percentage"?"1":"0.01",required:!0})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Usage Limit (optional)"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:p.usageLimit||"",onChange:E=>v(O=>({...O,usageLimit:E.target.value?parseInt(E.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Expiration Date (optional)"}),s.jsx("input",{type:"date",className:"cedros-admin__input",value:p.expiresAt,onChange:E=>v(O=>({...O,expiresAt:E.target.value}))})]})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsx(At,{value:p.scope,onChange:E=>v(O=>({...O,scope:E})),options:[{value:"all_products",label:"All Products"},{value:"specific_products",label:"Specific Products"},{value:"specific_categories",label:"Specific Categories"}],label:"Scope"}),s.jsx(At,{value:p.paymentMethod,onChange:E=>v(O=>({...O,paymentMethod:E})),options:[{value:"any",label:"Any Payment Method"},{value:"stripe",label:"Stripe (Card) Only"},{value:"x402",label:"Crypto (x402) Only"},{value:"credits",label:"Credits Only"}],label:"Payment Method"}),s.jsx(At,{value:p.appliesAt,onChange:E=>v(O=>({...O,appliesAt:E})),options:[{value:"both",label:"Cart & Checkout"},{value:"cart",label:"Cart Only"},{value:"checkout",label:"Checkout Only"}],label:"Applies At"})]}),p.scope==="specific_products"&&s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Product IDs"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:p.productIdsCsv,onChange:E=>v(O=>({...O,productIdsCsv:E.target.value})),placeholder:"e.g., prod_123, prod_456"}),s.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated product IDs this coupon applies to."})]})}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Start Date (optional)"}),s.jsx("input",{type:"date",className:"cedros-admin__input",value:p.startsAt,onChange:E=>v(O=>({...O,startsAt:E.target.value}))})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Auto Apply"}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:p.autoApply,onChange:E=>v(O=>({...O,autoApply:E.target.checked}))}),"Automatically apply when conditions met"]})]})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Minimum Purchase (USD)"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:p.minimumAmountUsd===""?"":p.minimumAmountUsd,onChange:E=>v(O=>({...O,minimumAmountUsd:E.target.value===""?"":parseFloat(E.target.value)||0})),placeholder:"e.g., 50.00",min:"0",step:"0.01"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Per-Customer Limit"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:p.usageLimitPerCustomer||"",onChange:E=>v(O=>({...O,usageLimitPerCustomer:E.target.value?parseInt(E.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"First Purchase Only"}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:p.firstPurchaseOnly,onChange:E=>v(O=>({...O,firstPurchaseOnly:E.target.checked}))}),"New customers only"]})]})]}),p.scope==="specific_categories"&&s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Category IDs"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:p.categoryIdsCsv,onChange:E=>v(O=>({...O,categoryIdsCsv:E.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"}),s.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated category IDs this coupon applies to."})]})}),s.jsx("div",{className:"cedros-admin__form-actions",children:s.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:f,children:f?"Creating...":"Create Coupon"})})]}),i?s.jsxs("div",{className:"cedros-admin__loading",children:[Y.loading," Loading coupons..."]}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":h?.key==="code"?h?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("code"),children:["Code",I("code")]})}),s.jsx("th",{"aria-sort":h?.key==="discount"?h?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("discount"),children:["Discount",I("discount")]})}),s.jsx("th",{"aria-sort":h?.key==="usage"?h?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("usage"),children:["Usage",I("usage")]})}),s.jsx("th",{"aria-sort":h?.key==="status"?h?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("status"),children:["Status",I("status")]})}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:C.map(E=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:E.code})}),s.jsx("td",{children:E.discountType==="percentage"?`${E.discountValue}%`:`$${E.discountValue.toFixed(2)}`}),s.jsxs("td",{children:[E.usageCount,E.usageLimit?` / ${E.usageLimit}`:""]}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge ${E.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:E.active?"Active":"Inactive"})}),s.jsx("td",{children:s.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",children:"Edit"})})]},E.code))})]})})]})}function Lc({serverUrl:e,apiKey:t,pageSize:n=20,authManager:r}){const[o,a]=k.useState([]),[i,c]=k.useState(!0),[l,d]=k.useState(null),[f,u]=k.useState([]),[h,g]=k.useState(!0),[y,x]=k.useState(null),[p,v]=k.useState(null),[_,w]=k.useState([]),[b,j]=k.useState(!0),[R,I]=k.useState(null),[C,E]=k.useState(null),[O,F]=k.useState(null),[M,U]=k.useState(""),[D,H]=k.useState(null),z=k.useCallback(async()=>{try{let T;const K=`/admin/refunds?limit=${n}`;if(r?.isAuthenticated())T=await r.fetchWithAuth(K);else{const se={"Content-Type":"application/json"};t&&(se["X-API-Key"]=t);const ve=await fetch(`${e}${K}`,{headers:se});if(!ve.ok)throw new Error(`Failed to fetch x402 refunds: ${ve.status}`);T=await ve.json()}a(T.refunds||[])}catch(T){Je.getLogger().error("[RefundsSection] Failed to fetch x402 refunds:",T,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),a([]),H("Failed to load x402 refunds")}finally{c(!1)}},[e,t,n,r]);k.useEffect(()=>{z()},[z]);const A=k.useCallback(async()=>{try{let T;const K=`/admin/credits/refund-requests?status=pending&limit=${n}&offset=0`;if(r?.isAuthenticated())T=await r.fetchWithAuth(K);else{const ve={"Content-Type":"application/json"};t&&(ve["X-API-Key"]=t);const ye=await fetch(`${e}${K}`,{headers:ve});if(!ye.ok)throw new Error(`Failed to fetch credits refund requests: ${ye.status}`);T=await ye.json()}const se=Array.isArray(T)?T:"refundRequests"in T?T.refundRequests:T.requests||[];u(se)}catch(T){Je.getLogger().error("[RefundsSection] Failed to fetch credits refunds:",T,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),u([]),H("Failed to load credits refunds")}finally{g(!1)}},[e,t,n,r]);k.useEffect(()=>{A()},[A]);const N=async T=>{x(T.id);try{const K=`/admin/credits/refund-requests/${T.id}/process`,se=JSON.stringify({amountLamports:T.amountLamports,reason:T.reason});if(r?.isAuthenticated())await r.fetchWithAuth(K,{method:"POST",body:se});else{const ve={"Content-Type":"application/json"};t&&(ve["X-API-Key"]=t);const ye=await fetch(`${e}${K}`,{method:"POST",headers:ve,body:se});if(!ye.ok)throw new Error(`Failed to process credits refund: ${ye.status}`)}await A()}catch(K){Je.getLogger().error("[RefundsSection] Failed to process credits refund:",K,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,requestId:T.id}),H("Failed to process credits refund")}finally{x(null)}},Z=T=>{U(T.reason??""),F(T)},te=()=>{F(null),U("")},re=async()=>{if(!O)return;const T=O,K=M;te(),x(T.id);try{const se=`/admin/credits/refund-requests/${T.id}/reject`,ve=JSON.stringify({reason:K});if(r?.isAuthenticated())await r.fetchWithAuth(se,{method:"POST",body:ve});else{const ye={"Content-Type":"application/json"};t&&(ye["X-API-Key"]=t);const Pe=await fetch(`${e}${se}`,{method:"POST",headers:ye,body:ve});if(!Pe.ok)throw new Error(`Failed to reject credits refund: ${Pe.status}`)}await A()}catch(se){Je.getLogger().error("[RefundsSection] Failed to reject credits refund:",se,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,requestId:T.id}),H("Failed to reject credits refund")}finally{x(null)}},de=k.useCallback(async()=>{try{let T;const K=`/admin/stripe/refunds?limit=${n}`;if(r?.isAuthenticated())T=await r.fetchWithAuth(K);else{const se={"Content-Type":"application/json"};t&&(se["X-API-Key"]=t);const ve=await fetch(`${e}${K}`,{headers:se});if(!ve.ok)throw new Error(`Failed to fetch Stripe refunds: ${ve.status}`);T=await ve.json()}w(T.refunds||[])}catch(T){Je.getLogger().error("[RefundsSection] Failed to fetch Stripe refunds:",T,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),w([]),H("Failed to load Stripe refunds")}finally{j(!1)}},[e,t,n,r]);k.useEffect(()=>{de()},[de]);const W=async T=>{I(T);try{const K=`/admin/stripe/refunds/${T}/process`;if(r?.isAuthenticated())await r.fetchWithAuth(K,{method:"POST"});else{const se={"Content-Type":"application/json"};t&&(se["X-API-Key"]=t);const ve=await fetch(`${e}${K}`,{method:"POST",headers:se});if(!ve.ok)throw new Error(`Failed to process refund: ${ve.status}`)}await de()}catch(K){Je.getLogger().error("[RefundsSection] Failed to process Stripe refund:",K,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,refundId:T}),H("Failed to process Stripe refund")}finally{I(null)}},Q=(T,K)=>new Intl.NumberFormat("en-US",{style:"currency",currency:K}).format(T/100),q=T=>T?T.replace(/_/g," ").replace(/\b\w/g,K=>K.toUpperCase()):"—",he=T=>{switch(T){case"processed":return"success";case"pending":return"pending";case"rejected":default:return"muted"}},P=(T,K)=>K?K.toLowerCase()==="usd"?`${new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(T/1e6)} (USD credits)`:`${T.toLocaleString()} ${K.toUpperCase()} (atomic)`:`${T.toLocaleString()} (atomic)`,G=T=>{switch(T){case"succeeded":return"success";case"failed":return"failed";case"pending":case"requires_action":return"pending";case"canceled":default:return"muted"}},ue=T=>T.stripeRefundId??"—",B=T=>T.chargeId??"—",ae=_.filter(T=>T.status==="pending"||T.status==="requires_action").length,ce=f.filter(T=>T.status==="pending").length,we=o.filter(T=>T.status==="pending").length,Te=ae+ce+we,Ve=_.filter(T=>T.status==="succeeded").reduce((T,K)=>T+K.amount,0),Ge=f.filter(T=>T.status==="processed").reduce((T,K)=>T+K.amountLamports,0),We=o.filter(T=>T.status==="completed").reduce((T,K)=>T+K.amount,0),_t=Ve/100+Ge/1e6+We,Ye=T=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(T),en=b||h||i,xt=T=>{E(K=>!K||K.key!==T?{key:T,direction:"asc"}:{key:T,direction:K.direction==="asc"?"desc":"asc"})},je=T=>{v(K=>!K||K.key!==T?{key:T,direction:"asc"}:{key:T,direction:K.direction==="asc"?"desc":"asc"})},Xe=T=>{d(K=>!K||K.key!==T?{key:T,direction:"asc"}:{key:T,direction:K.direction==="asc"?"desc":"asc"})},_e=(T,K)=>!T||!K?s.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Y.chevronUp}):s.jsx("span",{className:"cedros-admin__sort-icon",children:K==="asc"?Y.chevronUp:Y.chevronDown}),Zt=k.useMemo(()=>{if(!C)return _;const T=C.direction==="asc"?1:-1,K=se=>{switch(C.key){case"stripe":return se.stripeRefundId??"";case"charge":return se.chargeId??"";case"amount":return se.amount??0;case"reason":return se.reason??"";case"status":return se.status??"";case"date":return new Date(se.createdAt).getTime();case"id":default:return se.id}};return[..._].sort((se,ve)=>{const ye=K(se),Pe=K(ve);return typeof ye=="number"&&typeof Pe=="number"?(ye-Pe)*T:String(ye).localeCompare(String(Pe),void 0,{sensitivity:"base"})*T})},[_,C]),ft=k.useMemo(()=>{if(!p)return f;const T=p.direction==="asc"?1:-1,K=se=>{switch(p.key){case"original":return se.originalTransactionId??"";case"user":return se.userId??"";case"amount":return se.amountLamports??0;case"reason":return se.reason??"";case"status":return se.status??"";case"date":return new Date(se.createdAt).getTime();case"id":default:return se.id}};return[...f].sort((se,ve)=>{const ye=K(se),Pe=K(ve);return typeof ye=="number"&&typeof Pe=="number"?(ye-Pe)*T:String(ye).localeCompare(String(Pe),void 0,{sensitivity:"base"})*T})},[f,p]),it=k.useMemo(()=>{if(!l)return o;const T=l.direction==="asc"?1:-1,K=se=>{switch(l.key){case"transaction":return se.transactionId??"";case"amount":return se.amount??0;case"reason":return se.reason??"";case"status":return se.status??"";case"date":return new Date(se.createdAt).getTime();case"id":default:return se.id}};return[...o].sort((se,ve)=>{const ye=K(se),Pe=K(ve);return typeof ye=="number"&&typeof Pe=="number"?(ye-Pe)*T:String(ye).localeCompare(String(Pe),void 0,{sensitivity:"base"})*T})},[o,l]);return s.jsxs("div",{className:"cedros-admin__page",children:[s.jsx(jr,{message:D,onRetry:()=>{z(),A(),de()}}),s.jsx(Sr,{stats:[{label:"Pending",value:Te,variant:Te>0?"warning":"muted"},{label:"Card Pending",value:ae,description:"Stripe"},{label:"Credits Pending",value:ce},{label:"Crypto Pending",value:we,description:"x402"},{label:"Total Refunded",value:Ye(_t),variant:"success"}],isLoading:en}),s.jsx("div",{className:"cedros-admin__section-header",children:s.jsx("h3",{className:"cedros-admin__section-title",children:"Stripe Refund Requests"})}),b?s.jsxs("div",{className:"cedros-admin__loading",children:[Y.loading," Loading Stripe refunds..."]}):_.length===0?s.jsx("div",{className:"cedros-admin__empty",children:"No Stripe refund requests found."}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":C?.key==="id"?C?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("id"),children:["Request ID",_e(C?.key==="id",C?.direction)]})}),s.jsx("th",{"aria-sort":C?.key==="stripe"?C?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("stripe"),children:["Stripe Refund ID",_e(C?.key==="stripe",C?.direction)]})}),s.jsx("th",{"aria-sort":C?.key==="charge"?C?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("charge"),children:["Charge",_e(C?.key==="charge",C?.direction)]})}),s.jsx("th",{"aria-sort":C?.key==="amount"?C?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("amount"),children:["Amount",_e(C?.key==="amount",C?.direction)]})}),s.jsx("th",{"aria-sort":C?.key==="reason"?C?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("reason"),children:["Reason",_e(C?.key==="reason",C?.direction)]})}),s.jsx("th",{"aria-sort":C?.key==="status"?C?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("status"),children:["Status",_e(C?.key==="status",C?.direction)]})}),s.jsx("th",{"aria-sort":C?.key==="date"?C?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("date"),children:["Date",_e(C?.key==="date",C?.direction)]})}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:Zt.map(T=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:T.id})}),s.jsx("td",{children:s.jsx("code",{children:ue(T)})}),s.jsx("td",{children:s.jsx("code",{children:B(T)})}),s.jsx("td",{children:Q(T.amount,T.currency)}),s.jsx("td",{children:q(T.reason)}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${G(T.status)}`,children:T.status})}),s.jsx("td",{children:lr(T.createdAt)}),s.jsx("td",{children:(T.status==="pending"||T.status==="requires_action")&&s.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",onClick:()=>W(T.id),disabled:R===T.id,children:R===T.id?"Processing...":"Process"})})]},T.id))})]})}),s.jsx("div",{className:"cedros-admin__section-header",style:{marginTop:"2rem"},children:s.jsx("h3",{className:"cedros-admin__section-title",children:"Credits Refund Requests"})}),h?s.jsxs("div",{className:"cedros-admin__loading",children:[Y.loading," Loading credits refunds..."]}):f.length===0?s.jsx("div",{className:"cedros-admin__empty",children:"No credits refund requests found."}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":p?.key==="id"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>je("id"),children:["Request ID",_e(p?.key==="id",p?.direction)]})}),s.jsx("th",{"aria-sort":p?.key==="original"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>je("original"),children:["Original Tx",_e(p?.key==="original",p?.direction)]})}),s.jsx("th",{"aria-sort":p?.key==="user"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>je("user"),children:["User",_e(p?.key==="user",p?.direction)]})}),s.jsx("th",{"aria-sort":p?.key==="amount"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>je("amount"),children:["Amount",_e(p?.key==="amount",p?.direction)]})}),s.jsx("th",{"aria-sort":p?.key==="reason"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>je("reason"),children:["Reason",_e(p?.key==="reason",p?.direction)]})}),s.jsx("th",{"aria-sort":p?.key==="status"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>je("status"),children:["Status",_e(p?.key==="status",p?.direction)]})}),s.jsx("th",{"aria-sort":p?.key==="date"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>je("date"),children:["Date",_e(p?.key==="date",p?.direction)]})}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:ft.map(T=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:T.id})}),s.jsx("td",{children:s.jsx("code",{children:T.originalTransactionId})}),s.jsx("td",{children:s.jsx("code",{children:T.userId??"—"})}),s.jsx("td",{children:P(T.amountLamports,T.currency)}),s.jsx("td",{children:T.reason??"—"}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${he(T.status)}`,children:T.status})}),s.jsx("td",{children:lr(T.createdAt)}),s.jsx("td",{children:T.status==="pending"?s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",onClick:()=>N(T),disabled:y===T.id,children:y===T.id?"Processing...":"Process"}),s.jsx("button",{className:"cedros-admin__button cedros-admin__button--outline cedros-admin__button--danger cedros-admin__button--sm",onClick:()=>Z(T),disabled:y===T.id,children:"Reject"})]}):null})]},T.id))})]})}),s.jsx("div",{className:"cedros-admin__section-header",style:{marginTop:"2rem"},children:s.jsx("h3",{className:"cedros-admin__section-title",children:"x402 Refund Requests"})}),i?s.jsxs("div",{className:"cedros-admin__loading",children:[Y.loading," Loading x402 refunds..."]}):o.length===0?s.jsx("div",{className:"cedros-admin__empty",children:"No x402 refund requests found."}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":l?.key==="id"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("id"),children:["ID",_e(l?.key==="id",l?.direction)]})}),s.jsx("th",{"aria-sort":l?.key==="transaction"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("transaction"),children:["Transaction",_e(l?.key==="transaction",l?.direction)]})}),s.jsx("th",{"aria-sort":l?.key==="amount"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("amount"),children:["Amount",_e(l?.key==="amount",l?.direction)]})}),s.jsx("th",{"aria-sort":l?.key==="reason"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("reason"),children:["Reason",_e(l?.key==="reason",l?.direction)]})}),s.jsx("th",{"aria-sort":l?.key==="status"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("status"),children:["Status",_e(l?.key==="status",l?.direction)]})}),s.jsx("th",{"aria-sort":l?.key==="date"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("date"),children:["Date",_e(l?.key==="date",l?.direction)]})}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:it.map(T=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:T.id})}),s.jsx("td",{children:s.jsx("code",{children:T.transactionId})}),s.jsxs("td",{children:["$",T.amount.toFixed(2)]}),s.jsx("td",{children:T.reason||"—"}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${T.status}`,children:T.status})}),s.jsx("td",{children:lr(T.createdAt)}),s.jsx("td",{})]},T.id))})]})}),O&&s.jsx("div",{className:"cedros-admin__modal-overlay",onClick:te,children:s.jsxs("div",{className:"cedros-admin__modal",onClick:T=>T.stopPropagation(),children:[s.jsxs("div",{className:"cedros-admin__modal-header",children:[s.jsx("h3",{className:"cedros-admin__modal-title",children:"Reject Refund Request"}),s.jsx("button",{type:"button",className:"cedros-admin__modal-close",onClick:te,"aria-label":"Close",children:Y.close})]}),s.jsxs("div",{className:"cedros-admin__modal-body",children:[s.jsxs("p",{style:{marginBottom:"1rem",color:"var(--admin-muted)"},children:["Rejecting refund request ",s.jsx("code",{children:O.id})," for ",P(O.amountLamports,O.currency),"."]}),s.jsxs("label",{className:"cedros-admin__form-field",children:[s.jsx("span",{className:"cedros-admin__form-label",children:"Reason (optional)"}),s.jsx("textarea",{className:"cedros-admin__input",value:M,onChange:T=>U(T.target.value),placeholder:"Enter rejection reason...",rows:3,style:{resize:"vertical"}})]})]}),s.jsxs("div",{className:"cedros-admin__modal-footer",children:[s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--outline",onClick:te,children:"Cancel"}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--danger",onClick:re,children:"Reject Refund"})]})]})})]})}const Gf=k.lazy(()=>Promise.resolve().then(()=>require("./SettingsSection-ZrzfLBlS.js")).then(e=>({default:e.SettingsSection})));function Dc(e){return s.jsx(k.Suspense,{fallback:null,children:s.jsx(Gf,{...e})})}class $c{serverUrl;walletSigner=null;jwtToken=null;isAdminUser=!1;constructor(t){this.serverUrl=t}getAuthMethod(){return this.walletSigner?.publicKey&&this.walletSigner.signMessage?"wallet":this.jwtToken&&this.isAdminUser?"cedros-login":"none"}isAuthenticated(){return this.getAuthMethod()!=="none"}setWalletSigner(t){this.walletSigner=t,Je.getLogger().debug("[AdminAuthManager] Wallet signer updated:",!!t?.publicKey)}setCedrosLoginAuth(t,n){this.jwtToken=t,this.isAdminUser=n??!1,Je.getLogger().debug("[AdminAuthManager] Cedros-login auth updated:",{hasToken:!!t,isAdmin:this.isAdminUser})}async createAuthHeaders(t){const n=this.getAuthMethod();if(n==="wallet")return this.createWalletAuthHeaders(t);if(n==="cedros-login")return this.createJwtAuthHeaders();throw new Error("No admin authentication configured. Connect a wallet or sign in as admin.")}async createWalletAuthHeaders(t){if(!this.walletSigner?.publicKey||!this.walletSigner.signMessage)throw new Error("Wallet not connected or does not support message signing");const n=await this.fetchNonce(t),r=new TextEncoder().encode(n.nonce_id),o=await this.walletSigner.signMessage(r),a=oi.bs58.encode(this.walletSigner.publicKey.toBytes()),i=oi.bs58.encode(o);return{"X-Signer":a,"X-Message":n.nonce_id,"X-Signature":i}}createJwtAuthHeaders(){if(!this.jwtToken)throw new Error("No JWT token available");return{Authorization:`Bearer ${this.jwtToken}`}}async fetchNonce(t){const n=`${this.serverUrl}/paywall/v1/nonce`;Je.getLogger().debug("[AdminAuthManager] Fetching nonce for purpose:",t);const r=await Je.fetchWithTimeout(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({purpose:t})});if(!r.ok){const o=await r.text();throw new Error(`Failed to fetch nonce: ${r.status} ${o}`)}return await r.json()}async fetchWithAuth(t,n={}){if(this.getAuthMethod()==="none")throw new Error("No admin authentication configured");const o=this.getPurposeFromPath(t,n.method||"GET"),a=await this.createAuthHeaders(o),i=(n.method||"GET").toUpperCase(),c={...i!=="GET"&&i!=="HEAD"?{"Content-Type":"application/json"}:{},...n.headers||{},...a},l=await Je.fetchWithTimeout(`${this.serverUrl}${t}`,{...n,headers:c});if(!l.ok){let d=`Admin API error ${l.status}`;try{const f=await l.json();f&&typeof f.error=="string"?d=f.error:f&&typeof f.message=="string"&&(d=f.message)}catch{}throw new Error(d)}return await l.json()}getPurposeFromPath(t,n){const o={"/admin/stats":{GET:"admin_stats"},"/admin/products":{GET:"admin_products_list",POST:"admin_products_create"},"/admin/transactions":{GET:"admin_transactions_list"},"/admin/coupons":{GET:"admin_coupons_list",POST:"admin_coupons_create"},"/admin/refunds":{GET:"admin_refunds_list"},"/admin/config":{GET:"admin_config_list"}}[t];if(o?.[n])return o[n];if(t.startsWith("/admin/products/")){if(n==="PUT")return"admin_products_update";if(n==="DELETE")return"admin_products_delete"}if(t.startsWith("/admin/coupons/")){if(n==="PUT")return"admin_coupons_update";if(n==="DELETE")return"admin_coupons_delete"}if(t.startsWith("/admin/refunds/")&&t.includes("/process"))return"admin_refunds_process";if(t.startsWith("/admin/config/")){if(n==="GET")return"admin_config_get";if(n==="PUT")return"admin_config_update";if(n==="PATCH")return"admin_config_patch"}return`admin_${n.toLowerCase()}`}}const Yf={publicKey:null};function Qf({serverUrl:e,cedrosLoginToken:t,isAdmin:n=!1,wallet:r=Yf}){const o=k.useMemo(()=>{const u=new $c(e);return u.setCedrosLoginAuth(t??null,n),u},[e,t,n]);k.useEffect(()=>{r.publicKey&&r.signMessage?o.setWalletSigner({publicKey:r.publicKey,signMessage:r.signMessage}):o.setWalletSigner(null)},[o,r.publicKey,r.signMessage]);const a=o.getAuthMethod(),i=o.isAuthenticated(),c=!!(r.publicKey&&r.signMessage),l=!!t,d=k.useMemo(()=>{if(!r.publicKey)return null;const u=r.publicKey.toBase58();return`${u.slice(0,4)}...${u.slice(-4)}`},[r.publicKey]),f=k.useCallback((u,h)=>o.fetchWithAuth(u,h),[o]);return{authMethod:a,isAuthenticated:i,walletConnected:c,walletAddress:d,cedrosLoginAvailable:l,authManager:o,fetchWithAuth:f}}const Kf=k.lazy(()=>Promise.resolve().then(()=>require("./SubscriptionsSection-fzbL5DGC.js")).then(e=>({default:e.SubscriptionsSection}))),Jf=k.lazy(()=>Promise.resolve().then(()=>require("./StorefrontSection-DGVcJu1T.js")).then(e=>({default:e.StorefrontSection}))),Xf=k.lazy(()=>Promise.resolve().then(()=>require("./AISettingsSection-BXWZcMQT.js")).then(e=>({default:e.AISettingsSection}))),em=k.lazy(()=>Promise.resolve().then(()=>require("./PaymentSettingsSection-B-MRsh1K.js")).then(e=>({default:e.PaymentSettingsSection}))),tm=k.lazy(()=>Promise.resolve().then(()=>require("./MessagingSection-Cld5Q7ZM.js")).then(e=>({default:e.MessagingSection}))),nm=k.lazy(()=>Promise.resolve().then(()=>require("./FAQSection-r6eKjfdO.js")).then(e=>({default:e.FAQSection}))),zc=[{label:"Menu",sections:[{id:"transactions",label:"Transactions",icon:Y.transactions},{id:"products",label:"Products",icon:Y.products},{id:"subscriptions",label:"Subscriptions",icon:Y.calendarRepeat},{id:"coupons",label:"Coupons",icon:Y.coupons},{id:"refunds",label:"Refunds",icon:Y.refunds}]},{label:"Configuration",collapsible:!0,sections:[{id:"storefront",label:"Storefront",icon:Y.storefront},{id:"ai-settings",label:"Store AI",icon:Y.brain},{id:"faqs",label:"Knowledge Base",icon:Y.faq},{id:"payment-settings",label:"Payment Options",icon:Y.creditCard},{id:"messaging",label:"Store Messages",icon:Y.mail},{id:"settings",label:"Store Server",icon:Y.server}]}],rm=zc.flatMap(e=>e.sections);function sm(){const[e,t]=k.useState(()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");return k.useEffect(()=>{const n=window.matchMedia("(prefers-color-scheme: dark)"),r=o=>t(o.matches?"dark":"light");return n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),e}function om(e,t,n){return e!=="system"?e:t||n}function am({serverUrl:e,apiKey:t,title:n="Cedros Pay",sections:r=["transactions","products","subscriptions","coupons","refunds","storefront","ai-settings","faqs","payment-settings","messaging","settings"],defaultSection:o="transactions",refreshInterval:a=3e4,pageSize:i=20,onSectionChange:c,className:l="",cedrosLoginToken:d,isAdmin:f=!1,theme:u="system"}){const[h,g]=k.useState(o),[y]=k.useState(!1),[x,p]=k.useState(new Set),v=k.useCallback(M=>{p(U=>{const D=new Set(U);return D.has(M)?D.delete(M):D.add(M),D})},[]),_=Je.useCedrosThemeOptional(),w=sm(),j=om(u,_?.mode??null,w)==="dark"?"cedros-admin--dark":"",R=zf.useWallet(),{authManager:I,isAuthenticated:C}=Qf({serverUrl:e,cedrosLoginToken:d,isAdmin:f,wallet:R}),E=k.useCallback(M=>{g(M),c?.(M)},[c]),F=rm.filter(M=>r.includes(M.id)).find(M=>M.id===h);return y?s.jsxs("div",{className:`cedros-admin cedros-admin--loading ${j} ${l}`,children:[Y.loading,s.jsx("span",{className:"cedros-admin__loading-text",children:"Loading dashboard..."})]}):C?s.jsxs("div",{className:`cedros-admin ${j} ${l}`,children:[s.jsxs("aside",{className:"cedros-admin__sidebar",children:[s.jsx("div",{className:"cedros-admin__sidebar-header",children:s.jsxs("div",{className:"cedros-admin__logo",children:[Y.wallet,s.jsx("span",{className:"cedros-admin__logo-text",children:n})]})}),s.jsx("nav",{className:"cedros-admin__nav",children:zc.map(M=>{const U=M.sections.filter(H=>r.includes(H.id));if(U.length===0)return null;const D=M.collapsible&&x.has(M.label);return s.jsxs("div",{className:"cedros-admin__nav-group",children:[M.collapsible?s.jsxs("button",{type:"button",className:"cedros-admin__nav-label cedros-admin__nav-label--collapsible",onClick:()=>v(M.label),"aria-expanded":!D,children:[M.label,s.jsx("span",{className:`cedros-admin__nav-label-icon ${D?"":"cedros-admin__nav-label-icon--expanded"}`,children:Y.chevronRight})]}):s.jsx("span",{className:"cedros-admin__nav-label",children:M.label}),!D&&U.map(H=>s.jsxs("button",{type:"button",className:`cedros-admin__nav-item ${h===H.id?"cedros-admin__nav-item--active":""}`,onClick:()=>E(H.id),"aria-current":h===H.id?"page":void 0,children:[s.jsx("span",{className:"cedros-admin__nav-icon",children:H.icon}),s.jsx("span",{className:"cedros-admin__nav-text",children:H.label})]},H.id))]},M.label)})})]}),s.jsxs("main",{className:"cedros-admin__main",children:[s.jsx("header",{className:"cedros-admin__header",children:s.jsxs("div",{className:"cedros-admin__breadcrumb",children:[s.jsx("span",{className:"cedros-admin__breadcrumb-root",children:n}),s.jsx("span",{className:"cedros-admin__breadcrumb-sep",children:Y.chevronRight}),s.jsx("span",{className:"cedros-admin__breadcrumb-current",children:F?.label})]})}),s.jsxs("div",{className:"cedros-admin__content",children:[h==="products"&&s.jsx(Rc,{serverUrl:e,apiKey:t,pageSize:i,authManager:I}),h==="subscriptions"&&s.jsx(k.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(Kf,{serverUrl:e,apiKey:t,authManager:I})}),h==="transactions"&&s.jsx(Oc,{serverUrl:e,apiKey:t,pageSize:i,authManager:I}),h==="coupons"&&s.jsx(Mc,{serverUrl:e,apiKey:t,pageSize:i,authManager:I}),h==="refunds"&&s.jsx(Lc,{serverUrl:e,apiKey:t,pageSize:i,authManager:I}),h==="storefront"&&s.jsx(k.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(Jf,{serverUrl:e,apiKey:t,authManager:I})}),h==="ai-settings"&&s.jsx(k.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(Xf,{serverUrl:e,apiKey:t,authManager:I})}),h==="faqs"&&s.jsx(k.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(nm,{serverUrl:e,apiKey:t,pageSize:i,authManager:I})}),h==="payment-settings"&&s.jsx(k.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(em,{serverUrl:e,apiKey:t,authManager:I})}),h==="messaging"&&s.jsx(k.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(tm,{serverUrl:e,apiKey:t,authManager:I})}),h==="settings"&&s.jsx(Dc,{serverUrl:e,apiKey:t,authManager:I})]})]})]}):s.jsx("div",{className:`cedros-admin cedros-admin--unauthenticated ${j} ${l}`,children:s.jsx("p",{className:"cedros-admin__auth-prompt",children:"Please connect a wallet or sign in as admin to access the dashboard."})})}const kt=e=>k.lazy(async()=>{const r=(await e()).default;return{default:({pluginContext:a})=>{const c=Ff.useCedrosLogin()?._internal?.getAccessToken()??a.getAccessToken(),l=k.useMemo(()=>{const f=new $c(a.serverUrl);return f.setCedrosLoginAuth(c??null,!!c),f},[a.serverUrl,c]),d={serverUrl:a.serverUrl,authManager:l};return s.jsx(r,{...d})}}}),im={id:"cedros-pay",name:"Cedros Pay",version:"1.0.0",sections:[{id:"transactions",label:"Transactions",icon:Y.transactions,group:"Store",order:0},{id:"products",label:"Products",icon:Y.products,group:"Store",order:1},{id:"subscriptions",label:"Subscriptions",icon:Y.subscriptions,group:"Store",order:2},{id:"coupons",label:"Coupons",icon:Y.coupons,group:"Store",order:3},{id:"refunds",label:"Refunds",icon:Y.refunds,group:"Store",order:4},{id:"storefront",label:"Storefront",icon:Y.storefront,group:"Configuration",order:10},{id:"ai-settings",label:"Store AI",icon:Y.ai,group:"Configuration",order:11},{id:"faqs",label:"Knowledge Base",icon:Y.faq,group:"Configuration",order:12},{id:"payment-settings",label:"Payment Options",icon:Y.wallet,group:"Configuration",order:13},{id:"messaging",label:"Store Messages",icon:Y.notifications,group:"Configuration",order:14},{id:"settings",label:"Store Server",icon:Y.settings,group:"Configuration",order:15}],groups:[{id:"Store",label:"Store",order:1},{id:"Configuration",label:"Configuration",order:2,defaultCollapsed:!0}],components:{products:kt(()=>Promise.resolve().then(()=>require("./sections-Dh0qFSUW.js")).then(e=>({default:e.ProductsSection}))),subscriptions:kt(()=>Promise.resolve().then(()=>require("./SubscriptionsSection-fzbL5DGC.js")).then(e=>({default:e.SubscriptionsSection}))),transactions:kt(()=>Promise.resolve().then(()=>require("./sections-Dh0qFSUW.js")).then(e=>({default:e.TransactionsSection}))),coupons:kt(()=>Promise.resolve().then(()=>require("./sections-Dh0qFSUW.js")).then(e=>({default:e.CouponsSection}))),refunds:kt(()=>Promise.resolve().then(()=>require("./sections-Dh0qFSUW.js")).then(e=>({default:e.RefundsSection}))),storefront:kt(()=>Promise.resolve().then(()=>require("./StorefrontSection-DGVcJu1T.js")).then(e=>({default:e.StorefrontSection}))),"ai-settings":kt(()=>Promise.resolve().then(()=>require("./AISettingsSection-BXWZcMQT.js")).then(e=>({default:e.AISettingsSection}))),faqs:kt(()=>Promise.resolve().then(()=>require("./FAQSection-r6eKjfdO.js")).then(e=>({default:e.FAQSection}))),"payment-settings":kt(()=>Promise.resolve().then(()=>require("./PaymentSettingsSection-B-MRsh1K.js")).then(e=>({default:e.PaymentSettingsSection}))),messaging:kt(()=>Promise.resolve().then(()=>require("./MessagingSection-Cld5Q7ZM.js")).then(e=>({default:e.MessagingSection}))),settings:kt(()=>Promise.resolve().then(()=>require("./SettingsSection-ZrzfLBlS.js")).then(e=>({default:e.SettingsSection})))},createPluginContext(e){const t=e.cedrosPay,n=e.cedrosLogin;return{serverUrl:t?.serverUrl||n?.serverUrl||"",userId:n?.user?.id,getAccessToken:()=>n?.getAccessToken?.()||t?.jwtToken||null,hasPermission:o=>this.checkPermission(o,e),orgId:e.org?.orgId,pluginData:{walletAddress:t?.walletAddress}}},checkPermission(e,t){return t.org?.permissions?t.org.permissions.includes(e):!!(t.cedrosLogin?.user||t.cedrosPay?.jwtToken||t.cedrosPay?.walletAddress)},cssNamespace:"cedros-dashboard"},Fc=[{id:"transactions",qualifiedId:"cedros-pay:transactions",label:"Transactions",group:"Store",order:0,endpoints:["GET /admin/transactions"]},{id:"products",qualifiedId:"cedros-pay:products",label:"Products",group:"Store",order:1,endpoints:["GET /admin/products","POST /admin/products","PUT /admin/products/{id}","DELETE /admin/products/{id}"]},{id:"subscriptions",qualifiedId:"cedros-pay:subscriptions",label:"Subscriptions",group:"Store",order:2,endpoints:["GET /admin/subscriptions","POST /admin/subscriptions","PUT /admin/subscriptions/{id}"]},{id:"coupons",qualifiedId:"cedros-pay:coupons",label:"Coupons",group:"Store",order:3,endpoints:["GET /admin/coupons","POST /admin/coupons","PUT /admin/coupons/{id}","DELETE /admin/coupons/{id}"]},{id:"refunds",qualifiedId:"cedros-pay:refunds",label:"Refunds",group:"Store",order:4,endpoints:["GET /admin/refunds","POST /admin/refunds/{id}/approve","POST /admin/refunds/{id}/deny"]},{id:"storefront",qualifiedId:"cedros-pay:storefront",label:"Storefront",group:"Configuration",order:10,endpoints:["GET /admin/config/shop","PUT /admin/config/shop"]},{id:"ai-settings",qualifiedId:"cedros-pay:ai-settings",label:"Store AI",group:"Configuration",order:11,endpoints:["GET /admin/config/ai","PUT /admin/config/ai/api-key","PUT /admin/config/ai/assignment","PUT /admin/config/ai/prompt"]},{id:"faqs",qualifiedId:"cedros-pay:faqs",label:"Knowledge Base",group:"Configuration",order:12,endpoints:["GET /admin/faqs","POST /admin/faqs","PUT /admin/faqs/{id}","DELETE /admin/faqs/{id}"]},{id:"payment-settings",qualifiedId:"cedros-pay:payment-settings",label:"Payment Options",group:"Configuration",order:13,endpoints:["GET /admin/config/stripe","PUT /admin/config/stripe","GET /admin/config/x402","PUT /admin/config/x402","GET /admin/config/cedros_login","PUT /admin/config/cedros_login"]},{id:"messaging",qualifiedId:"cedros-pay:messaging",label:"Store Messages",group:"Configuration",order:14,endpoints:["GET /admin/config/messaging","PUT /admin/config/messaging"]},{id:"settings",qualifiedId:"cedros-pay:settings",label:"Store Server",group:"Configuration",order:15,endpoints:["GET /admin/config/server","PUT /admin/config/server"]}],cm=Fc.map(e=>e.qualifiedId),lm=[{id:"Store",label:"Store",order:1,defaultCollapsed:!1},{id:"Configuration",label:"Configuration",order:2,defaultCollapsed:!0}],qo=k.createContext(null);function Ee(){const e=k.useContext(qo);if(!e)throw new Error("useCedrosShop must be used within CedrosShopProvider");return e}function Go(){return k.useContext(qo)}function dm({config:e,children:t}){const n=k.useMemo(()=>({config:e}),[e]);return s.jsx(qo.Provider,{value:n,children:t})}function jt(e){return new Promise(t=>setTimeout(t,e))}const Uc=[{id:"cat_all",slug:"all",name:"All Products",description:"Everything in the catalog."},{id:"cat_apparel",slug:"apparel",name:"Apparel",description:"Soft goods and daily wear."},{id:"cat_accessories",slug:"accessories",name:"Accessories",description:"Carry, attach, decorate."}],Kr=[{id:"p_tee",slug:"cedros-tee",title:"Cedros Tee",description:"A heavyweight tee with a clean silhouette.",images:[{url:"https://picsum.photos/seed/cedros-tee/900/900",alt:"Cedros Tee"},{url:"https://picsum.photos/seed/cedros-tee-2/900/900",alt:"Cedros Tee detail"}],price:38,currency:"USD",tags:["new","cotton"],categoryIds:["cat_apparel"],compareAtPrice:48,inventoryStatus:"in_stock",variants:[{id:"v_tee_s",title:"Small / Black",options:{Size:"S",Color:"Black"}},{id:"v_tee_m",title:"Medium / Black",options:{Size:"M",Color:"Black"}},{id:"v_tee_l",title:"Large / Black",options:{Size:"L",Color:"Black"}}],shippingProfile:"physical"},{id:"p_crewneck",slug:"cedros-crewneck",title:"Cedros Crewneck",description:"Midweight fleece with a relaxed fit and embroidered mark.",images:[{url:"https://picsum.photos/seed/cedros-crewneck/900/900",alt:"Cedros Crewneck"}],price:64,currency:"USD",tags:["fleece","core"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",compareAtPrice:78,variants:[{id:"v_crew_s",title:"Small / Heather",options:{Size:"S",Color:"Heather"}},{id:"v_crew_m",title:"Medium / Heather",options:{Size:"M",Color:"Heather"}},{id:"v_crew_l",title:"Large / Heather",options:{Size:"L",Color:"Heather"}}],shippingProfile:"physical"},{id:"p_hoodie",slug:"cedros-hoodie",title:"Cedros Hoodie",description:"Pullover hoodie with soft interior and structured hood.",images:[{url:"https://picsum.photos/seed/cedros-hoodie/900/900",alt:"Cedros Hoodie"},{url:"https://picsum.photos/seed/cedros-hoodie-2/900/900",alt:"Cedros Hoodie detail"}],price:74,currency:"USD",tags:["fleece","new"],categoryIds:["cat_apparel"],inventoryStatus:"low",variants:[{id:"v_hoodie_s",title:"Small / Black",options:{Size:"S",Color:"Black"}},{id:"v_hoodie_m",title:"Medium / Black",options:{Size:"M",Color:"Black"}},{id:"v_hoodie_l",title:"Large / Black",options:{Size:"L",Color:"Black"}}],shippingProfile:"physical"},{id:"p_cap",slug:"cedros-cap",title:"Cedros Cap",description:"Unstructured cap with adjustable strap and curved brim.",images:[{url:"https://picsum.photos/seed/cedros-cap/900/900",alt:"Cedros Cap"}],price:28,currency:"USD",tags:["core"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_socks",slug:"cedros-socks",title:"Cedros Socks",description:"Rib-knit socks designed for everyday comfort.",images:[{url:"https://picsum.photos/seed/cedros-socks/900/900",alt:"Cedros Socks"}],price:14,currency:"USD",tags:["cotton"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_tote",slug:"cedros-tote",title:"Cedros Tote",description:"Heavy canvas tote with reinforced handles.",images:[{url:"https://picsum.photos/seed/cedros-tote/900/900",alt:"Cedros Tote"}],price:32,currency:"USD",tags:["gift","canvas"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_stickers",slug:"cedros-sticker-pack",title:"Sticker Pack",description:"Five durable vinyl stickers for laptops and water bottles.",images:[{url:"https://picsum.photos/seed/cedros-stickers/900/900",alt:"Sticker Pack"}],price:8,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_keychain",slug:"cedros-keychain",title:"Enamel Keychain",description:"Polished enamel keychain with a subtle mark.",images:[{url:"https://picsum.photos/seed/cedros-keychain/900/900",alt:"Enamel Keychain"}],price:12,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_lanyard",slug:"cedros-lanyard",title:"Woven Lanyard",description:"Soft woven lanyard with swivel clasp.",images:[{url:"https://picsum.photos/seed/cedros-lanyard/900/900",alt:"Woven Lanyard"}],price:10,currency:"USD",tags:["core"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_notebook",slug:"cedros-notebook",title:"Dot Grid Notebook",description:"Lay-flat notebook for sketches, notes, and plans.",images:[{url:"https://picsum.photos/seed/cedros-notebook/900/900",alt:"Dot Grid Notebook"}],price:18,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_waterbottle",slug:"cedros-water-bottle",title:"Insulated Bottle",description:"Vacuum-insulated bottle that keeps drinks cold for hours.",images:[{url:"https://picsum.photos/seed/cedros-bottle/900/900",alt:"Insulated Bottle"}],price:36,currency:"USD",tags:["gift","new"],categoryIds:["cat_accessories"],inventoryStatus:"backorder",shippingProfile:"physical"},{id:"p_posters",slug:"cedros-poster-set",title:"Poster Set",description:"Two prints on thick matte stock.",images:[{url:"https://picsum.photos/seed/cedros-posters/900/900",alt:"Poster Set"}],price:24,currency:"USD",tags:["gift","limited"],categoryIds:["cat_accessories"],inventoryStatus:"out_of_stock",shippingProfile:"physical"},{id:"p_pins",slug:"cedros-pin-set",title:"Pin Set",description:"Two enamel pins with rubber backings.",images:[{url:"https://picsum.photos/seed/cedros-pins/900/900",alt:"Pin Set"}],price:16,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_brandbook",slug:"cedros-brand-book",title:"Brand Book (PDF)",description:"A compact brand book: typography, color, layout, and voice.",images:[{url:"https://picsum.photos/seed/cedros-brandbook/900/900",alt:"Brand Book cover"}],price:19,currency:"USD",tags:["digital"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital",checkoutRequirements:{email:"optional",name:"none",phone:"none",shippingAddress:!1,billingAddress:!1},fulfillment:{type:"digital_download",notes:"This is a digital product and will be downloadable from your account after purchase."}},{id:"p_wallpaper",slug:"cedros-wallpaper-pack",title:"Wallpaper Pack",description:"A set of desktop + mobile wallpapers in multiple colorways.",images:[{url:"https://picsum.photos/seed/cedros-wallpaper/900/900",alt:"Wallpaper Pack"}],price:6,currency:"USD",tags:["digital","new"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital"},{id:"p_longsleeve",slug:"cedros-long-sleeve",title:"Long Sleeve Tee",description:"Soft long sleeve tee with rib cuff and relaxed drape.",images:[{url:"https://picsum.photos/seed/cedros-longsleeve/900/900",alt:"Long Sleeve Tee"}],price:44,currency:"USD",tags:["cotton"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_shorts",slug:"cedros-shorts",title:"Everyday Shorts",description:"Lightweight shorts with a comfortable waistband.",images:[{url:"https://picsum.photos/seed/cedros-shorts/900/900",alt:"Everyday Shorts"}],price:40,currency:"USD",tags:["new"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_beanie",slug:"cedros-beanie",title:"Rib Beanie",description:"Warm rib beanie with a clean folded cuff.",images:[{url:"https://picsum.photos/seed/cedros-beanie/900/900",alt:"Rib Beanie"}],price:20,currency:"USD",tags:["core"],categoryIds:["cat_apparel"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_jacket",slug:"cedros-coach-jacket",title:"Coach Jacket",description:"Lightweight jacket with snap front and subtle sheen.",images:[{url:"https://picsum.photos/seed/cedros-jacket/900/900",alt:"Coach Jacket"}],price:96,currency:"USD",tags:["limited"],categoryIds:["cat_apparel"],inventoryStatus:"backorder",shippingProfile:"physical"},{id:"p_mug",slug:"cedros-mug",title:"Cedros Mug",description:"Stoneware mug with a satin glaze.",images:[{url:"https://picsum.photos/seed/cedros-mug/900/900",alt:"Cedros Mug"}],price:22,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_guide",slug:"cedros-field-guide",title:"Field Guide (Digital)",description:"A short digital guide to shipping delightful checkout flows.",images:[{url:"https://picsum.photos/seed/cedros-guide/900/900",alt:"Field Guide cover"}],price:12,currency:"USD",tags:["digital"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital"}];function um(e,t){let n=e;if(t.category&&t.category!=="all"){const l=Uc.find(d=>d.slug===t.category||d.id===t.category);l&&(n=n.filter(d=>d.categoryIds.includes(l.id)))}if(t.search){const l=t.search.toLowerCase();n=n.filter(d=>d.title.toLowerCase().includes(l)||d.description.toLowerCase().includes(l))}const r=t.filters??{},o=r.tags;if(Array.isArray(o)&&o.length>0){const l=new Set(o.map(String));n=n.filter(d=>d.tags?.some(f=>l.has(f)))}const a=typeof r.priceMin=="number"?r.priceMin:void 0,i=typeof r.priceMax=="number"?r.priceMax:void 0;return typeof a=="number"&&(n=n.filter(l=>l.price>=a)),typeof i=="number"&&(n=n.filter(l=>l.price<=i)),(typeof r.inStock=="boolean"?r.inStock:void 0)===!0&&(n=n.filter(l=>l.inventoryStatus!=="out_of_stock")),n}function fm(e,t){if(!t||t==="featured")return e;const n=[...e];return t==="price_asc"&&n.sort((r,o)=>r.price-o.price),t==="price_desc"&&n.sort((r,o)=>o.price-r.price),n}function mm(e,t,n){const r=(t-1)*n;return{items:e.slice(r,r+n),page:t,pageSize:n,total:e.length,hasNextPage:r+n<e.length}}function pm(e){const t=new Date().toISOString(),n=e.cart.map(o=>{const a=Kr.find(i=>i.id===o.resource||i.slug===o.resource)??Kr[0];return{title:a.title,qty:o.quantity,unitPrice:a.price,currency:e.options.currency,imageUrl:a.images[0]?.url}}),r=n.reduce((o,a)=>o+a.qty*a.unitPrice,0);return{id:`ord_${Math.random().toString(16).slice(2)}`,createdAt:t,status:"paid",total:r,currency:e.options.currency,items:n,receiptUrl:e.options.successUrl}}function hm(){let e=[];const t={};return{async listProducts(n){await jt(150);const r=n.page??1,o=n.pageSize??24,a=um(Kr,n),i=fm(a,n.sort);return mm(i,r,o)},async getProductBySlug(n){return await jt(100),Kr.find(r=>r.slug===n)??null},async listCategories(){return await jt(80),Uc},async getOrderHistory(){return await jt(120),e},async getCart({customerId:n}){return await jt(80),t[n]??{items:[]}},async mergeCart({customerId:n,cart:r}){await jt(120);const o=t[n]??{items:[]},a=new Map,i=l=>{const d=`${l.productId}::${l.variantId??""}`,f=a.get(d);f?a.set(d,{...f,qty:f.qty+l.qty}):a.set(d,l)};for(const l of o.items)i(l);for(const l of r.items)i(l);const c={items:Array.from(a.values()),promoCode:r.promoCode??o.promoCode};return t[n]=c,c},async updateCart({customerId:n,cart:r}){await jt(60),t[n]=r},async createCheckoutSession(n){await jt(250);const r=pm(n);if(e=[r,...e].slice(0,25),n.options.successUrl){const o=new URL(n.options.successUrl,"http://localhost");return o.searchParams.set("demoOrderId",r.id),{kind:"redirect",url:o.toString().replace("http://localhost","")}}return{kind:"custom",data:{orderId:r.id}}},async listSubscriptionTiers(){return await jt(80),[{id:"tier_starter",title:"Starter",description:"For small shops getting started.",priceMonthly:19,priceAnnual:190,currency:"USD",features:["Basic analytics","Email support","1 storefront"]},{id:"tier_growth",title:"Growth",description:"For teams iterating fast.",priceMonthly:49,priceAnnual:490,currency:"USD",features:["Advanced analytics","Priority support","3 storefronts"],isPopular:!0},{id:"tier_enterprise",title:"Enterprise",description:"For high volume and custom needs.",priceMonthly:199,priceAnnual:1990,currency:"USD",features:["SLA","Dedicated success","Unlimited storefronts"]}]},async getSubscriptionStatus(){return await jt(80),{isActive:!1}},async createSubscriptionCheckoutSession(n){return await jt(200),n.successUrl?{kind:"redirect",url:n.successUrl}:{kind:"custom",data:n}}}}const ci=50,gm=4,xm=5,vm=1e4,ym={maxRetries:2,initialDelayMs:100,backoffFactor:2,maxDelayMs:500,jitter:!1};function Bc(e){return e.replace(/[_-]+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function bm(e){return e?e.toUpperCase():"USD"}function wm(e){if(e&&(e==="in_stock"||e==="low"||e==="out_of_stock"||e==="backorder"))return e}function _m(e){if(e&&(e==="physical"||e==="digital"))return e}function km(e){const t=[];if(Array.isArray(e))for(const n of e)typeof n=="string"&&t.push(n);else if(typeof e=="string"){const n=e.trim();if(n.startsWith("["))try{const r=JSON.parse(n);if(Array.isArray(r))for(const o of r)typeof o=="string"&&t.push(o);else t.push(e)}catch{t.push(e)}else t.push(e)}return t.flatMap(n=>n.split(",")).map(n=>n.trim().toUpperCase()).filter(Boolean)}function Tn(e){const t=bm(e.fiatCurrency),n=e.images&&e.images.length?e.images:e.imageUrl?[{url:e.imageUrl,alt:e.title}]:[],r=e.effectiveFiatAmountCents??e.fiatAmountCents??0,o=e.compareAtAmountCents,a=e.metadata?.shippingCountries??e.metadata?.shipping_countries,i=km(a);return{id:e.id,slug:e.slug??e.id,title:e.title??Bc(e.id),description:e.description??"",images:n,price:r/100,currency:t,tags:e.tags??[],categoryIds:e.categoryIds??[],inventoryStatus:wm(e.inventoryStatus),inventoryQuantity:typeof e.inventoryQuantity=="number"?e.inventoryQuantity:void 0,compareAtPrice:typeof o=="number"?o/100:void 0,shippingProfile:_m(e.shippingProfile),checkoutRequirements:e.checkoutRequirements,fulfillment:e.fulfillment,attributes:i.length?{shippingCountries:i.join(",")}:void 0}}function Hr(e){if(Array.isArray(e))return{products:e};const t=e.products??e.items??[],n=e.total??e.count;return{products:t,total:n}}async function Kt(e,t,n,r={}){const{body:o,headers:a,method:i="GET",retryableRead:c=!1,timeoutMs:l=vm}=r,d={};n&&(d["X-API-Key"]=n),a&&Object.assign(d,a);const f=async()=>{const u=await Je.fetchWithTimeout(`${e}${t}`,{body:o,headers:d,method:i},l);if(!u.ok){const h=await u.text().catch(()=>""),g=new Error(`Request failed (${u.status}): ${h}`);throw g.status=u.status,g}return u.json()};return c?Je.retryWithBackoff(f,{...ym,name:`paywall-read-${i.toLowerCase()}`}):f()}async function jm(e,t,n,r){const o=await Kt(e,`/paywall/v1/products?limit=${n}&offset=${r}`,t,{retryableRead:!0});return Hr(o)}async function li(e,t,n,r){const{maxPages:o,pageSize:a}=n;for(let i=0;i<o;i+=1){const c=i*a,{products:l,total:d}=await jm(e,t,a,c);if(l.length===0||r(l))return;const f=typeof d=="number"&&c+l.length>=d,u=l.length<a;if(f||u)return}}function Sm(e){const t=async d=>{const f=d.page??1,u=d.pageSize??24,h=u,g=(f-1)*u,y=new URLSearchParams;y.set("limit",String(h)),y.set("offset",String(g)),d.search&&y.set("search",d.search),d.category&&y.set("category",d.category),d.sort&&y.set("sort",d.sort),d.filters?.inStock&&y.set("in_stock","true"),d.filters?.minPrice!=null&&y.set("min_price",String(d.filters.minPrice)),d.filters?.maxPrice!=null&&y.set("max_price",String(d.filters.maxPrice));const x=d.filters?.tags,p=Array.isArray(x)?x:typeof x=="string"?[x]:[];p.length&&y.set("tags",p.join(","));const v=await Kt(e.serverUrl,`/paywall/v1/products?${y.toString()}`,e.apiKey,{retryableRead:!0}),{products:_,total:w}=Hr(v);return{items:_.map(Tn),page:f,pageSize:u,total:w,hasNextPage:typeof w=="number"?g+h<w:_.length===h}},n=async d=>{try{const f=await Kt(e.serverUrl,`/paywall/v1/products/by-slug/${encodeURIComponent(d)}`,e.apiKey,{retryableRead:!0});return Tn(f)}catch(f){const u=f?.status;if(u!==404&&u!==405)throw f;try{const h=await Kt(e.serverUrl,`/paywall/v1/products/${encodeURIComponent(d)}`,e.apiKey,{retryableRead:!0});return Tn(h)}catch(h){const g=h?.status;if(g!==404&&g!==405)throw h;let y;return await li(e.serverUrl,e.apiKey,{maxPages:gm,pageSize:ci},x=>(y=x.find(p=>p.slug===d||p.id===d),!!y)),y?Tn(y):null}}};return{listProducts:t,getProductBySlug:n,getProductsByIds:async d=>{const f=Array.from(new Set(d.filter(Boolean)));if(f.length===0)return new Map;const u=new Map;try{const y=new URLSearchParams;y.set("ids",f.join(",")),y.set("limit",String(f.length)),y.set("offset","0");const x=await Kt(e.serverUrl,`/paywall/v1/products?${y.toString()}`,e.apiKey,{retryableRead:!0}),{products:p}=Hr(x);for(const v of p){const _=Tn(v);u.set(_.id,_),_.slug&&_.slug!==_.id&&u.set(_.slug,_)}}catch{}const h=f.filter(y=>!u.has(y));if(h.length===0)return u;let g=h;try{const y=new Set(g);if(await li(e.serverUrl,e.apiKey,{maxPages:xm,pageSize:ci},x=>{for(const p of x){const v=Tn(p);!y.has(v.id)&&!(v.slug&&y.has(v.slug))||(u.set(v.id,v),v.slug&&v.slug!==v.id&&u.set(v.slug,v),y.delete(v.id),v.slug&&y.delete(v.slug))}return y.size===0}),g=Array.from(y),g.length===0)return u}catch{}for(const y of g)try{const x=await n(y);x&&(u.set(x.id,x),x.slug&&x.slug!==x.id&&u.set(x.slug,x))}catch{}return u},listCategories:async()=>{const d=await Kt(e.serverUrl,"/paywall/v1/products?limit=500&offset=0",e.apiKey,{retryableRead:!0}),{products:f}=Hr(d),u=new Set;for(const h of f)for(const g of h.categoryIds??[])u.add(g);return Array.from(u).map(h=>({id:h,slug:h,name:Bc(h)}))},getOrderHistory:async()=>[],createCheckoutSession:async d=>{throw new Error("createCheckoutSession is not implemented for paywall adapter")},getStorefrontSettings:async()=>{try{return(await Kt(e.serverUrl,"/paywall/v1/storefront",e.apiKey,{retryableRead:!0})).config??null}catch{return null}},getPaymentMethodsConfig:async()=>{try{const f=(await Kt(e.serverUrl,"/paywall/v1/storefront",e.apiKey,{retryableRead:!0})).paymentMethods;return f?{card:!!f.stripe,crypto:!!f.x402,credits:!!f.credits}:null}catch{return null}},getAIRelatedProducts:async d=>Kt(e.serverUrl,"/admin/ai/related-products",e.apiKey,{method:"POST",body:JSON.stringify(d),headers:{"Content-Type":"application/json"},retryableRead:!1})}}function Cm(e){throw new Error(`Unhandled cart action: ${JSON.stringify(e)}`)}function gn(e){return`${e.productId}::${e.variantId??""}`}const Nm={items:[]};function Am(e,t){switch(t.type){case"cart/hydrate":return t.state;case"cart/add":{const n=Math.max(1,Math.floor(t.qty??1)),r=gn(t.item);return e.items.find(a=>gn(a)===r)?{...e,items:e.items.map(a=>gn(a)===r?{...a,qty:a.qty+n}:a)}:{...e,items:[...e.items,{...t.item,qty:n}]}}case"cart/remove":{const n=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.filter(r=>gn(r)!==n)}}case"cart/setQty":{const n=Math.max(0,Math.floor(t.qty)),r=`${t.productId}::${t.variantId??""}`;return n===0?{...e,items:e.items.filter(o=>gn(o)!==r)}:{...e,items:e.items.map(o=>gn(o)===r?{...o,qty:n}:o)}}case"cart/clear":return{items:[],promoCode:void 0};case"cart/setPromoCode":return{...e,promoCode:t.promoCode||void 0};case"cart/updateHold":{const n=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.map(r=>gn(r)===n?{...r,holdId:t.holdId,holdExpiresAt:t.holdExpiresAt}:r)}}default:return Cm(t)}}function Em(e){return e.reduce((t,n)=>t+n.qty,0)}function Im(e){return e.reduce((t,n)=>t+n.qty*n.unitPrice,0)}function di(){try{return typeof window>"u"?null:window.localStorage}catch{return null}}function Tm(e,t){try{const n=e.getItem(t);return n?JSON.parse(n):null}catch{return null}}function Pm(e,t,n){try{return e.setItem(t,JSON.stringify(n)),!0}catch(r){return console.warn(`[cedros] Failed to write "${t}" to storage`,r),!1}}const Vc=k.createContext(null);function Pt(){const e=k.useContext(Vc);if(!e)throw new Error("useCart must be used within CartProvider");return e}function ui(e){return!!e&&typeof e=="object"&&typeof e.productId=="string"&&e.productId.length>0&&typeof e.qty=="number"&&e.qty>0&&typeof e.unitPrice=="number"&&typeof e.currency=="string"&&typeof e.titleSnapshot=="string"}function Rm({children:e}){const{config:t}=Ee(),n=t.cart?.storageKey??"cedros_shop_cart_v1",r=t.customer?.id,o=t.customer?.isSignedIn??!!r,a=t.cart?.syncDebounceMs??800,i=!!t.adapter.getCartInventoryStatus,[c,l]=k.useReducer(Am,Nm),d=k.useRef(c);d.current=c;const[f,u]=k.useState(!1),h=k.useRef(!1),g=k.useRef(null),y=k.useRef(null);k.useEffect(()=>{const _=di();if(!_)return;const w=Tm(_,n);if(w&&Array.isArray(w.items)){const b=w.items.filter(ui);l({type:"cart/hydrate",state:{items:b,promoCode:typeof w.promoCode=="string"?w.promoCode:void 0}})}u(!0)},[n]),k.useEffect(()=>{if(!f)return;const _=di();_&&Pm(_,n,c)},[c,n,f]),k.useEffect(()=>{if(!f||!o||!r||!t.adapter.mergeCart&&!t.adapter.getCart||(y.current!==r&&(h.current=!1,g.current=null,y.current=r),h.current))return;let _=!1;return(async()=>{try{const w=t.adapter.mergeCart?await t.adapter.mergeCart({customerId:r,cart:d.current}):await t.adapter.getCart({customerId:r});if(_)return;if(w&&Array.isArray(w.items)){h.current=!0;const b={...w,items:w.items.filter(ui)};l({type:"cart/hydrate",state:b}),g.current=JSON.stringify(b)}}catch{_||(h.current=!1)}})(),()=>{_=!0}},[t.adapter,r,f,o]),k.useEffect(()=>{if(!f||!o||!r||!t.adapter.updateCart||!h.current||typeof window>"u")return;const _=JSON.stringify(c);if(g.current===_)return;const w=window.setTimeout(()=>{t.adapter.updateCart({customerId:r,cart:c}).then(()=>{g.current=_}).catch(b=>{console.warn("[CedrosPay] Cart server sync failed:",b instanceof Error?b.message:b)})},a);return()=>window.clearTimeout(w)},[t.adapter,r,f,o,c,a]);const x=k.useCallback((_,w)=>{const b=c.items.find(j=>j.productId===_&&j.variantId===w);if(b)return{holdId:b.holdId,expiresAt:b.holdExpiresAt}},[c.items]),p=k.useCallback((_,w,b)=>{l({type:"cart/updateHold",productId:_,variantId:w,holdExpiresAt:b})},[]),v=k.useMemo(()=>{const _=Em(c.items),w=Im(c.items);return{items:c.items,promoCode:c.promoCode,count:_,subtotal:w,addItem:(b,j)=>l({type:"cart/add",item:b,qty:j}),removeItem:(b,j)=>l({type:"cart/remove",productId:b,variantId:j}),setQty:(b,j,R)=>l({type:"cart/setQty",productId:b,variantId:j,qty:R}),clear:()=>l({type:"cart/clear"}),setPromoCode:b=>l({type:"cart/setPromoCode",promoCode:b}),holdsSupported:i,getItemHold:x,updateItemHold:p}},[c.items,c.promoCode,i,x,p]);return s.jsx(Vc.Provider,{value:v,children:e})}function $(e,t,n){function r(c,l){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:l,constr:i,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,l);const d=i.prototype,f=Object.keys(d);for(let u=0;u<f.length;u++){const h=f[u];h in c||(c[h]=d[h].bind(c))}}const o=n?.Parent??Object;class a extends o{}Object.defineProperty(a,"name",{value:e});function i(c){var l;const d=n?.Parent?new a:this;r(d,c),(l=d._zod).deferred??(l.deferred=[]);for(const f of d._zod.deferred)f();return d}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class Dn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Wc extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const Hc={};function yn(e){return Hc}function Zc(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function ko(e,t){return typeof t=="bigint"?t.toString():t}function Yo(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Qo(e){return e==null}function Ko(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Om(e,t){const n=(e.toString().split(".")[1]||"").length,r=t.toString();let o=(r.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(r)){const l=r.match(/\d?e-(\d?)/);l?.[1]&&(o=Number.parseInt(l[1]))}const a=n>o?n:o,i=Number.parseInt(e.toFixed(a).replace(".","")),c=Number.parseInt(t.toFixed(a).replace(".",""));return i%c/10**a}const fi=Symbol("evaluating");function be(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==fi)return r===void 0&&(r=fi,r=n()),r},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Sn(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function ln(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function mi(e){return JSON.stringify(e)}function Mm(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const qc="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Jr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Lm=Yo(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function mr(e){if(Jr(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Jr(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Gc(e){return mr(e)?{...e}:Array.isArray(e)?[...e]:e}const Dm=new Set(["string","number","symbol"]);function Fn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dn(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function ie(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function $m(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const zm={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Fm(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const a=ln(e._zod.def,{get shape(){const i={};for(const c in t){if(!(c in n.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(i[c]=n.shape[c])}return Sn(this,"shape",i),i},checks:[]});return dn(e,a)}function Um(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const a=ln(e._zod.def,{get shape(){const i={...e._zod.def.shape};for(const c in t){if(!(c in n.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&delete i[c]}return Sn(this,"shape",i),i},checks:[]});return dn(e,a)}function Bm(e,t){if(!mr(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const a=e._zod.def.shape;for(const i in t)if(Object.getOwnPropertyDescriptor(a,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=ln(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return Sn(this,"shape",a),a}});return dn(e,o)}function Vm(e,t){if(!mr(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=ln(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return Sn(this,"shape",r),r}});return dn(e,n)}function Wm(e,t){const n=ln(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return Sn(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:[]});return dn(e,n)}function Hm(e,t,n){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const i=ln(t._zod.def,{get shape(){const c=t._zod.def.shape,l={...c};if(n)for(const d in n){if(!(d in c))throw new Error(`Unrecognized key: "${d}"`);n[d]&&(l[d]=e?new e({type:"optional",innerType:c[d]}):c[d])}else for(const d in c)l[d]=e?new e({type:"optional",innerType:c[d]}):c[d];return Sn(this,"shape",l),l},checks:[]});return dn(t,i)}function Zm(e,t,n){const r=ln(t._zod.def,{get shape(){const o=t._zod.def.shape,a={...o};if(n)for(const i in n){if(!(i in a))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(a[i]=new e({type:"nonoptional",innerType:o[i]}))}else for(const i in o)a[i]=new e({type:"nonoptional",innerType:o[i]});return Sn(this,"shape",a),a}});return dn(t,r)}function Ln(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Yc(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Ir(e){return typeof e=="string"?e:e?.message}function bn(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const o=Ir(e.inst?._zod.def?.error?.(e))??Ir(t?.error?.(e))??Ir(n.customError?.(e))??Ir(n.localeError?.(e))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function Jo(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function pr(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const Qc=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ko,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Kc=$("$ZodError",Qc),Jc=$("$ZodError",Qc,{Parent:Error});function qm(e,t=n=>n.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}function Gm(e,t=n=>n.message){const n={_errors:[]},r=o=>{for(const a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>r({issues:i}));else if(a.code==="invalid_key")r({issues:a.issues});else if(a.code==="invalid_element")r({issues:a.issues});else if(a.path.length===0)n._errors.push(t(a));else{let i=n,c=0;for(;c<a.path.length;){const l=a.path[c];c===a.path.length-1?(i[l]=i[l]||{_errors:[]},i[l]._errors.push(t(a))):i[l]=i[l]||{_errors:[]},i=i[l],c++}}};return r(e),n}const Xo=e=>(t,n,r,o)=>{const a=r?Object.assign(r,{async:!1}):{async:!1},i=t._zod.run({value:n,issues:[]},a);if(i instanceof Promise)throw new Dn;if(i.issues.length){const c=new(o?.Err??e)(i.issues.map(l=>bn(l,a,yn())));throw qc(c,o?.callee),c}return i.value},ea=e=>async(t,n,r,o)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){const c=new(o?.Err??e)(i.issues.map(l=>bn(l,a,yn())));throw qc(c,o?.callee),c}return i.value},hs=e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},o);if(a instanceof Promise)throw new Dn;return a.issues.length?{success:!1,error:new(e??Kc)(a.issues.map(i=>bn(i,o,yn())))}:{success:!0,data:a.value}},Ym=hs(Jc),gs=e=>async(t,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},o);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(i=>bn(i,o,yn())))}:{success:!0,data:a.value}},Qm=gs(Jc),Km=e=>(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Xo(e)(t,n,o)},Jm=e=>(t,n,r)=>Xo(e)(t,n,r),Xm=e=>async(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return ea(e)(t,n,o)},ep=e=>async(t,n,r)=>ea(e)(t,n,r),tp=e=>(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return hs(e)(t,n,o)},np=e=>(t,n,r)=>hs(e)(t,n,r),rp=e=>async(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return gs(e)(t,n,o)},sp=e=>async(t,n,r)=>gs(e)(t,n,r),op=/^[cC][^\s-]{8,}$/,ap=/^[0-9a-z]+$/,ip=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,cp=/^[0-9a-vA-V]{20}$/,lp=/^[A-Za-z0-9]{27}$/,dp=/^[a-zA-Z0-9_-]{21}$/,up=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,fp=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,pi=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,mp=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,pp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function hp(){return new RegExp(pp,"u")}const gp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,xp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,vp=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,yp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,bp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Xc=/^[A-Za-z0-9_-]*$/,wp=/^\+[1-9]\d{6,14}$/,el="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",_p=new RegExp(`^${el}$`);function tl(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function kp(e){return new RegExp(`^${tl(e)}$`)}function jp(e){const t=tl({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${el}T(?:${r})$`)}const Sp=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Cp=/^-?\d+$/,Np=/^-?\d+(?:\.\d+)?$/,Ap=/^[^A-Z]*$/,Ep=/^[^a-z]*$/,ut=$("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),nl={number:"number",bigint:"bigint",object:"date"},rl=$("$ZodCheckLessThan",(e,t)=>{ut.init(e,t);const n=nl[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,a=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<a&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),sl=$("$ZodCheckGreaterThan",(e,t)=>{ut.init(e,t);const n=nl[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,a=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>a&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ip=$("$ZodCheckMultipleOf",(e,t)=>{ut.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):Om(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Tp=$("$ZodCheckNumberFormat",(e,t)=>{ut.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[o,a]=zm[t.format];e._zod.onattach.push(i=>{const c=i._zod.bag;c.format=t.format,c.minimum=o,c.maximum=a,n&&(c.pattern=Cp)}),e._zod.check=i=>{const c=i.value;if(n){if(!Number.isInteger(c)){i.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?i.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):i.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}c<o&&i.issues.push({origin:"number",input:c,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),c>a&&i.issues.push({origin:"number",input:c,code:"too_big",maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Pp=$("$ZodCheckMaxLength",(e,t)=>{var n;ut.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!Qo(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const o=r.value;if(o.length<=t.maximum)return;const i=Jo(o);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Rp=$("$ZodCheckMinLength",(e,t)=>{var n;ut.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!Qo(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const o=r.value;if(o.length>=t.minimum)return;const i=Jo(o);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Op=$("$ZodCheckLengthEquals",(e,t)=>{var n;ut.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!Qo(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=r=>{const o=r.value,a=o.length;if(a===t.length)return;const i=Jo(o),c=a>t.length;r.issues.push({origin:i,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),xs=$("$ZodCheckStringFormat",(e,t)=>{var n,r;ut.init(e,t),e._zod.onattach.push(o=>{const a=o._zod.bag;a.format=t.format,t.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Mp=$("$ZodCheckRegex",(e,t)=>{xs.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Lp=$("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ap),xs.init(e,t)}),Dp=$("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Ep),xs.init(e,t)}),$p=$("$ZodCheckIncludes",(e,t)=>{ut.init(e,t);const n=Fn(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(o=>{const a=o._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(r)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),zp=$("$ZodCheckStartsWith",(e,t)=>{ut.init(e,t);const n=new RegExp(`^${Fn(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),Fp=$("$ZodCheckEndsWith",(e,t)=>{ut.init(e,t);const n=new RegExp(`.*${Fn(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),Up=$("$ZodCheckOverwrite",(e,t)=>{ut.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class Bp{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
|
|
1
|
+
"use strict";const s=require("react/jsx-runtime"),k=require("react"),zf=require("@solana/wallet-adapter-react"),Je=require("./CedrosContext-D-lnoEkR.js"),Ff=require("@cedros/login-react"),oi=require("./index-WcOlBYZJ.js"),Zo=require("react-dom"),Uf=require("./styles-BWrLnaUW.js");function Tc(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const m=Tc(k),ps=Tc(Zo);function lr(e){return new Date(e).toLocaleString()}const Y={products:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M20 7.5v9l-4 2.25M4 7.5v9l4 2.25"}),s.jsx("path",{d:"m20 7.5-8-4.5-8 4.5"}),s.jsx("path",{d:"m12 12 8-4.5M12 12v9.5M12 12 4 7.5"})]}),transactions:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"})}),coupons:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z"}),s.jsx("path",{d:"M13 5v2M13 17v2M13 11v2"})]}),refunds:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),s.jsx("path",{d:"M3 3v5h5"}),s.jsx("path",{d:"M12 7v5l4 2"})]}),settings:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),wallet:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}),s.jsx("path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"})]}),chevronRight:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"m9 18 6-6-6-6"})}),loading:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"cedros-admin__spinner",children:s.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),refresh:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}),s.jsx("path",{d:"M21 3v5h-5"}),s.jsx("path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}),s.jsx("path",{d:"M8 16H3v5"})]}),check:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M20 6 9 17l-5-5"})}),subscriptions:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M12 2v2M12 20v2M2 12H4M20 12h2"})]}),trash:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"})}),plus:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M12 5v14M5 12h14"})}),chevronDown:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"m6 9 6 6 6-6"})}),chevronUp:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"m18 15-6-6-6 6"})}),storefront:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M3 9h18v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V9Z"}),s.jsx("path",{d:"m3 9 2.45-4.9A2 2 0 0 1 7.24 3h9.52a2 2 0 0 1 1.8 1.1L21 9"}),s.jsx("path",{d:"M12 3v6"})]}),arrowUp:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"m5 12 7-7 7 7"}),s.jsx("path",{d:"M12 19V5"})]}),arrowDown:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"m5 12 7 7 7-7"}),s.jsx("path",{d:"M12 5v14"})]}),delete:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"}),s.jsx("path",{d:"M10 11v6M14 11v6"})]}),close:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M18 6 6 18M6 6l12 12"})}),edit:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),s.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),faq:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),s.jsx("path",{d:"M12 17h.01"})]}),chat:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"m3 21 1.9-5.7a8.5 8.5 0 1 1 3.8 3.8z"})}),globe:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}),s.jsx("path",{d:"M2 12h20"})]}),ai:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M12 2a4 4 0 0 1 4 4v2a4 4 0 0 1-8 0V6a4 4 0 0 1 4-4Z"}),s.jsx("path",{d:"M10 10v.5"}),s.jsx("path",{d:"M14 10v.5"}),s.jsx("path",{d:"M12 14v2"}),s.jsx("path",{d:"M8 18h8"}),s.jsx("path",{d:"M6 18a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2"}),s.jsx("path",{d:"M6 12v6"}),s.jsx("path",{d:"M18 12v6"})]}),notifications:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"}),s.jsx("path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0"})]}),eye:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),eyeOff:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24"}),s.jsx("path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"}),s.jsx("path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"}),s.jsx("line",{x1:"2",x2:"22",y1:"2",y2:"22"})]}),creditCard:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),s.jsx("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),mail:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),s.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),server:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2"}),s.jsx("rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2"}),s.jsx("line",{x1:"6",x2:"6.01",y1:"6",y2:"6"}),s.jsx("line",{x1:"6",x2:"6.01",y1:"18",y2:"18"})]}),calendarRepeat:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",ry:"2"}),s.jsx("line",{x1:"16",x2:"16",y1:"2",y2:"6"}),s.jsx("line",{x1:"8",x2:"8",y1:"2",y2:"6"}),s.jsx("line",{x1:"3",x2:"21",y1:"10",y2:"10"}),s.jsx("path",{d:"M11 14h1.5a1.5 1.5 0 0 1 0 3H11v2"}),s.jsx("path",{d:"M16 14v3a1 1 0 0 0 1 1h1"})]}),brain:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"}),s.jsx("path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"}),s.jsx("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),s.jsx("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),s.jsx("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),s.jsx("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),s.jsx("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),s.jsx("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),s.jsx("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]})};function jr({message:e,onRetry:t}){return e?s.jsxs("div",{className:"cedros-admin__error-banner",children:[s.jsx("span",{children:e}),t&&s.jsxs("button",{type:"button",className:"cedros-admin__error-banner-retry",onClick:t,children:[Y.refresh," Retry"]})]}):null}function Sr({stats:e,isLoading:t=!1,onRefresh:n}){return s.jsxs("div",{className:"cedros-admin__stats-bar",children:[s.jsx("div",{className:"cedros-admin__stats-bar-grid",children:e.map((r,o)=>s.jsxs("div",{className:"cedros-admin__stats-bar-item",children:[s.jsx("span",{className:"cedros-admin__stats-bar-label",children:r.label}),s.jsx("span",{className:`cedros-admin__stats-bar-value ${r.variant?`cedros-admin__stats-bar-value--${r.variant}`:""}`,children:t?s.jsx("span",{className:"cedros-admin__skeleton cedros-admin__skeleton--value"}):r.value}),r.description&&s.jsx("span",{className:"cedros-admin__stats-bar-desc",children:r.description})]},o))}),n&&s.jsx("button",{type:"button",className:"cedros-admin__stats-bar-refresh",onClick:n,disabled:t,title:"Refresh stats",children:t?Y.loading:Y.refresh})]})}function Bf({serverUrl:e,productId:t,apiKey:n,authManager:r}){const[o,a]=k.useState(null),[i,c]=k.useState(!1),[l,d]=k.useState(!1),[f,u]=k.useState(null),h=k.useCallback(async()=>{if(t){c(!0),u(null);try{let x;if(r?.isAuthenticated())x=await r.fetchWithAuth(`/admin/products/${t}/variations`);else{const p={"Content-Type":"application/json"};n&&(p["X-API-Key"]=n);const v=await fetch(`${e}/admin/products/${t}/variations`,{headers:p});if(!v.ok)throw new Error(`Failed to fetch variations: ${v.status}`);x=await v.json()}x.variationConfig||(x.variationConfig={variationTypes:[]}),x.variants||(x.variants=[]),a(x)}catch(x){const p=x instanceof Error?x.message:"Failed to fetch variations";u(p),a({productId:t,variationConfig:{variationTypes:[]},variants:[]})}finally{c(!1)}}},[e,t,n,r]),g=k.useCallback(async x=>{if(!t)return null;d(!0),u(null);try{let p;if(r?.isAuthenticated())p=await r.fetchWithAuth(`/admin/products/${t}/variations`,{method:"PUT",body:JSON.stringify(x)});else{const v={"Content-Type":"application/json"};n&&(v["X-API-Key"]=n);const _=await fetch(`${e}/admin/products/${t}/variations`,{method:"PUT",headers:v,body:JSON.stringify(x)});if(!_.ok)throw new Error(`Failed to save variations: ${_.status}`);p=await _.json()}return a({productId:t,variationConfig:p.variationConfig,variants:p.variants}),{variantsCreated:p.variantsCreated}}catch(p){const v=p instanceof Error?p.message:"Failed to save variations";return u(v),null}finally{d(!1)}},[e,t,n,r]),y=k.useCallback(async x=>{if(!t||x.length===0)return!1;d(!0),u(null);try{if(r?.isAuthenticated())await r.fetchWithAuth(`/admin/products/${t}/variants/inventory`,{method:"PUT",body:JSON.stringify({updates:x})});else{const p={"Content-Type":"application/json"};n&&(p["X-API-Key"]=n);const v=await fetch(`${e}/admin/products/${t}/variants/inventory`,{method:"PUT",headers:p,body:JSON.stringify({updates:x})});if(!v.ok)throw new Error(`Failed to update inventory: ${v.status}`)}if(o){const p=new Map(x.map(v=>[v.variantId,v]));a({...o,variants:o.variants.map(v=>{const _=p.get(v.id);return _?{...v,inventoryQuantity:_.inventoryQuantity,inventoryStatus:_.inventoryStatus??v.inventoryStatus}:v})})}return!0}catch(p){const v=p instanceof Error?p.message:"Failed to update inventory";return u(v),!1}finally{d(!1)}},[e,t,n,r,o]);return{data:o,isLoading:i,error:f,fetch:h,save:g,bulkUpdateInventory:y,isSaving:l}}function ai(){return`var_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Vf({value:e,onChange:t,maxTypes:n=5,maxValuesPerType:r=20,disabled:o=!1}){const[a,i]=k.useState(null),[c,l]=k.useState(""),[d,f]=k.useState({}),u=e.variationTypes,h=k.useCallback(()=>{if(!c.trim()||u.length>=n)return;const w={id:ai(),name:c.trim(),displayOrder:u.length,values:[]};t({variationTypes:[...u,w]}),l(""),i(w.id)},[c,u,n,t]),g=k.useCallback(w=>{t({variationTypes:u.filter(b=>b.id!==w).map((b,j)=>({...b,displayOrder:j}))}),a===w&&i(null)},[u,t,a]),y=k.useCallback((w,b)=>{t({variationTypes:u.map(j=>j.id===w?{...j,name:b}:j)})},[u,t]),x=k.useCallback((w,b)=>{const j=u.findIndex(C=>C.id===w);if(j===-1||b==="up"&&j===0||b==="down"&&j===u.length-1)return;const R=[...u],I=b==="up"?j-1:j+1;[R[j],R[I]]=[R[I],R[j]],t({variationTypes:R.map((C,E)=>({...C,displayOrder:E}))})},[u,t]),p=k.useCallback(w=>{const b=(d[w]||"").trim();if(!b)return;const j=u.find(I=>I.id===w);if(!j||j.values.length>=r)return;const R={id:ai(),label:b};t({variationTypes:u.map(I=>I.id===w?{...I,values:[...I.values,R]}:I)}),f(I=>({...I,[w]:""}))},[u,d,r,t]),v=k.useCallback((w,b)=>{t({variationTypes:u.map(j=>j.id===w?{...j,values:j.values.filter(R=>R.id!==b)}:j)})},[u,t]),_=k.useCallback((w,b,j)=>{t({variationTypes:u.map(R=>R.id===w?{...R,values:R.values.map(I=>I.id===b?{...I,label:j}:I)}:R)})},[u,t]);return s.jsxs("div",{className:"cedros-admin__variation-editor",children:[s.jsxs("div",{className:"cedros-admin__variation-editor-header",children:[s.jsx("h4",{className:"cedros-admin__field-label",style:{marginBottom:0},children:"Variation Types"}),s.jsxs("span",{style:{fontSize:12,opacity:.7},children:[u.length,"/",n," types"]})]}),u.length===0?s.jsx("div",{className:"cedros-admin__variation-empty",children:'No variation types defined. Add types like "Size" or "Color" to create product variants.'}):s.jsx("div",{className:"cedros-admin__variation-type-list",children:u.map((w,b)=>s.jsxs("div",{className:"cedros-admin__variation-type-item",children:[s.jsxs("div",{className:"cedros-admin__variation-type-header",children:[s.jsxs("div",{className:"cedros-admin__variation-type-controls",children:[s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>x(w.id,"up"),disabled:o||b===0,title:"Move up",children:Y.arrowUp}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>x(w.id,"down"),disabled:o||b===u.length-1,title:"Move down",children:Y.arrowDown})]}),s.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__variation-type-name",value:w.name,onChange:j=>y(w.id,j.target.value),disabled:o,placeholder:"Type name"}),s.jsxs("span",{className:"cedros-admin__variation-value-count",children:[w.values.length," values"]}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>i(a===w.id?null:w.id),children:a===w.id?"Collapse":"Edit values"}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>g(w.id),disabled:o,title:"Remove type",children:Y.delete})]}),a===w.id&&s.jsxs("div",{className:"cedros-admin__variation-values",children:[s.jsxs("div",{className:"cedros-admin__variation-values-header",children:[s.jsxs("span",{style:{fontSize:12,fontWeight:600},children:['Values for "',w.name,'"']}),s.jsxs("span",{style:{fontSize:11,opacity:.7},children:[w.values.length,"/",r]})]}),w.values.length===0?s.jsx("div",{className:"cedros-admin__variation-empty",style:{padding:"8px 0"},children:'No values yet. Add values like "Small", "Medium", "Large".'}):s.jsx("div",{className:"cedros-admin__variation-value-list",children:w.values.map(j=>s.jsxs("div",{className:"cedros-admin__variation-value-item",children:[s.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:j.label,onChange:R=>_(w.id,j.id,R.target.value),disabled:o}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon cedros-admin__button--danger",onClick:()=>v(w.id,j.id),disabled:o,title:"Remove value",children:Y.close})]},j.id))}),w.values.length<r&&s.jsxs("div",{className:"cedros-admin__variation-add-value",children:[s.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:d[w.id]||"",onChange:j=>f(R=>({...R,[w.id]:j.target.value})),placeholder:"Add value...",disabled:o,onKeyDown:j=>{j.key==="Enter"&&(j.preventDefault(),p(w.id))}}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary cedros-admin__button--sm",onClick:()=>p(w.id),disabled:o||!d[w.id]?.trim(),children:"Add"})]})]})]},w.id))}),u.length<n&&s.jsxs("div",{className:"cedros-admin__variation-add-type",children:[s.jsx("input",{type:"text",className:"cedros-admin__input",value:c,onChange:w=>l(w.target.value),placeholder:"New variation type (e.g., Size, Color)",disabled:o,onKeyDown:w=>{w.key==="Enter"&&(w.preventDefault(),h())}}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary",onClick:h,disabled:o||!c.trim(),children:"Add Type"})]})]})}function Pc({value:e,onChange:t,options:n,placeholder:r="Filter",disabled:o}){const[a,i]=k.useState(!1),c=k.useRef(null),d=n.find(f=>f.value===e)?.label||r;return k.useEffect(()=>{const f=u=>{c.current&&!c.current.contains(u.target)&&i(!1)};if(a)return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[a]),k.useEffect(()=>{const f=u=>{u.key==="Escape"&&i(!1)};if(a)return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[a]),s.jsxs("div",{className:"cedros-admin__dropdown",ref:c,children:[s.jsxs("button",{type:"button",className:"cedros-admin__dropdown-trigger",onClick:()=>!o&&i(!a),"aria-expanded":a,"aria-haspopup":"listbox",disabled:o,children:[s.jsx("span",{children:d}),s.jsx("span",{className:`cedros-admin__dropdown-chevron ${a?"cedros-admin__dropdown-chevron--open":""}`,children:Y.chevronDown})]}),a&&s.jsx("div",{className:"cedros-admin__dropdown-menu",role:"listbox",children:n.map(f=>s.jsxs("button",{type:"button",className:`cedros-admin__dropdown-item ${f.value===e?"cedros-admin__dropdown-item--selected":""}`,onClick:()=>{f.disabled||(t(f.value),i(!1))},role:"option","aria-selected":f.value===e,disabled:f.disabled,children:[f.label,f.value===e&&s.jsx("span",{className:"cedros-admin__dropdown-check",children:Y.check})]},f.value))})]})}function At({value:e,onChange:t,options:n,label:r,description:o,disabled:a,className:i,style:c}){const[l,d]=k.useState(!1),f=k.useRef(null),h=n.find(g=>g.value===e)?.label||"Select...";return k.useEffect(()=>{const g=y=>{f.current&&!f.current.contains(y.target)&&d(!1)};if(l)return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[l]),k.useEffect(()=>{const g=y=>{y.key==="Escape"&&d(!1)};if(l)return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[l]),s.jsxs("div",{className:`cedros-admin__field ${i||""}`,style:c,children:[s.jsx("label",{className:"cedros-admin__field-label",children:r}),s.jsxs("div",{className:"cedros-admin__dropdown cedros-admin__dropdown--form",ref:f,children:[s.jsxs("button",{type:"button",className:"cedros-admin__dropdown-trigger cedros-admin__dropdown-trigger--form",onClick:()=>!a&&d(!l),"aria-expanded":l,"aria-haspopup":"listbox",disabled:a,children:[s.jsx("span",{children:h}),s.jsx("span",{className:`cedros-admin__dropdown-chevron ${l?"cedros-admin__dropdown-chevron--open":""}`,children:Y.chevronDown})]}),l&&s.jsx("div",{className:"cedros-admin__dropdown-menu cedros-admin__dropdown-menu--form",role:"listbox",children:n.map(g=>s.jsxs("button",{type:"button",className:`cedros-admin__dropdown-item ${g.value===e?"cedros-admin__dropdown-item--selected":""}`,onClick:()=>{g.disabled||(t(g.value),d(!1))},role:"option","aria-selected":g.value===e,disabled:g.disabled,children:[g.label,g.value===e&&s.jsx("span",{className:"cedros-admin__dropdown-check",children:Y.check})]},g.value))})]}),o&&s.jsx("p",{className:"cedros-admin__field-description",children:o})]})}function ii(){return`variant_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Wf(e){if(e.length===0)return[];const t=[...e].sort((r,o)=>r.displayOrder-o.displayOrder),n=(r,o)=>{if(r>=t.length){const c=o.valueIds.sort().join("|"),l=Object.values(o.options).join(" / ");return[{key:c,title:l,optionValueIds:[...o.valueIds],options:{...o.options}}]}const a=t[r],i=[];for(const c of a.values)i.push(...n(r+1,{valueIds:[...o.valueIds,c.id],options:{...o.options,[a.name]:c.label}}));return i};return n(0,{valueIds:[],options:{}})}function Hf(e){return e.optionValueIds?.length?[...e.optionValueIds].sort().join("|"):Object.entries(e.options).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${t}:${n}`).join("|")}function Zf({variationConfig:e,variants:t,onChange:n,defaultPrice:r=0,currencySymbol:o="$",maxVariants:a=100,disabled:i=!1}){const c=k.useMemo(()=>Wf(e.variationTypes),[e.variationTypes]),l=k.useMemo(()=>{const x=new Map;for(const p of t)x.set(Hf(p),p);return x},[t]),{existingRows:d,possibleRows:f}=k.useMemo(()=>{const x=[],p=[];for(const v of c){const _=l.get(v.key);_?x.push({combo:v,variant:_}):p.push(v)}return{existingRows:x,possibleRows:p}},[c,l]),u=k.useCallback((x,p)=>{n(t.map(v=>v.id===x?{...v,...p}:v))},[t,n]),h=k.useCallback(x=>{n(t.filter(p=>p.id!==x))},[t,n]),g=k.useCallback(x=>{if(t.length>=a)return;const p={id:ii(),title:x.title,options:x.options,optionValueIds:x.optionValueIds,price:r,inventoryQuantity:0,inventoryStatus:"in_stock",autoGenerated:!1};n([...t,p])},[t,n,a,r]),y=k.useCallback(()=>{const x=a-t.length,v=f.slice(0,x).map(_=>({id:ii(),title:_.title,options:_.options,optionValueIds:_.optionValueIds,price:r,inventoryQuantity:0,inventoryStatus:"in_stock",autoGenerated:!0}));n([...t,...v])},[t,n,f,a,r]);return e.variationTypes.length===0?s.jsx("div",{className:"cedros-admin__variant-grid-empty",children:"Add variation types above to create product variants."}):c.length===0?s.jsx("div",{className:"cedros-admin__variant-grid-empty",children:"Add values to your variation types to create product variants."}):s.jsxs("div",{className:"cedros-admin__variant-grid",children:[s.jsxs("div",{className:"cedros-admin__variant-grid-header",children:[s.jsx("h4",{className:"cedros-admin__field-label",style:{marginBottom:0},children:"Variants"}),s.jsxs("span",{style:{fontSize:12,opacity:.7},children:[t.length,"/",a," variants (",c.length," ","possible)"]})]}),f.length>0&&t.length<a&&s.jsxs("div",{className:"cedros-admin__variant-grid-actions",children:[s.jsxs("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary",onClick:y,disabled:i,children:["Generate All (",Math.min(f.length,a-t.length),")"]}),s.jsx("span",{style:{fontSize:11,opacity:.7},children:"Creates variants with default price and 0 inventory"})]}),s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table cedros-admin__variant-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Variant"}),s.jsx("th",{style:{width:100},children:"Price"}),s.jsx("th",{style:{width:80},children:"Qty"}),s.jsx("th",{style:{width:100},children:"SKU"}),s.jsx("th",{style:{width:100},children:"Status"}),s.jsx("th",{style:{width:80},children:"Actions"})]})}),s.jsxs("tbody",{children:[d.map(({combo:x,variant:p})=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[s.jsx("span",{style:{fontWeight:600},children:x.title}),s.jsx("span",{style:{fontSize:11,opacity:.6},children:Object.entries(x.options).map(([v,_])=>`${v}: ${_}`).join(", ")})]})}),s.jsx("td",{children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[s.jsx("span",{children:o}),s.jsx("input",{type:"number",className:"cedros-admin__input cedros-admin__input--sm",value:p.price??"",onChange:v=>u(p.id,{price:v.target.value===""?void 0:parseFloat(v.target.value)||0}),disabled:i,min:"0",step:"0.01",style:{width:70}})]})}),s.jsx("td",{children:s.jsx("input",{type:"number",className:"cedros-admin__input cedros-admin__input--sm",value:p.inventoryQuantity??"",onChange:v=>u(p.id,{inventoryQuantity:v.target.value===""?void 0:parseInt(v.target.value)||0}),disabled:i,min:"0",style:{width:60}})}),s.jsx("td",{children:s.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:p.sku??"",onChange:v=>u(p.id,{sku:v.target.value||void 0}),disabled:i,placeholder:"SKU",style:{width:80}})}),s.jsx("td",{children:s.jsx(Pc,{value:p.inventoryStatus??"in_stock",onChange:v=>u(p.id,{inventoryStatus:v}),options:[{value:"in_stock",label:"In stock"},{value:"low",label:"Low"},{value:"out_of_stock",label:"Out of stock"},{value:"backorder",label:"Backorder"}],disabled:i})}),s.jsx("td",{children:s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon cedros-admin__button--danger",onClick:()=>h(p.id),disabled:i,title:"Remove variant",children:Y.trash})})]},p.id)),f.length>0&&t.length<a&&s.jsxs(s.Fragment,{children:[s.jsx("tr",{className:"cedros-admin__variant-separator",children:s.jsx("td",{colSpan:6,children:s.jsxs("span",{style:{fontSize:11,opacity:.6},children:["Uncreated combinations (",f.length,")"]})})}),f.slice(0,10).map(x=>s.jsxs("tr",{className:"cedros-admin__variant-possible",children:[s.jsx("td",{children:s.jsx("span",{style:{opacity:.6},children:x.title})}),s.jsx("td",{colSpan:4,style:{opacity:.5},children:"Not created"}),s.jsx("td",{children:s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>g(x),disabled:i,title:"Create variant",children:Y.plus})})]},x.key)),f.length>10&&s.jsx("tr",{className:"cedros-admin__variant-more",children:s.jsxs("td",{colSpan:6,style:{textAlign:"center",opacity:.6},children:["+",f.length-10," more combinations"]})})]})]})]})})]})}function qf({serverUrl:e,productId:t,productTitle:n,defaultPrice:r=0,currencySymbol:o="$",apiKey:a,authManager:i,onClose:c}){const{data:l,isLoading:d,error:f,fetch:u,save:h,isSaving:g}=Bf({serverUrl:e,productId:t,apiKey:a,authManager:i}),[y,x]=k.useState({variationTypes:[]}),[p,v]=k.useState([]),[_,w]=k.useState(!1),[b,j]=k.useState(!1);k.useEffect(()=>{u()},[u]),k.useEffect(()=>{l&&(x(l.variationConfig),v(l.variants),w(!1))},[l]);const R=k.useCallback(E=>{x(E),w(!0),j(!1)},[]),I=k.useCallback(E=>{v(E),w(!0),j(!1)},[]),C=k.useCallback(async()=>{const E=new Set((l?.variants??[]).map(D=>D.id)),O=p.filter(D=>!E.has(D.id)),F=p.filter(D=>E.has(D.id)),M=(l?.variants??[]).filter(D=>!p.some(H=>H.id===D.id)).map(D=>D.id);await h({variationConfig:y,createVariants:O.map(D=>({optionValueIds:D.optionValueIds??[],inventoryQuantity:D.inventoryQuantity,sku:D.sku,price:D.price})),updateVariants:F.map(D=>({id:D.id,inventoryQuantity:D.inventoryQuantity,sku:D.sku,price:D.price,inventoryStatus:D.inventoryStatus})),deleteVariantIds:M.length>0?M:void 0})&&(w(!1),j(!0),setTimeout(()=>j(!1),3e3))},[y,p,l?.variants,h]);return d?s.jsxs("div",{className:"cedros-admin__variations-editor",children:[s.jsxs("div",{className:"cedros-admin__variations-editor-header",children:[s.jsx("h3",{className:"cedros-admin__section-title",children:n?`Variations: ${n}`:"Product Variations"}),c&&s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:c,children:Y.close})]}),s.jsxs("div",{className:"cedros-admin__loading",children:[Y.loading," Loading variations..."]})]}):s.jsxs("div",{className:"cedros-admin__variations-editor",children:[s.jsxs("div",{className:"cedros-admin__variations-editor-header",children:[s.jsx("h3",{className:"cedros-admin__section-title",children:n?`Variations: ${n}`:"Product Variations"}),s.jsxs("div",{className:"cedros-admin__variations-editor-actions",children:[b&&s.jsxs("span",{className:"cedros-admin__success-text",children:[Y.check," Saved"]}),_&&s.jsx("span",{className:"cedros-admin__unsaved-text",children:"Unsaved changes"}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--primary",onClick:C,disabled:g||!_,children:g?"Saving...":"Save Changes"}),c&&s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:c,children:Y.close})]})]}),f&&s.jsx("div",{className:"cedros-admin__error-banner",children:f}),s.jsxs("div",{className:"cedros-admin__variations-editor-content",children:[s.jsx("div",{className:"cedros-admin__variations-editor-section",children:s.jsx(Vf,{value:y,onChange:R,disabled:g})}),y.variationTypes.length>0&&s.jsx("div",{className:"cedros-admin__variations-editor-section",children:s.jsx(Zf,{variationConfig:y,variants:p,onChange:I,defaultPrice:r,currencySymbol:o,disabled:g})})]})]})}function Rc({serverUrl:e,apiKey:t,pageSize:n=20,authManager:r}){const[o,a]=k.useState([]),[i,c]=k.useState(!0),[l,d]=k.useState(!1),[f,u]=k.useState(!1),[h,g]=k.useState(null),[y,x]=k.useState(null),[p,v]=k.useState(null),[_,w]=k.useState(null),[b,j]=k.useState({id:"",title:"",slug:"",imageUrl:"",description:"",productType:"one_time",priceUsd:"",fiatCurrency:"usd",cryptoToken:"USDC",inventoryStatus:"in_stock",compareAtUsd:"",tagsCsv:"",categoryIdsCsv:"",checkoutEmail:"required",checkoutName:"optional",checkoutPhone:"none",checkoutShippingAddress:!1,checkoutBillingAddress:!1,fulfillmentType:"shipping",fulfillmentNotes:"",shippingCountriesCsv:"",inventoryQuantity:""}),R=A=>{const N=A.tagsCsv.split(",").map(q=>q.trim()).filter(Boolean),Z=A.categoryIdsCsv.split(",").map(q=>q.trim()).filter(Boolean),te={email:A.checkoutEmail,name:A.checkoutName,phone:A.checkoutPhone,shippingAddress:A.checkoutShippingAddress,billingAddress:A.checkoutBillingAddress},re=A.fulfillmentType==="shipping"?"physical":"digital",de={title:A.title,slug:A.slug||A.id,shipping_profile:re,inventory_status:A.inventoryStatus,checkout_requirements:JSON.stringify(te),fulfillment_type:A.fulfillmentType};A.imageUrl&&(de.image_url=A.imageUrl);const W=A.compareAtUsd?Math.round(Number(A.compareAtUsd)*100):0;W&&(de.compare_at_amount_cents=String(W)),N.length&&(de.tags=JSON.stringify(N)),Z.length&&(de.category_ids=JSON.stringify(Z)),A.fulfillmentNotes&&(de.fulfillment_notes=A.fulfillmentNotes);const Q=A.shippingCountriesCsv.split(",").map(q=>q.trim().toUpperCase()).filter(Boolean);return Q.length&&(de.shippingCountries=Q.join(","),de.shipping_countries=Q.join(",")),de},I=A=>A.metadata?.title||A.description||A.id,C=A=>A.metadata?.image_url,E=k.useCallback(async()=>{try{w(null);let A;if(r?.isAuthenticated())A=await r.fetchWithAuth(`/admin/products?limit=${n}`);else{const N={"Content-Type":"application/json"};t&&(N["X-API-Key"]=t);const Z=await fetch(`${e}/admin/products?limit=${n}`,{headers:N});if(!Z.ok)throw new Error(`Failed to fetch products: ${Z.status}`);A=await Z.json()}a(A.products||[])}catch{a([]),w("Failed to load products")}finally{c(!1)}},[e,t,n,r]);k.useEffect(()=>{E()},[E]);const O=async A=>{if(A.preventDefault(),!(!b.id||!b.description)){if(g(null),b.fulfillmentType==="shipping"&&b.checkoutShippingAddress&&!b.shippingCountriesCsv.split(",").map(Z=>Z.trim()).filter(Boolean).length){g("Shipping countries are required when collecting shipping address. Example: US,CA");return}u(!0);try{const{productType:N}=b,Z=b.inventoryQuantity===""?void 0:Number.isFinite(Number(b.inventoryQuantity))?Number(b.inventoryQuantity):void 0,te=Number(b.priceUsd)||0,re=Math.round(te*100),de=Math.round(te*1e6),W={id:b.id,description:b.description,fiatAmountCents:re,fiatCurrency:b.fiatCurrency,cryptoAtomicAmount:de,cryptoToken:b.cryptoToken,...Z!==void 0?{inventoryQuantity:Z}:{},metadata:{...N?{product_type:N}:{},...R(b)}};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/products",{method:"POST",body:JSON.stringify(W)});else{const Q={"Content-Type":"application/json"};t&&(Q["X-API-Key"]=t);const q=await fetch(`${e}/admin/products`,{method:"POST",headers:Q,body:JSON.stringify(W)});if(!q.ok)throw new Error(`Failed to create product: ${q.status}`)}j({id:"",title:"",slug:"",imageUrl:"",description:"",productType:"one_time",priceUsd:"",fiatCurrency:"usd",cryptoToken:"USDC",inventoryStatus:"in_stock",compareAtUsd:"",tagsCsv:"",categoryIdsCsv:"",checkoutEmail:"required",checkoutName:"optional",checkoutPhone:"none",checkoutShippingAddress:!1,checkoutBillingAddress:!1,fulfillmentType:"shipping",fulfillmentNotes:"",shippingCountriesCsv:"",inventoryQuantity:""}),d(!1),E()}catch(N){g(N instanceof Error?N.message:"Failed to create product")}finally{u(!1)}}},F=A=>`$${(A/100).toFixed(2)}`,M=A=>{switch(A){case"subscription":return"Subscription";case"pay_per_access":return"Pay per access";case"one_time":return"One-time purchase";default:return"One-time purchase"}},U=k.useMemo(()=>{const A=o.filter(Z=>Z.active).length,N=o.reduce((Z,te)=>{const re=te.variations?.length??0;return Z+(re>0?re:1)},0);return{activeCount:A,totalSkus:N}},[o]),D=A=>{v(N=>!N||N.key!==A?{key:A,direction:"asc"}:{key:A,direction:N.direction==="asc"?"desc":"asc"})},H=A=>!p||p.key!==A?s.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Y.chevronUp}):s.jsx("span",{className:"cedros-admin__sort-icon",children:p.direction==="asc"?Y.chevronUp:Y.chevronDown}),z=k.useMemo(()=>{if(!p)return o;const A=p.direction==="asc"?1:-1,N=Z=>{switch(p.key){case"product":return I(Z);case"type":return M(Z.metadata?.product_type);case"price":return Z.fiatAmountCents??0;case"status":return Z.active?1:0;case"id":default:return Z.id}};return[...o].sort((Z,te)=>{const re=N(Z),de=N(te);return typeof re=="number"&&typeof de=="number"?(re-de)*A:String(re).localeCompare(String(de),void 0,{sensitivity:"base"})*A})},[o,p]);return s.jsxs("div",{className:"cedros-admin__page",children:[s.jsx(jr,{message:_,onRetry:E}),s.jsx(Sr,{stats:[{label:"Total Products",value:o.length},{label:"Active",value:U.activeCount,variant:U.activeCount>0?"success":"muted"},{label:"Total SKUs",value:U.totalSkus}],isLoading:i}),s.jsxs("div",{className:"cedros-admin__section-header",children:[s.jsx("h3",{className:"cedros-admin__section-title",children:"Paywall Products"}),s.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:()=>{g(null),d(!l)},children:[l?Y.close:Y.plus,l?"Cancel":"Add Product"]})]}),l&&s.jsxs("form",{onSubmit:O,className:"cedros-admin__add-form",children:[h&&s.jsx("div",{style:{marginBottom:"0.75rem",color:"#B42318",fontWeight:600},children:h}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Product ID"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:b.id,onChange:A=>j(N=>({...N,id:A.target.value})),placeholder:"e.g., premium-article",required:!0})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Product name"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:b.title,onChange:A=>j(N=>({...N,title:A.target.value})),placeholder:"e.g., Cedros Hoodie"})]})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Slug"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:b.slug,onChange:A=>j(N=>({...N,slug:A.target.value})),placeholder:"e.g., cedros-hoodie (defaults to ID)"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Primary image URL"}),s.jsx("input",{type:"url",className:"cedros-admin__input",value:b.imageUrl,onChange:A=>j(N=>({...N,imageUrl:A.target.value})),placeholder:"https://..."})]})]}),s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Short description"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:b.description,onChange:A=>j(N=>({...N,description:A.target.value})),placeholder:"e.g., Midweight fleece with relaxed fit",required:!0})]})}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsx(At,{value:b.productType,onChange:A=>j(N=>({...N,productType:A})),options:[{value:"one_time",label:"One-time purchase"},{value:"pay_per_access",label:"Pay per access"},{value:"subscription",label:"Subscription"}],label:"Product Type"}),s.jsx(At,{value:b.fulfillmentType,onChange:A=>{const N=A;j(Z=>({...Z,fulfillmentType:N,checkoutShippingAddress:N==="shipping"?Z.checkoutShippingAddress:!1}))},options:[{value:"shipping",label:"Physical (shipped)"},{value:"digital_download",label:"Digital download"},{value:"service",label:"Service"}],label:"Fulfillment"})]}),b.fulfillmentType==="shipping"&&s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsx(At,{value:b.inventoryStatus,onChange:A=>j(N=>({...N,inventoryStatus:A})),options:[{value:"in_stock",label:"In stock"},{value:"low",label:"Low"},{value:"out_of_stock",label:"Out of stock"},{value:"backorder",label:"Backorder"}],label:"Inventory status"}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Inventory quantity (tracked)"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:b.inventoryQuantity,onChange:A=>j(N=>({...N,inventoryQuantity:A.target.value===""?"":parseInt(A.target.value)||0})),placeholder:"Leave blank for untracked",min:"0"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Compare-at price (USD)"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:b.compareAtUsd===""?"":b.compareAtUsd,onChange:A=>j(N=>({...N,compareAtUsd:A.target.value===""?"":parseFloat(A.target.value)||0})),placeholder:"e.g., 78.00",min:"0",step:"0.01"})]})]}),s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Price (USD)"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:b.priceUsd===""?"":b.priceUsd,onChange:A=>j(N=>({...N,priceUsd:A.target.value===""?"":parseFloat(A.target.value)||0})),placeholder:"e.g., 5.00",min:"0",step:"0.01",required:!0})]})}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Tags (comma-separated)"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:b.tagsCsv,onChange:A=>j(N=>({...N,tagsCsv:A.target.value})),placeholder:"e.g., core, new, gift"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Category IDs (comma-separated)"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:b.categoryIdsCsv,onChange:A=>j(N=>({...N,categoryIdsCsv:A.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"})]})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsx(At,{value:b.checkoutEmail,onChange:A=>j(N=>({...N,checkoutEmail:A})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Email"}),s.jsx(At,{value:b.checkoutName,onChange:A=>j(N=>({...N,checkoutName:A})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Name"}),s.jsx(At,{value:b.checkoutPhone,onChange:A=>j(N=>({...N,checkoutPhone:A})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Phone"})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[b.fulfillmentType==="shipping"&&s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Checkout: Shipping address"}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:b.checkoutShippingAddress,onChange:A=>j(N=>({...N,checkoutShippingAddress:A.target.checked}))}),"Collect shipping address"]})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Checkout: Billing address"}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:b.checkoutBillingAddress,onChange:A=>j(N=>({...N,checkoutBillingAddress:A.target.checked}))}),"Collect billing address"]})]})]}),s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Fulfillment notes"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:b.fulfillmentNotes,onChange:A=>j(N=>({...N,fulfillmentNotes:A.target.value})),placeholder:b.fulfillmentType==="shipping"?"e.g., Ships within 3-5 business days":"e.g., Downloadable from your account after purchase"})]})}),b.fulfillmentType==="shipping"&&b.checkoutShippingAddress&&s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Shipping countries"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:b.shippingCountriesCsv,onChange:A=>j(N=>({...N,shippingCountriesCsv:A.target.value})),placeholder:"e.g., US,CA"}),s.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"ISO 2-letter country codes, comma-separated. Required for shipping address collection."})]})}),s.jsx("div",{className:"cedros-admin__form-actions",children:s.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:f,children:f?"Creating...":"Create Product"})})]}),i?s.jsxs("div",{className:"cedros-admin__loading",children:[Y.loading," Loading products..."]}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":p?.key==="id"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>D("id"),children:["ID",H("id")]})}),s.jsx("th",{"aria-sort":p?.key==="product"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>D("product"),children:["Product",H("product")]})}),s.jsx("th",{"aria-sort":p?.key==="type"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>D("type"),children:["Type",H("type")]})}),s.jsx("th",{"aria-sort":p?.key==="price"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>D("price"),children:["Price",H("price")]})}),s.jsx("th",{"aria-sort":p?.key==="status"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>D("status"),children:["Status",H("status")]})}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:z.map(A=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:A.id})}),s.jsx("td",{children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[C(A)?s.jsx("img",{src:C(A),alt:"",style:{width:28,height:28,borderRadius:6,objectFit:"cover"}}):s.jsx("div",{style:{width:28,height:28,borderRadius:6,background:"rgba(0,0,0,0.06)"}}),s.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[s.jsx("span",{style:{fontWeight:600},children:I(A)}),s.jsx("span",{style:{opacity:.8},children:A.description})]})]})}),s.jsx("td",{children:M(A.metadata?.product_type)}),s.jsx("td",{children:F(A.fiatAmountCents)}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge ${A.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:A.active?"Active":"Inactive"})}),s.jsx("td",{children:s.jsx("div",{style:{display:"flex",gap:"0.25rem"},children:s.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>x(A),children:"Variations"})})})]},A.id))})]})}),y&&s.jsx("div",{className:"cedros-admin__modal-overlay",onClick:()=>x(null),children:s.jsx("div",{className:"cedros-admin__modal cedros-admin__modal--lg",onClick:A=>A.stopPropagation(),children:s.jsx(qf,{serverUrl:e,productId:y.id,productTitle:I(y),defaultPrice:y.fiatAmountCents/100,apiKey:t,authManager:r,onClose:()=>x(null)})})})]})}function Oc({serverUrl:e,apiKey:t,pageSize:n=20,authManager:r}){const[o,a]=k.useState([]),[i,c]=k.useState(null),[l,d]=k.useState(!0),[f,u]=k.useState(!0),[h,g]=k.useState(null),[y,x]=k.useState(""),[p,v]=k.useState(null),_=k.useCallback(async()=>{u(!0);try{g(null);let C;if(r?.isAuthenticated())C=await r.fetchWithAuth("/admin/stats");else{const E={"Content-Type":"application/json"};t&&(E["X-API-Key"]=t);const O=await fetch(`${e}/admin/stats`,{headers:E});if(!O.ok)throw new Error(`Failed to fetch stats: ${O.status}`);C=await O.json()}c(C)}catch{c(null),g("Failed to load payment stats")}finally{u(!1)}},[e,t,r]);k.useEffect(()=>{_()},[_]);const w=k.useCallback(async()=>{try{g(null);let C;const E=new URLSearchParams({limit:n.toString()});y&&E.set("method",y);const O=`/admin/transactions?${E}`;if(r?.isAuthenticated())C=await r.fetchWithAuth(O);else{const F={"Content-Type":"application/json"};t&&(F["X-API-Key"]=t);const M=await fetch(`${e}${O}`,{headers:F});if(!M.ok)throw new Error(`Failed to fetch transactions: ${M.status}`);C=await M.json()}a(C.transactions||[])}catch{a([]),g("Failed to load transactions")}finally{d(!1)}},[e,t,n,y,r]);k.useEffect(()=>{w()},[w]);const b=(C,E="USD")=>new Intl.NumberFormat("en-US",{style:"currency",currency:E}).format(C),j=C=>{v(E=>!E||E.key!==C?{key:C,direction:"asc"}:{key:C,direction:E.direction==="asc"?"desc":"asc"})},R=C=>!p||p.key!==C?s.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Y.chevronUp}):s.jsx("span",{className:"cedros-admin__sort-icon",children:p.direction==="asc"?Y.chevronUp:Y.chevronDown}),I=k.useMemo(()=>{if(!p)return o;const C=p.direction==="asc"?1:-1,E=O=>{switch(p.key){case"resource":return O.resourceId;case"method":return O.method;case"amount":return O.amount;case"status":return O.status;case"date":return new Date(O.paidAt).getTime();case"id":default:return O.id}};return[...o].sort((O,F)=>{const M=E(O),U=E(F);return typeof M=="number"&&typeof U=="number"?(M-U)*C:String(M).localeCompare(String(U),void 0,{sensitivity:"base"})*C})},[o,p]);return s.jsxs("div",{className:"cedros-admin__page",children:[s.jsx(jr,{message:h,onRetry:()=>{_(),w()}}),s.jsx(Sr,{stats:[{label:"Revenue",value:b(i?.totalRevenue??0)},{label:"Orders",value:i?.totalTransactions??0},{label:"Card",value:b(i?.revenueByMethod.stripe??0),description:`${i?.transactionsByMethod.stripe??0} orders`},{label:"Crypto",value:b(i?.revenueByMethod.x402??0),description:`${i?.transactionsByMethod.x402??0} orders`},{label:"Credits",value:b(i?.revenueByMethod.credits??0),description:`${i?.transactionsByMethod.credits??0} orders`}],isLoading:f,onRefresh:_}),s.jsxs("div",{className:"cedros-admin__section-header",children:[s.jsx("h3",{className:"cedros-admin__section-title",children:"Transaction History"}),s.jsx(Pc,{value:y,onChange:x,options:[{value:"",label:"All"},{value:"stripe",label:"Card"},{value:"x402",label:"Crypto"},{value:"credits",label:"Credits"}]})]}),l?s.jsxs("div",{className:"cedros-admin__loading",children:[Y.loading," Loading transactions..."]}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":p?.key==="id"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("id"),children:["ID",R("id")]})}),s.jsx("th",{"aria-sort":p?.key==="resource"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("resource"),children:["Resource",R("resource")]})}),s.jsx("th",{"aria-sort":p?.key==="method"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("method"),children:["Method",R("method")]})}),s.jsx("th",{"aria-sort":p?.key==="amount"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("amount"),children:["Amount",R("amount")]})}),s.jsx("th",{"aria-sort":p?.key==="status"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("status"),children:["Status",R("status")]})}),s.jsx("th",{"aria-sort":p?.key==="date"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("date"),children:["Date",R("date")]})})]})}),s.jsx("tbody",{children:I.map(C=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:C.id})}),s.jsx("td",{children:C.resourceId}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${C.method}`,children:C.method})}),s.jsxs("td",{children:["$",C.amount.toFixed(2)," ",C.currency.toUpperCase()]}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${C.status}`,children:C.status})}),s.jsx("td",{children:lr(C.paidAt)})]},C.id))})]})})]})}function Mc({serverUrl:e,apiKey:t,pageSize:n=20,authManager:r}){const[o,a]=k.useState([]),[i,c]=k.useState(!0),[l,d]=k.useState(!1),[f,u]=k.useState(!1),[h,g]=k.useState(null),[y,x]=k.useState(null),[p,v]=k.useState({code:"",discountType:"percentage",discountValue:0,usageLimit:void 0,expiresAt:"",scope:"all_products",productIdsCsv:"",categoryIdsCsv:"",paymentMethod:"any",autoApply:!1,appliesAt:"both",startsAt:"",minimumAmountUsd:"",usageLimitPerCustomer:void 0,firstPurchaseOnly:!1}),_=k.useCallback(async()=>{try{x(null);let E;const O=`/admin/coupons?limit=${n}`;if(r?.isAuthenticated())E=await r.fetchWithAuth(O);else{const F={"Content-Type":"application/json"};t&&(F["X-API-Key"]=t);const M=await fetch(`${e}${O}`,{headers:F});if(!M.ok)throw new Error(`Failed to fetch coupons: ${M.status}`);E=await M.json()}a(E.coupons||[])}catch(E){Je.getLogger().error("[CouponsSection] Failed to fetch coupons:",E,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),a([]),x("Failed to load coupons")}finally{c(!1)}},[e,t,n,r]);k.useEffect(()=>{_()},[_]);const w=async E=>{if(E.preventDefault(),!(!p.code||p.discountValue<=0)){u(!0);try{const O=p.minimumAmountUsd?Math.round(Number(p.minimumAmountUsd)*100):void 0,F=p.productIdsCsv.split(",").map(D=>D.trim()).filter(Boolean),M=p.categoryIdsCsv.split(",").map(D=>D.trim()).filter(Boolean),U={code:p.code,discountType:p.discountType,discountValue:p.discountValue,usageLimit:p.usageLimit,active:!0,usageCount:0,scope:p.scope,...F.length?{productIds:F}:{},...M.length?{categoryIds:M}:{},...p.paymentMethod!=="any"?{paymentMethod:p.paymentMethod}:{},...p.autoApply?{autoApply:!0}:{},...p.appliesAt!=="both"?{appliesAt:p.appliesAt}:{},...p.startsAt?{startsAt:p.startsAt}:{},...p.expiresAt?{expiresAt:p.expiresAt}:{},...O?{minimumAmountCents:O}:{},...p.usageLimitPerCustomer?{usageLimitPerCustomer:p.usageLimitPerCustomer}:{},...p.firstPurchaseOnly?{firstPurchaseOnly:!0}:{}};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/coupons",{method:"POST",body:JSON.stringify(U)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const H=await fetch(`${e}/admin/coupons`,{method:"POST",headers:D,body:JSON.stringify(U)});if(!H.ok)throw new Error(`Failed to create coupon: ${H.status}`)}v({code:"",discountType:"percentage",discountValue:0,usageLimit:void 0,expiresAt:"",scope:"all_products",productIdsCsv:"",categoryIdsCsv:"",paymentMethod:"any",autoApply:!1,appliesAt:"both",startsAt:"",minimumAmountUsd:"",usageLimitPerCustomer:void 0,firstPurchaseOnly:!1}),d(!1),_()}catch(O){Je.getLogger().error("[CouponsSection] Failed to add coupon:",O,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),x("Failed to create coupon")}finally{u(!1)}}},b=o.filter(E=>E.active).length,j=o.reduce((E,O)=>E+(O.usageCount??0),0),R=E=>{g(O=>!O||O.key!==E?{key:E,direction:"asc"}:{key:E,direction:O.direction==="asc"?"desc":"asc"})},I=E=>!h||h.key!==E?s.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Y.chevronUp}):s.jsx("span",{className:"cedros-admin__sort-icon",children:h.direction==="asc"?Y.chevronUp:Y.chevronDown}),C=k.useMemo(()=>{if(!h)return o;const E=h.direction==="asc"?1:-1,O=F=>{switch(h.key){case"discount":return F.discountValue??0;case"usage":return F.usageCount??0;case"status":return F.active?1:0;case"code":default:return F.code}};return[...o].sort((F,M)=>{const U=O(F),D=O(M);return typeof U=="number"&&typeof D=="number"?(U-D)*E:String(U).localeCompare(String(D),void 0,{sensitivity:"base"})*E})},[o,h]);return s.jsxs("div",{className:"cedros-admin__page",children:[s.jsx(jr,{message:y,onRetry:_}),s.jsx(Sr,{stats:[{label:"Total Coupons",value:o.length},{label:"Active",value:b,variant:b>0?"success":"muted"},{label:"Redemptions",value:j}],isLoading:i}),s.jsxs("div",{className:"cedros-admin__section-header",children:[s.jsx("h3",{className:"cedros-admin__section-title",children:"Discount Coupons"}),s.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:()=>d(!l),children:[l?Y.close:Y.plus,l?"Cancel":"Add Coupon"]})]}),l&&s.jsxs("form",{onSubmit:w,className:"cedros-admin__add-form",children:[s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Coupon Code"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:p.code,onChange:E=>v(O=>({...O,code:E.target.value.toUpperCase()})),placeholder:"e.g., SAVE20",required:!0})]}),s.jsx(At,{value:p.discountType,onChange:E=>v(O=>({...O,discountType:E})),options:[{value:"percentage",label:"Percentage (%)"},{value:"fixed",label:"Fixed Amount ($)"}],label:"Discount Type"})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsxs("label",{className:"cedros-admin__field-label",children:["Discount Value ",p.discountType==="percentage"?"(%)":"($)"]}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:p.discountValue||"",onChange:E=>v(O=>({...O,discountValue:parseFloat(E.target.value)||0})),placeholder:p.discountType==="percentage"?"e.g., 20":"e.g., 10.00",min:"0",step:p.discountType==="percentage"?"1":"0.01",required:!0})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Usage Limit (optional)"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:p.usageLimit||"",onChange:E=>v(O=>({...O,usageLimit:E.target.value?parseInt(E.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Expiration Date (optional)"}),s.jsx("input",{type:"date",className:"cedros-admin__input",value:p.expiresAt,onChange:E=>v(O=>({...O,expiresAt:E.target.value}))})]})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsx(At,{value:p.scope,onChange:E=>v(O=>({...O,scope:E})),options:[{value:"all_products",label:"All Products"},{value:"specific_products",label:"Specific Products"},{value:"specific_categories",label:"Specific Categories"}],label:"Scope"}),s.jsx(At,{value:p.paymentMethod,onChange:E=>v(O=>({...O,paymentMethod:E})),options:[{value:"any",label:"Any Payment Method"},{value:"stripe",label:"Stripe (Card) Only"},{value:"x402",label:"Crypto (x402) Only"},{value:"credits",label:"Credits Only"}],label:"Payment Method"}),s.jsx(At,{value:p.appliesAt,onChange:E=>v(O=>({...O,appliesAt:E})),options:[{value:"both",label:"Cart & Checkout"},{value:"cart",label:"Cart Only"},{value:"checkout",label:"Checkout Only"}],label:"Applies At"})]}),p.scope==="specific_products"&&s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Product IDs"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:p.productIdsCsv,onChange:E=>v(O=>({...O,productIdsCsv:E.target.value})),placeholder:"e.g., prod_123, prod_456"}),s.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated product IDs this coupon applies to."})]})}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Start Date (optional)"}),s.jsx("input",{type:"date",className:"cedros-admin__input",value:p.startsAt,onChange:E=>v(O=>({...O,startsAt:E.target.value}))})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Auto Apply"}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:p.autoApply,onChange:E=>v(O=>({...O,autoApply:E.target.checked}))}),"Automatically apply when conditions met"]})]})]}),s.jsxs("div",{className:"cedros-admin__form-row",children:[s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Minimum Purchase (USD)"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:p.minimumAmountUsd===""?"":p.minimumAmountUsd,onChange:E=>v(O=>({...O,minimumAmountUsd:E.target.value===""?"":parseFloat(E.target.value)||0})),placeholder:"e.g., 50.00",min:"0",step:"0.01"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Per-Customer Limit"}),s.jsx("input",{type:"number",className:"cedros-admin__input",value:p.usageLimitPerCustomer||"",onChange:E=>v(O=>({...O,usageLimitPerCustomer:E.target.value?parseInt(E.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),s.jsxs("div",{className:"cedros-admin__field",children:[s.jsx("label",{className:"cedros-admin__field-label",children:"First Purchase Only"}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:p.firstPurchaseOnly,onChange:E=>v(O=>({...O,firstPurchaseOnly:E.target.checked}))}),"New customers only"]})]})]}),p.scope==="specific_categories"&&s.jsx("div",{className:"cedros-admin__form-row",children:s.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[s.jsx("label",{className:"cedros-admin__field-label",children:"Category IDs"}),s.jsx("input",{type:"text",className:"cedros-admin__input",value:p.categoryIdsCsv,onChange:E=>v(O=>({...O,categoryIdsCsv:E.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"}),s.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated category IDs this coupon applies to."})]})}),s.jsx("div",{className:"cedros-admin__form-actions",children:s.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:f,children:f?"Creating...":"Create Coupon"})})]}),i?s.jsxs("div",{className:"cedros-admin__loading",children:[Y.loading," Loading coupons..."]}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":h?.key==="code"?h?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("code"),children:["Code",I("code")]})}),s.jsx("th",{"aria-sort":h?.key==="discount"?h?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("discount"),children:["Discount",I("discount")]})}),s.jsx("th",{"aria-sort":h?.key==="usage"?h?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("usage"),children:["Usage",I("usage")]})}),s.jsx("th",{"aria-sort":h?.key==="status"?h?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>R("status"),children:["Status",I("status")]})}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:C.map(E=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:E.code})}),s.jsx("td",{children:E.discountType==="percentage"?`${E.discountValue}%`:`$${E.discountValue.toFixed(2)}`}),s.jsxs("td",{children:[E.usageCount,E.usageLimit?` / ${E.usageLimit}`:""]}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge ${E.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:E.active?"Active":"Inactive"})}),s.jsx("td",{children:s.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",children:"Edit"})})]},E.code))})]})})]})}function Lc({serverUrl:e,apiKey:t,pageSize:n=20,authManager:r}){const[o,a]=k.useState([]),[i,c]=k.useState(!0),[l,d]=k.useState(null),[f,u]=k.useState([]),[h,g]=k.useState(!0),[y,x]=k.useState(null),[p,v]=k.useState(null),[_,w]=k.useState([]),[b,j]=k.useState(!0),[R,I]=k.useState(null),[C,E]=k.useState(null),[O,F]=k.useState(null),[M,U]=k.useState(""),[D,H]=k.useState(null),z=k.useCallback(async()=>{try{let T;const K=`/admin/refunds?limit=${n}`;if(r?.isAuthenticated())T=await r.fetchWithAuth(K);else{const se={"Content-Type":"application/json"};t&&(se["X-API-Key"]=t);const ve=await fetch(`${e}${K}`,{headers:se});if(!ve.ok)throw new Error(`Failed to fetch x402 refunds: ${ve.status}`);T=await ve.json()}a(T.refunds||[])}catch(T){Je.getLogger().error("[RefundsSection] Failed to fetch x402 refunds:",T,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),a([]),H("Failed to load x402 refunds")}finally{c(!1)}},[e,t,n,r]);k.useEffect(()=>{z()},[z]);const A=k.useCallback(async()=>{try{let T;const K=`/admin/credits/refund-requests?status=pending&limit=${n}&offset=0`;if(r?.isAuthenticated())T=await r.fetchWithAuth(K);else{const ve={"Content-Type":"application/json"};t&&(ve["X-API-Key"]=t);const ye=await fetch(`${e}${K}`,{headers:ve});if(!ye.ok)throw new Error(`Failed to fetch credits refund requests: ${ye.status}`);T=await ye.json()}const se=Array.isArray(T)?T:"refundRequests"in T?T.refundRequests:T.requests||[];u(se)}catch(T){Je.getLogger().error("[RefundsSection] Failed to fetch credits refunds:",T,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),u([]),H("Failed to load credits refunds")}finally{g(!1)}},[e,t,n,r]);k.useEffect(()=>{A()},[A]);const N=async T=>{x(T.id);try{const K=`/admin/credits/refund-requests/${T.id}/process`,se=JSON.stringify({amountLamports:T.amountLamports,reason:T.reason});if(r?.isAuthenticated())await r.fetchWithAuth(K,{method:"POST",body:se});else{const ve={"Content-Type":"application/json"};t&&(ve["X-API-Key"]=t);const ye=await fetch(`${e}${K}`,{method:"POST",headers:ve,body:se});if(!ye.ok)throw new Error(`Failed to process credits refund: ${ye.status}`)}await A()}catch(K){Je.getLogger().error("[RefundsSection] Failed to process credits refund:",K,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,requestId:T.id}),H("Failed to process credits refund")}finally{x(null)}},Z=T=>{U(T.reason??""),F(T)},te=()=>{F(null),U("")},re=async()=>{if(!O)return;const T=O,K=M;te(),x(T.id);try{const se=`/admin/credits/refund-requests/${T.id}/reject`,ve=JSON.stringify({reason:K});if(r?.isAuthenticated())await r.fetchWithAuth(se,{method:"POST",body:ve});else{const ye={"Content-Type":"application/json"};t&&(ye["X-API-Key"]=t);const Pe=await fetch(`${e}${se}`,{method:"POST",headers:ye,body:ve});if(!Pe.ok)throw new Error(`Failed to reject credits refund: ${Pe.status}`)}await A()}catch(se){Je.getLogger().error("[RefundsSection] Failed to reject credits refund:",se,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,requestId:T.id}),H("Failed to reject credits refund")}finally{x(null)}},de=k.useCallback(async()=>{try{let T;const K=`/admin/stripe/refunds?limit=${n}`;if(r?.isAuthenticated())T=await r.fetchWithAuth(K);else{const se={"Content-Type":"application/json"};t&&(se["X-API-Key"]=t);const ve=await fetch(`${e}${K}`,{headers:se});if(!ve.ok)throw new Error(`Failed to fetch Stripe refunds: ${ve.status}`);T=await ve.json()}w(T.refunds||[])}catch(T){Je.getLogger().error("[RefundsSection] Failed to fetch Stripe refunds:",T,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t}),w([]),H("Failed to load Stripe refunds")}finally{j(!1)}},[e,t,n,r]);k.useEffect(()=>{de()},[de]);const W=async T=>{I(T);try{const K=`/admin/stripe/refunds/${T}/process`;if(r?.isAuthenticated())await r.fetchWithAuth(K,{method:"POST"});else{const se={"Content-Type":"application/json"};t&&(se["X-API-Key"]=t);const ve=await fetch(`${e}${K}`,{method:"POST",headers:se});if(!ve.ok)throw new Error(`Failed to process refund: ${ve.status}`)}await de()}catch(K){Je.getLogger().error("[RefundsSection] Failed to process Stripe refund:",K,{serverUrl:e.slice(0,20)+"...",hasApiKey:!!t,refundId:T}),H("Failed to process Stripe refund")}finally{I(null)}},Q=(T,K)=>new Intl.NumberFormat("en-US",{style:"currency",currency:K}).format(T/100),q=T=>T?T.replace(/_/g," ").replace(/\b\w/g,K=>K.toUpperCase()):"—",he=T=>{switch(T){case"processed":return"success";case"pending":return"pending";case"rejected":default:return"muted"}},P=(T,K)=>K?K.toLowerCase()==="usd"?`${new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(T/1e6)} (USD credits)`:`${T.toLocaleString()} ${K.toUpperCase()} (atomic)`:`${T.toLocaleString()} (atomic)`,G=T=>{switch(T){case"succeeded":return"success";case"failed":return"failed";case"pending":case"requires_action":return"pending";case"canceled":default:return"muted"}},ue=T=>T.stripeRefundId??"—",B=T=>T.chargeId??"—",ae=_.filter(T=>T.status==="pending"||T.status==="requires_action").length,ce=f.filter(T=>T.status==="pending").length,we=o.filter(T=>T.status==="pending").length,Te=ae+ce+we,Ve=_.filter(T=>T.status==="succeeded").reduce((T,K)=>T+K.amount,0),Ge=f.filter(T=>T.status==="processed").reduce((T,K)=>T+K.amountLamports,0),We=o.filter(T=>T.status==="completed").reduce((T,K)=>T+K.amount,0),_t=Ve/100+Ge/1e6+We,Ye=T=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(T),en=b||h||i,xt=T=>{E(K=>!K||K.key!==T?{key:T,direction:"asc"}:{key:T,direction:K.direction==="asc"?"desc":"asc"})},je=T=>{v(K=>!K||K.key!==T?{key:T,direction:"asc"}:{key:T,direction:K.direction==="asc"?"desc":"asc"})},Xe=T=>{d(K=>!K||K.key!==T?{key:T,direction:"asc"}:{key:T,direction:K.direction==="asc"?"desc":"asc"})},_e=(T,K)=>!T||!K?s.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:Y.chevronUp}):s.jsx("span",{className:"cedros-admin__sort-icon",children:K==="asc"?Y.chevronUp:Y.chevronDown}),Zt=k.useMemo(()=>{if(!C)return _;const T=C.direction==="asc"?1:-1,K=se=>{switch(C.key){case"stripe":return se.stripeRefundId??"";case"charge":return se.chargeId??"";case"amount":return se.amount??0;case"reason":return se.reason??"";case"status":return se.status??"";case"date":return new Date(se.createdAt).getTime();case"id":default:return se.id}};return[..._].sort((se,ve)=>{const ye=K(se),Pe=K(ve);return typeof ye=="number"&&typeof Pe=="number"?(ye-Pe)*T:String(ye).localeCompare(String(Pe),void 0,{sensitivity:"base"})*T})},[_,C]),ft=k.useMemo(()=>{if(!p)return f;const T=p.direction==="asc"?1:-1,K=se=>{switch(p.key){case"original":return se.originalTransactionId??"";case"user":return se.userId??"";case"amount":return se.amountLamports??0;case"reason":return se.reason??"";case"status":return se.status??"";case"date":return new Date(se.createdAt).getTime();case"id":default:return se.id}};return[...f].sort((se,ve)=>{const ye=K(se),Pe=K(ve);return typeof ye=="number"&&typeof Pe=="number"?(ye-Pe)*T:String(ye).localeCompare(String(Pe),void 0,{sensitivity:"base"})*T})},[f,p]),it=k.useMemo(()=>{if(!l)return o;const T=l.direction==="asc"?1:-1,K=se=>{switch(l.key){case"transaction":return se.transactionId??"";case"amount":return se.amount??0;case"reason":return se.reason??"";case"status":return se.status??"";case"date":return new Date(se.createdAt).getTime();case"id":default:return se.id}};return[...o].sort((se,ve)=>{const ye=K(se),Pe=K(ve);return typeof ye=="number"&&typeof Pe=="number"?(ye-Pe)*T:String(ye).localeCompare(String(Pe),void 0,{sensitivity:"base"})*T})},[o,l]);return s.jsxs("div",{className:"cedros-admin__page",children:[s.jsx(jr,{message:D,onRetry:()=>{z(),A(),de()}}),s.jsx(Sr,{stats:[{label:"Pending",value:Te,variant:Te>0?"warning":"muted"},{label:"Card Pending",value:ae,description:"Stripe"},{label:"Credits Pending",value:ce},{label:"Crypto Pending",value:we,description:"x402"},{label:"Total Refunded",value:Ye(_t),variant:"success"}],isLoading:en}),s.jsx("div",{className:"cedros-admin__section-header",children:s.jsx("h3",{className:"cedros-admin__section-title",children:"Stripe Refund Requests"})}),b?s.jsxs("div",{className:"cedros-admin__loading",children:[Y.loading," Loading Stripe refunds..."]}):_.length===0?s.jsx("div",{className:"cedros-admin__empty",children:"No Stripe refund requests found."}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":C?.key==="id"?C?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("id"),children:["Request ID",_e(C?.key==="id",C?.direction)]})}),s.jsx("th",{"aria-sort":C?.key==="stripe"?C?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("stripe"),children:["Stripe Refund ID",_e(C?.key==="stripe",C?.direction)]})}),s.jsx("th",{"aria-sort":C?.key==="charge"?C?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("charge"),children:["Charge",_e(C?.key==="charge",C?.direction)]})}),s.jsx("th",{"aria-sort":C?.key==="amount"?C?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("amount"),children:["Amount",_e(C?.key==="amount",C?.direction)]})}),s.jsx("th",{"aria-sort":C?.key==="reason"?C?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("reason"),children:["Reason",_e(C?.key==="reason",C?.direction)]})}),s.jsx("th",{"aria-sort":C?.key==="status"?C?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("status"),children:["Status",_e(C?.key==="status",C?.direction)]})}),s.jsx("th",{"aria-sort":C?.key==="date"?C?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>xt("date"),children:["Date",_e(C?.key==="date",C?.direction)]})}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:Zt.map(T=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:T.id})}),s.jsx("td",{children:s.jsx("code",{children:ue(T)})}),s.jsx("td",{children:s.jsx("code",{children:B(T)})}),s.jsx("td",{children:Q(T.amount,T.currency)}),s.jsx("td",{children:q(T.reason)}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${G(T.status)}`,children:T.status})}),s.jsx("td",{children:lr(T.createdAt)}),s.jsx("td",{children:(T.status==="pending"||T.status==="requires_action")&&s.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",onClick:()=>W(T.id),disabled:R===T.id,children:R===T.id?"Processing...":"Process"})})]},T.id))})]})}),s.jsx("div",{className:"cedros-admin__section-header",style:{marginTop:"2rem"},children:s.jsx("h3",{className:"cedros-admin__section-title",children:"Credits Refund Requests"})}),h?s.jsxs("div",{className:"cedros-admin__loading",children:[Y.loading," Loading credits refunds..."]}):f.length===0?s.jsx("div",{className:"cedros-admin__empty",children:"No credits refund requests found."}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":p?.key==="id"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>je("id"),children:["Request ID",_e(p?.key==="id",p?.direction)]})}),s.jsx("th",{"aria-sort":p?.key==="original"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>je("original"),children:["Original Tx",_e(p?.key==="original",p?.direction)]})}),s.jsx("th",{"aria-sort":p?.key==="user"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>je("user"),children:["User",_e(p?.key==="user",p?.direction)]})}),s.jsx("th",{"aria-sort":p?.key==="amount"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>je("amount"),children:["Amount",_e(p?.key==="amount",p?.direction)]})}),s.jsx("th",{"aria-sort":p?.key==="reason"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>je("reason"),children:["Reason",_e(p?.key==="reason",p?.direction)]})}),s.jsx("th",{"aria-sort":p?.key==="status"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>je("status"),children:["Status",_e(p?.key==="status",p?.direction)]})}),s.jsx("th",{"aria-sort":p?.key==="date"?p?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>je("date"),children:["Date",_e(p?.key==="date",p?.direction)]})}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:ft.map(T=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:T.id})}),s.jsx("td",{children:s.jsx("code",{children:T.originalTransactionId})}),s.jsx("td",{children:s.jsx("code",{children:T.userId??"—"})}),s.jsx("td",{children:P(T.amountLamports,T.currency)}),s.jsx("td",{children:T.reason??"—"}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${he(T.status)}`,children:T.status})}),s.jsx("td",{children:lr(T.createdAt)}),s.jsx("td",{children:T.status==="pending"?s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",onClick:()=>N(T),disabled:y===T.id,children:y===T.id?"Processing...":"Process"}),s.jsx("button",{className:"cedros-admin__button cedros-admin__button--outline cedros-admin__button--danger cedros-admin__button--sm",onClick:()=>Z(T),disabled:y===T.id,children:"Reject"})]}):null})]},T.id))})]})}),s.jsx("div",{className:"cedros-admin__section-header",style:{marginTop:"2rem"},children:s.jsx("h3",{className:"cedros-admin__section-title",children:"x402 Refund Requests"})}),i?s.jsxs("div",{className:"cedros-admin__loading",children:[Y.loading," Loading x402 refunds..."]}):o.length===0?s.jsx("div",{className:"cedros-admin__empty",children:"No x402 refund requests found."}):s.jsx("div",{className:"cedros-admin__table-container",children:s.jsxs("table",{className:"cedros-admin__table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"aria-sort":l?.key==="id"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("id"),children:["ID",_e(l?.key==="id",l?.direction)]})}),s.jsx("th",{"aria-sort":l?.key==="transaction"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("transaction"),children:["Transaction",_e(l?.key==="transaction",l?.direction)]})}),s.jsx("th",{"aria-sort":l?.key==="amount"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("amount"),children:["Amount",_e(l?.key==="amount",l?.direction)]})}),s.jsx("th",{"aria-sort":l?.key==="reason"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("reason"),children:["Reason",_e(l?.key==="reason",l?.direction)]})}),s.jsx("th",{"aria-sort":l?.key==="status"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("status"),children:["Status",_e(l?.key==="status",l?.direction)]})}),s.jsx("th",{"aria-sort":l?.key==="date"?l?.direction==="asc"?"ascending":"descending":"none",children:s.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>Xe("date"),children:["Date",_e(l?.key==="date",l?.direction)]})}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:it.map(T=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:T.id})}),s.jsx("td",{children:s.jsx("code",{children:T.transactionId})}),s.jsxs("td",{children:["$",T.amount.toFixed(2)]}),s.jsx("td",{children:T.reason||"—"}),s.jsx("td",{children:s.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${T.status}`,children:T.status})}),s.jsx("td",{children:lr(T.createdAt)}),s.jsx("td",{})]},T.id))})]})}),O&&s.jsx("div",{className:"cedros-admin__modal-overlay",onClick:te,children:s.jsxs("div",{className:"cedros-admin__modal",onClick:T=>T.stopPropagation(),children:[s.jsxs("div",{className:"cedros-admin__modal-header",children:[s.jsx("h3",{className:"cedros-admin__modal-title",children:"Reject Refund Request"}),s.jsx("button",{type:"button",className:"cedros-admin__modal-close",onClick:te,"aria-label":"Close",children:Y.close})]}),s.jsxs("div",{className:"cedros-admin__modal-body",children:[s.jsxs("p",{style:{marginBottom:"1rem",color:"var(--admin-muted)"},children:["Rejecting refund request ",s.jsx("code",{children:O.id})," for ",P(O.amountLamports,O.currency),"."]}),s.jsxs("label",{className:"cedros-admin__form-field",children:[s.jsx("span",{className:"cedros-admin__form-label",children:"Reason (optional)"}),s.jsx("textarea",{className:"cedros-admin__input",value:M,onChange:T=>U(T.target.value),placeholder:"Enter rejection reason...",rows:3,style:{resize:"vertical"}})]})]}),s.jsxs("div",{className:"cedros-admin__modal-footer",children:[s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--outline",onClick:te,children:"Cancel"}),s.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--danger",onClick:re,children:"Reject Refund"})]})]})})]})}const Gf=k.lazy(()=>Promise.resolve().then(()=>require("./SettingsSection-DrzGdvHH.js")).then(e=>({default:e.SettingsSection})));function Dc(e){return s.jsx(k.Suspense,{fallback:null,children:s.jsx(Gf,{...e})})}class $c{serverUrl;walletSigner=null;jwtToken=null;isAdminUser=!1;constructor(t){this.serverUrl=t}getAuthMethod(){return this.walletSigner?.publicKey&&this.walletSigner.signMessage?"wallet":this.jwtToken&&this.isAdminUser?"cedros-login":"none"}isAuthenticated(){return this.getAuthMethod()!=="none"}setWalletSigner(t){this.walletSigner=t,Je.getLogger().debug("[AdminAuthManager] Wallet signer updated:",!!t?.publicKey)}setCedrosLoginAuth(t,n){this.jwtToken=t,this.isAdminUser=n??!1,Je.getLogger().debug("[AdminAuthManager] Cedros-login auth updated:",{hasToken:!!t,isAdmin:this.isAdminUser})}async createAuthHeaders(t){const n=this.getAuthMethod();if(n==="wallet")return this.createWalletAuthHeaders(t);if(n==="cedros-login")return this.createJwtAuthHeaders();throw new Error("No admin authentication configured. Connect a wallet or sign in as admin.")}async createWalletAuthHeaders(t){if(!this.walletSigner?.publicKey||!this.walletSigner.signMessage)throw new Error("Wallet not connected or does not support message signing");const n=await this.fetchNonce(t),r=new TextEncoder().encode(n.nonce_id),o=await this.walletSigner.signMessage(r),a=oi.bs58.encode(this.walletSigner.publicKey.toBytes()),i=oi.bs58.encode(o);return{"X-Signer":a,"X-Message":n.nonce_id,"X-Signature":i}}createJwtAuthHeaders(){if(!this.jwtToken)throw new Error("No JWT token available");return{Authorization:`Bearer ${this.jwtToken}`}}async fetchNonce(t){const n=`${this.serverUrl}/paywall/v1/nonce`;Je.getLogger().debug("[AdminAuthManager] Fetching nonce for purpose:",t);const r=await Je.fetchWithTimeout(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({purpose:t})});if(!r.ok){const o=await r.text();throw new Error(`Failed to fetch nonce: ${r.status} ${o}`)}return await r.json()}async fetchWithAuth(t,n={}){if(this.getAuthMethod()==="none")throw new Error("No admin authentication configured");const o=this.getPurposeFromPath(t,n.method||"GET"),a=await this.createAuthHeaders(o),i=(n.method||"GET").toUpperCase(),c={...i!=="GET"&&i!=="HEAD"?{"Content-Type":"application/json"}:{},...n.headers||{},...a},l=await Je.fetchWithTimeout(`${this.serverUrl}${t}`,{...n,headers:c});if(!l.ok){let d=`Admin API error ${l.status}`;try{const f=await l.json();f&&typeof f.error=="string"?d=f.error:f&&typeof f.message=="string"&&(d=f.message)}catch{}throw new Error(d)}return await l.json()}getPurposeFromPath(t,n){const o={"/admin/stats":{GET:"admin_stats"},"/admin/products":{GET:"admin_products_list",POST:"admin_products_create"},"/admin/transactions":{GET:"admin_transactions_list"},"/admin/coupons":{GET:"admin_coupons_list",POST:"admin_coupons_create"},"/admin/refunds":{GET:"admin_refunds_list"},"/admin/config":{GET:"admin_config_list"}}[t];if(o?.[n])return o[n];if(t.startsWith("/admin/products/")){if(n==="PUT")return"admin_products_update";if(n==="DELETE")return"admin_products_delete"}if(t.startsWith("/admin/coupons/")){if(n==="PUT")return"admin_coupons_update";if(n==="DELETE")return"admin_coupons_delete"}if(t.startsWith("/admin/refunds/")&&t.includes("/process"))return"admin_refunds_process";if(t.startsWith("/admin/config/")){if(n==="GET")return"admin_config_get";if(n==="PUT")return"admin_config_update";if(n==="PATCH")return"admin_config_patch"}return`admin_${n.toLowerCase()}`}}const Yf={publicKey:null};function Qf({serverUrl:e,cedrosLoginToken:t,isAdmin:n=!1,wallet:r=Yf}){const o=k.useMemo(()=>{const u=new $c(e);return u.setCedrosLoginAuth(t??null,n),u},[e,t,n]);k.useEffect(()=>{r.publicKey&&r.signMessage?o.setWalletSigner({publicKey:r.publicKey,signMessage:r.signMessage}):o.setWalletSigner(null)},[o,r.publicKey,r.signMessage]);const a=o.getAuthMethod(),i=o.isAuthenticated(),c=!!(r.publicKey&&r.signMessage),l=!!t,d=k.useMemo(()=>{if(!r.publicKey)return null;const u=r.publicKey.toBase58();return`${u.slice(0,4)}...${u.slice(-4)}`},[r.publicKey]),f=k.useCallback((u,h)=>o.fetchWithAuth(u,h),[o]);return{authMethod:a,isAuthenticated:i,walletConnected:c,walletAddress:d,cedrosLoginAvailable:l,authManager:o,fetchWithAuth:f}}const Kf=k.lazy(()=>Promise.resolve().then(()=>require("./SubscriptionsSection-CYJpArJ8.js")).then(e=>({default:e.SubscriptionsSection}))),Jf=k.lazy(()=>Promise.resolve().then(()=>require("./StorefrontSection-DTpZ_GgO.js")).then(e=>({default:e.StorefrontSection}))),Xf=k.lazy(()=>Promise.resolve().then(()=>require("./AISettingsSection-BtOxEweU.js")).then(e=>({default:e.AISettingsSection}))),em=k.lazy(()=>Promise.resolve().then(()=>require("./PaymentSettingsSection-Cmmuhmd4.js")).then(e=>({default:e.PaymentSettingsSection}))),tm=k.lazy(()=>Promise.resolve().then(()=>require("./MessagingSection-B6EHvjDw.js")).then(e=>({default:e.MessagingSection}))),nm=k.lazy(()=>Promise.resolve().then(()=>require("./FAQSection-DQpF7hVx.js")).then(e=>({default:e.FAQSection}))),zc=[{label:"Menu",sections:[{id:"transactions",label:"Transactions",icon:Y.transactions},{id:"products",label:"Products",icon:Y.products},{id:"subscriptions",label:"Subscriptions",icon:Y.calendarRepeat},{id:"coupons",label:"Coupons",icon:Y.coupons},{id:"refunds",label:"Refunds",icon:Y.refunds}]},{label:"Configuration",collapsible:!0,sections:[{id:"storefront",label:"Storefront",icon:Y.storefront},{id:"ai-settings",label:"Store AI",icon:Y.brain},{id:"faqs",label:"Knowledge Base",icon:Y.faq},{id:"payment-settings",label:"Payment Options",icon:Y.creditCard},{id:"messaging",label:"Store Messages",icon:Y.mail},{id:"settings",label:"Store Server",icon:Y.server}]}],rm=zc.flatMap(e=>e.sections);function sm(){const[e,t]=k.useState(()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");return k.useEffect(()=>{const n=window.matchMedia("(prefers-color-scheme: dark)"),r=o=>t(o.matches?"dark":"light");return n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),e}function om(e,t,n){return e!=="system"?e:t||n}function am({serverUrl:e,apiKey:t,title:n="Cedros Pay",sections:r=["transactions","products","subscriptions","coupons","refunds","storefront","ai-settings","faqs","payment-settings","messaging","settings"],defaultSection:o="transactions",refreshInterval:a=3e4,pageSize:i=20,onSectionChange:c,className:l="",cedrosLoginToken:d,isAdmin:f=!1,theme:u="system"}){const[h,g]=k.useState(o),[y]=k.useState(!1),[x,p]=k.useState(new Set),v=k.useCallback(M=>{p(U=>{const D=new Set(U);return D.has(M)?D.delete(M):D.add(M),D})},[]),_=Je.useCedrosThemeOptional(),w=sm(),j=om(u,_?.mode??null,w)==="dark"?"cedros-admin--dark":"",R=zf.useWallet(),{authManager:I,isAuthenticated:C}=Qf({serverUrl:e,cedrosLoginToken:d,isAdmin:f,wallet:R}),E=k.useCallback(M=>{g(M),c?.(M)},[c]),F=rm.filter(M=>r.includes(M.id)).find(M=>M.id===h);return y?s.jsxs("div",{className:`cedros-admin cedros-admin--loading ${j} ${l}`,children:[Y.loading,s.jsx("span",{className:"cedros-admin__loading-text",children:"Loading dashboard..."})]}):C?s.jsxs("div",{className:`cedros-admin ${j} ${l}`,children:[s.jsxs("aside",{className:"cedros-admin__sidebar",children:[s.jsx("div",{className:"cedros-admin__sidebar-header",children:s.jsxs("div",{className:"cedros-admin__logo",children:[Y.wallet,s.jsx("span",{className:"cedros-admin__logo-text",children:n})]})}),s.jsx("nav",{className:"cedros-admin__nav",children:zc.map(M=>{const U=M.sections.filter(H=>r.includes(H.id));if(U.length===0)return null;const D=M.collapsible&&x.has(M.label);return s.jsxs("div",{className:"cedros-admin__nav-group",children:[M.collapsible?s.jsxs("button",{type:"button",className:"cedros-admin__nav-label cedros-admin__nav-label--collapsible",onClick:()=>v(M.label),"aria-expanded":!D,children:[M.label,s.jsx("span",{className:`cedros-admin__nav-label-icon ${D?"":"cedros-admin__nav-label-icon--expanded"}`,children:Y.chevronRight})]}):s.jsx("span",{className:"cedros-admin__nav-label",children:M.label}),!D&&U.map(H=>s.jsxs("button",{type:"button",className:`cedros-admin__nav-item ${h===H.id?"cedros-admin__nav-item--active":""}`,onClick:()=>E(H.id),"aria-current":h===H.id?"page":void 0,children:[s.jsx("span",{className:"cedros-admin__nav-icon",children:H.icon}),s.jsx("span",{className:"cedros-admin__nav-text",children:H.label})]},H.id))]},M.label)})})]}),s.jsxs("main",{className:"cedros-admin__main",children:[s.jsx("header",{className:"cedros-admin__header",children:s.jsxs("div",{className:"cedros-admin__breadcrumb",children:[s.jsx("span",{className:"cedros-admin__breadcrumb-root",children:n}),s.jsx("span",{className:"cedros-admin__breadcrumb-sep",children:Y.chevronRight}),s.jsx("span",{className:"cedros-admin__breadcrumb-current",children:F?.label})]})}),s.jsxs("div",{className:"cedros-admin__content",children:[h==="products"&&s.jsx(Rc,{serverUrl:e,apiKey:t,pageSize:i,authManager:I}),h==="subscriptions"&&s.jsx(k.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(Kf,{serverUrl:e,apiKey:t,authManager:I})}),h==="transactions"&&s.jsx(Oc,{serverUrl:e,apiKey:t,pageSize:i,authManager:I}),h==="coupons"&&s.jsx(Mc,{serverUrl:e,apiKey:t,pageSize:i,authManager:I}),h==="refunds"&&s.jsx(Lc,{serverUrl:e,apiKey:t,pageSize:i,authManager:I}),h==="storefront"&&s.jsx(k.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(Jf,{serverUrl:e,apiKey:t,authManager:I})}),h==="ai-settings"&&s.jsx(k.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(Xf,{serverUrl:e,apiKey:t,authManager:I})}),h==="faqs"&&s.jsx(k.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(nm,{serverUrl:e,apiKey:t,pageSize:i,authManager:I})}),h==="payment-settings"&&s.jsx(k.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(em,{serverUrl:e,apiKey:t,authManager:I})}),h==="messaging"&&s.jsx(k.Suspense,{fallback:s.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:s.jsx(tm,{serverUrl:e,apiKey:t,authManager:I})}),h==="settings"&&s.jsx(Dc,{serverUrl:e,apiKey:t,authManager:I})]})]})]}):s.jsx("div",{className:`cedros-admin cedros-admin--unauthenticated ${j} ${l}`,children:s.jsx("p",{className:"cedros-admin__auth-prompt",children:"Please connect a wallet or sign in as admin to access the dashboard."})})}const kt=e=>k.lazy(async()=>{const r=(await e()).default;return{default:({pluginContext:a})=>{const c=Ff.useCedrosLogin()?._internal?.getAccessToken()??a.getAccessToken(),l=k.useMemo(()=>{const f=new $c(a.serverUrl);return f.setCedrosLoginAuth(c??null,!!c),f},[a.serverUrl,c]),d={serverUrl:a.serverUrl,authManager:l};return s.jsx(r,{...d})}}}),im={id:"cedros-pay",name:"Cedros Pay",version:"1.0.0",sections:[{id:"transactions",label:"Transactions",icon:Y.transactions,group:"Store",order:0},{id:"products",label:"Products",icon:Y.products,group:"Store",order:1},{id:"subscriptions",label:"Subscriptions",icon:Y.subscriptions,group:"Store",order:2},{id:"coupons",label:"Coupons",icon:Y.coupons,group:"Store",order:3},{id:"refunds",label:"Refunds",icon:Y.refunds,group:"Store",order:4},{id:"storefront",label:"Storefront",icon:Y.storefront,group:"Configuration",order:10},{id:"ai-settings",label:"Store AI",icon:Y.ai,group:"Configuration",order:11},{id:"faqs",label:"Knowledge Base",icon:Y.faq,group:"Configuration",order:12},{id:"payment-settings",label:"Payment Options",icon:Y.wallet,group:"Configuration",order:13},{id:"messaging",label:"Store Messages",icon:Y.notifications,group:"Configuration",order:14},{id:"settings",label:"Store Server",icon:Y.settings,group:"Configuration",order:15}],groups:[{id:"Store",label:"Store",order:1},{id:"Configuration",label:"Configuration",order:2,defaultCollapsed:!0}],components:{products:kt(()=>Promise.resolve().then(()=>require("./sections-CR7NRsjq.js")).then(e=>({default:e.ProductsSection}))),subscriptions:kt(()=>Promise.resolve().then(()=>require("./SubscriptionsSection-CYJpArJ8.js")).then(e=>({default:e.SubscriptionsSection}))),transactions:kt(()=>Promise.resolve().then(()=>require("./sections-CR7NRsjq.js")).then(e=>({default:e.TransactionsSection}))),coupons:kt(()=>Promise.resolve().then(()=>require("./sections-CR7NRsjq.js")).then(e=>({default:e.CouponsSection}))),refunds:kt(()=>Promise.resolve().then(()=>require("./sections-CR7NRsjq.js")).then(e=>({default:e.RefundsSection}))),storefront:kt(()=>Promise.resolve().then(()=>require("./StorefrontSection-DTpZ_GgO.js")).then(e=>({default:e.StorefrontSection}))),"ai-settings":kt(()=>Promise.resolve().then(()=>require("./AISettingsSection-BtOxEweU.js")).then(e=>({default:e.AISettingsSection}))),faqs:kt(()=>Promise.resolve().then(()=>require("./FAQSection-DQpF7hVx.js")).then(e=>({default:e.FAQSection}))),"payment-settings":kt(()=>Promise.resolve().then(()=>require("./PaymentSettingsSection-Cmmuhmd4.js")).then(e=>({default:e.PaymentSettingsSection}))),messaging:kt(()=>Promise.resolve().then(()=>require("./MessagingSection-B6EHvjDw.js")).then(e=>({default:e.MessagingSection}))),settings:kt(()=>Promise.resolve().then(()=>require("./SettingsSection-DrzGdvHH.js")).then(e=>({default:e.SettingsSection})))},createPluginContext(e){const t=e.cedrosPay,n=e.cedrosLogin;return{serverUrl:t?.serverUrl||n?.serverUrl||"",userId:n?.user?.id,getAccessToken:()=>n?.getAccessToken?.()||t?.jwtToken||null,hasPermission:o=>this.checkPermission(o,e),orgId:e.org?.orgId,pluginData:{walletAddress:t?.walletAddress}}},checkPermission(e,t){return t.org?.permissions?t.org.permissions.includes(e):!!(t.cedrosLogin?.user||t.cedrosPay?.jwtToken||t.cedrosPay?.walletAddress)},cssNamespace:"cedros-dashboard"},Fc=[{id:"transactions",qualifiedId:"cedros-pay:transactions",label:"Transactions",group:"Store",order:0,endpoints:["GET /admin/transactions"]},{id:"products",qualifiedId:"cedros-pay:products",label:"Products",group:"Store",order:1,endpoints:["GET /admin/products","POST /admin/products","PUT /admin/products/{id}","DELETE /admin/products/{id}"]},{id:"subscriptions",qualifiedId:"cedros-pay:subscriptions",label:"Subscriptions",group:"Store",order:2,endpoints:["GET /admin/subscriptions","POST /admin/subscriptions","PUT /admin/subscriptions/{id}"]},{id:"coupons",qualifiedId:"cedros-pay:coupons",label:"Coupons",group:"Store",order:3,endpoints:["GET /admin/coupons","POST /admin/coupons","PUT /admin/coupons/{id}","DELETE /admin/coupons/{id}"]},{id:"refunds",qualifiedId:"cedros-pay:refunds",label:"Refunds",group:"Store",order:4,endpoints:["GET /admin/refunds","POST /admin/refunds/{id}/approve","POST /admin/refunds/{id}/deny"]},{id:"storefront",qualifiedId:"cedros-pay:storefront",label:"Storefront",group:"Configuration",order:10,endpoints:["GET /admin/config/shop","PUT /admin/config/shop"]},{id:"ai-settings",qualifiedId:"cedros-pay:ai-settings",label:"Store AI",group:"Configuration",order:11,endpoints:["GET /admin/config/ai","PUT /admin/config/ai/api-key","PUT /admin/config/ai/assignment","PUT /admin/config/ai/prompt"]},{id:"faqs",qualifiedId:"cedros-pay:faqs",label:"Knowledge Base",group:"Configuration",order:12,endpoints:["GET /admin/faqs","POST /admin/faqs","PUT /admin/faqs/{id}","DELETE /admin/faqs/{id}"]},{id:"payment-settings",qualifiedId:"cedros-pay:payment-settings",label:"Payment Options",group:"Configuration",order:13,endpoints:["GET /admin/config/stripe","PUT /admin/config/stripe","GET /admin/config/x402","PUT /admin/config/x402","GET /admin/config/cedros_login","PUT /admin/config/cedros_login"]},{id:"messaging",qualifiedId:"cedros-pay:messaging",label:"Store Messages",group:"Configuration",order:14,endpoints:["GET /admin/config/messaging","PUT /admin/config/messaging"]},{id:"settings",qualifiedId:"cedros-pay:settings",label:"Store Server",group:"Configuration",order:15,endpoints:["GET /admin/config/server","PUT /admin/config/server"]}],cm=Fc.map(e=>e.qualifiedId),lm=[{id:"Store",label:"Store",order:1,defaultCollapsed:!1},{id:"Configuration",label:"Configuration",order:2,defaultCollapsed:!0}],qo=k.createContext(null);function Ee(){const e=k.useContext(qo);if(!e)throw new Error("useCedrosShop must be used within CedrosShopProvider");return e}function Go(){return k.useContext(qo)}function dm({config:e,children:t}){const n=k.useMemo(()=>({config:e}),[e]);return s.jsx(qo.Provider,{value:n,children:t})}function jt(e){return new Promise(t=>setTimeout(t,e))}const Uc=[{id:"cat_all",slug:"all",name:"All Products",description:"Everything in the catalog."},{id:"cat_apparel",slug:"apparel",name:"Apparel",description:"Soft goods and daily wear."},{id:"cat_accessories",slug:"accessories",name:"Accessories",description:"Carry, attach, decorate."}],Kr=[{id:"p_tee",slug:"cedros-tee",title:"Cedros Tee",description:"A heavyweight tee with a clean silhouette.",images:[{url:"https://picsum.photos/seed/cedros-tee/900/900",alt:"Cedros Tee"},{url:"https://picsum.photos/seed/cedros-tee-2/900/900",alt:"Cedros Tee detail"}],price:38,currency:"USD",tags:["new","cotton"],categoryIds:["cat_apparel"],compareAtPrice:48,inventoryStatus:"in_stock",variants:[{id:"v_tee_s",title:"Small / Black",options:{Size:"S",Color:"Black"}},{id:"v_tee_m",title:"Medium / Black",options:{Size:"M",Color:"Black"}},{id:"v_tee_l",title:"Large / Black",options:{Size:"L",Color:"Black"}}],shippingProfile:"physical"},{id:"p_crewneck",slug:"cedros-crewneck",title:"Cedros Crewneck",description:"Midweight fleece with a relaxed fit and embroidered mark.",images:[{url:"https://picsum.photos/seed/cedros-crewneck/900/900",alt:"Cedros Crewneck"}],price:64,currency:"USD",tags:["fleece","core"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",compareAtPrice:78,variants:[{id:"v_crew_s",title:"Small / Heather",options:{Size:"S",Color:"Heather"}},{id:"v_crew_m",title:"Medium / Heather",options:{Size:"M",Color:"Heather"}},{id:"v_crew_l",title:"Large / Heather",options:{Size:"L",Color:"Heather"}}],shippingProfile:"physical"},{id:"p_hoodie",slug:"cedros-hoodie",title:"Cedros Hoodie",description:"Pullover hoodie with soft interior and structured hood.",images:[{url:"https://picsum.photos/seed/cedros-hoodie/900/900",alt:"Cedros Hoodie"},{url:"https://picsum.photos/seed/cedros-hoodie-2/900/900",alt:"Cedros Hoodie detail"}],price:74,currency:"USD",tags:["fleece","new"],categoryIds:["cat_apparel"],inventoryStatus:"low",variants:[{id:"v_hoodie_s",title:"Small / Black",options:{Size:"S",Color:"Black"}},{id:"v_hoodie_m",title:"Medium / Black",options:{Size:"M",Color:"Black"}},{id:"v_hoodie_l",title:"Large / Black",options:{Size:"L",Color:"Black"}}],shippingProfile:"physical"},{id:"p_cap",slug:"cedros-cap",title:"Cedros Cap",description:"Unstructured cap with adjustable strap and curved brim.",images:[{url:"https://picsum.photos/seed/cedros-cap/900/900",alt:"Cedros Cap"}],price:28,currency:"USD",tags:["core"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_socks",slug:"cedros-socks",title:"Cedros Socks",description:"Rib-knit socks designed for everyday comfort.",images:[{url:"https://picsum.photos/seed/cedros-socks/900/900",alt:"Cedros Socks"}],price:14,currency:"USD",tags:["cotton"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_tote",slug:"cedros-tote",title:"Cedros Tote",description:"Heavy canvas tote with reinforced handles.",images:[{url:"https://picsum.photos/seed/cedros-tote/900/900",alt:"Cedros Tote"}],price:32,currency:"USD",tags:["gift","canvas"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_stickers",slug:"cedros-sticker-pack",title:"Sticker Pack",description:"Five durable vinyl stickers for laptops and water bottles.",images:[{url:"https://picsum.photos/seed/cedros-stickers/900/900",alt:"Sticker Pack"}],price:8,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_keychain",slug:"cedros-keychain",title:"Enamel Keychain",description:"Polished enamel keychain with a subtle mark.",images:[{url:"https://picsum.photos/seed/cedros-keychain/900/900",alt:"Enamel Keychain"}],price:12,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_lanyard",slug:"cedros-lanyard",title:"Woven Lanyard",description:"Soft woven lanyard with swivel clasp.",images:[{url:"https://picsum.photos/seed/cedros-lanyard/900/900",alt:"Woven Lanyard"}],price:10,currency:"USD",tags:["core"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_notebook",slug:"cedros-notebook",title:"Dot Grid Notebook",description:"Lay-flat notebook for sketches, notes, and plans.",images:[{url:"https://picsum.photos/seed/cedros-notebook/900/900",alt:"Dot Grid Notebook"}],price:18,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_waterbottle",slug:"cedros-water-bottle",title:"Insulated Bottle",description:"Vacuum-insulated bottle that keeps drinks cold for hours.",images:[{url:"https://picsum.photos/seed/cedros-bottle/900/900",alt:"Insulated Bottle"}],price:36,currency:"USD",tags:["gift","new"],categoryIds:["cat_accessories"],inventoryStatus:"backorder",shippingProfile:"physical"},{id:"p_posters",slug:"cedros-poster-set",title:"Poster Set",description:"Two prints on thick matte stock.",images:[{url:"https://picsum.photos/seed/cedros-posters/900/900",alt:"Poster Set"}],price:24,currency:"USD",tags:["gift","limited"],categoryIds:["cat_accessories"],inventoryStatus:"out_of_stock",shippingProfile:"physical"},{id:"p_pins",slug:"cedros-pin-set",title:"Pin Set",description:"Two enamel pins with rubber backings.",images:[{url:"https://picsum.photos/seed/cedros-pins/900/900",alt:"Pin Set"}],price:16,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_brandbook",slug:"cedros-brand-book",title:"Brand Book (PDF)",description:"A compact brand book: typography, color, layout, and voice.",images:[{url:"https://picsum.photos/seed/cedros-brandbook/900/900",alt:"Brand Book cover"}],price:19,currency:"USD",tags:["digital"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital",checkoutRequirements:{email:"optional",name:"none",phone:"none",shippingAddress:!1,billingAddress:!1},fulfillment:{type:"digital_download",notes:"This is a digital product and will be downloadable from your account after purchase."}},{id:"p_wallpaper",slug:"cedros-wallpaper-pack",title:"Wallpaper Pack",description:"A set of desktop + mobile wallpapers in multiple colorways.",images:[{url:"https://picsum.photos/seed/cedros-wallpaper/900/900",alt:"Wallpaper Pack"}],price:6,currency:"USD",tags:["digital","new"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital"},{id:"p_longsleeve",slug:"cedros-long-sleeve",title:"Long Sleeve Tee",description:"Soft long sleeve tee with rib cuff and relaxed drape.",images:[{url:"https://picsum.photos/seed/cedros-longsleeve/900/900",alt:"Long Sleeve Tee"}],price:44,currency:"USD",tags:["cotton"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_shorts",slug:"cedros-shorts",title:"Everyday Shorts",description:"Lightweight shorts with a comfortable waistband.",images:[{url:"https://picsum.photos/seed/cedros-shorts/900/900",alt:"Everyday Shorts"}],price:40,currency:"USD",tags:["new"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_beanie",slug:"cedros-beanie",title:"Rib Beanie",description:"Warm rib beanie with a clean folded cuff.",images:[{url:"https://picsum.photos/seed/cedros-beanie/900/900",alt:"Rib Beanie"}],price:20,currency:"USD",tags:["core"],categoryIds:["cat_apparel"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_jacket",slug:"cedros-coach-jacket",title:"Coach Jacket",description:"Lightweight jacket with snap front and subtle sheen.",images:[{url:"https://picsum.photos/seed/cedros-jacket/900/900",alt:"Coach Jacket"}],price:96,currency:"USD",tags:["limited"],categoryIds:["cat_apparel"],inventoryStatus:"backorder",shippingProfile:"physical"},{id:"p_mug",slug:"cedros-mug",title:"Cedros Mug",description:"Stoneware mug with a satin glaze.",images:[{url:"https://picsum.photos/seed/cedros-mug/900/900",alt:"Cedros Mug"}],price:22,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_guide",slug:"cedros-field-guide",title:"Field Guide (Digital)",description:"A short digital guide to shipping delightful checkout flows.",images:[{url:"https://picsum.photos/seed/cedros-guide/900/900",alt:"Field Guide cover"}],price:12,currency:"USD",tags:["digital"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital"}];function um(e,t){let n=e;if(t.category&&t.category!=="all"){const l=Uc.find(d=>d.slug===t.category||d.id===t.category);l&&(n=n.filter(d=>d.categoryIds.includes(l.id)))}if(t.search){const l=t.search.toLowerCase();n=n.filter(d=>d.title.toLowerCase().includes(l)||d.description.toLowerCase().includes(l))}const r=t.filters??{},o=r.tags;if(Array.isArray(o)&&o.length>0){const l=new Set(o.map(String));n=n.filter(d=>d.tags?.some(f=>l.has(f)))}const a=typeof r.priceMin=="number"?r.priceMin:void 0,i=typeof r.priceMax=="number"?r.priceMax:void 0;return typeof a=="number"&&(n=n.filter(l=>l.price>=a)),typeof i=="number"&&(n=n.filter(l=>l.price<=i)),(typeof r.inStock=="boolean"?r.inStock:void 0)===!0&&(n=n.filter(l=>l.inventoryStatus!=="out_of_stock")),n}function fm(e,t){if(!t||t==="featured")return e;const n=[...e];return t==="price_asc"&&n.sort((r,o)=>r.price-o.price),t==="price_desc"&&n.sort((r,o)=>o.price-r.price),n}function mm(e,t,n){const r=(t-1)*n;return{items:e.slice(r,r+n),page:t,pageSize:n,total:e.length,hasNextPage:r+n<e.length}}function pm(e){const t=new Date().toISOString(),n=e.cart.map(o=>{const a=Kr.find(i=>i.id===o.resource||i.slug===o.resource)??Kr[0];return{title:a.title,qty:o.quantity,unitPrice:a.price,currency:e.options.currency,imageUrl:a.images[0]?.url}}),r=n.reduce((o,a)=>o+a.qty*a.unitPrice,0);return{id:`ord_${Math.random().toString(16).slice(2)}`,createdAt:t,status:"paid",total:r,currency:e.options.currency,items:n,receiptUrl:e.options.successUrl}}function hm(){let e=[];const t={};return{async listProducts(n){await jt(150);const r=n.page??1,o=n.pageSize??24,a=um(Kr,n),i=fm(a,n.sort);return mm(i,r,o)},async getProductBySlug(n){return await jt(100),Kr.find(r=>r.slug===n)??null},async listCategories(){return await jt(80),Uc},async getOrderHistory(){return await jt(120),e},async getCart({customerId:n}){return await jt(80),t[n]??{items:[]}},async mergeCart({customerId:n,cart:r}){await jt(120);const o=t[n]??{items:[]},a=new Map,i=l=>{const d=`${l.productId}::${l.variantId??""}`,f=a.get(d);f?a.set(d,{...f,qty:f.qty+l.qty}):a.set(d,l)};for(const l of o.items)i(l);for(const l of r.items)i(l);const c={items:Array.from(a.values()),promoCode:r.promoCode??o.promoCode};return t[n]=c,c},async updateCart({customerId:n,cart:r}){await jt(60),t[n]=r},async createCheckoutSession(n){await jt(250);const r=pm(n);if(e=[r,...e].slice(0,25),n.options.successUrl){const o=new URL(n.options.successUrl,"http://localhost");return o.searchParams.set("demoOrderId",r.id),{kind:"redirect",url:o.toString().replace("http://localhost","")}}return{kind:"custom",data:{orderId:r.id}}},async listSubscriptionTiers(){return await jt(80),[{id:"tier_starter",title:"Starter",description:"For small shops getting started.",priceMonthly:19,priceAnnual:190,currency:"USD",features:["Basic analytics","Email support","1 storefront"]},{id:"tier_growth",title:"Growth",description:"For teams iterating fast.",priceMonthly:49,priceAnnual:490,currency:"USD",features:["Advanced analytics","Priority support","3 storefronts"],isPopular:!0},{id:"tier_enterprise",title:"Enterprise",description:"For high volume and custom needs.",priceMonthly:199,priceAnnual:1990,currency:"USD",features:["SLA","Dedicated success","Unlimited storefronts"]}]},async getSubscriptionStatus(){return await jt(80),{isActive:!1}},async createSubscriptionCheckoutSession(n){return await jt(200),n.successUrl?{kind:"redirect",url:n.successUrl}:{kind:"custom",data:n}}}}const ci=50,gm=4,xm=5,vm=1e4,ym={maxRetries:2,initialDelayMs:100,backoffFactor:2,maxDelayMs:500,jitter:!1};function Bc(e){return e.replace(/[_-]+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function bm(e){return e?e.toUpperCase():"USD"}function wm(e){if(e&&(e==="in_stock"||e==="low"||e==="out_of_stock"||e==="backorder"))return e}function _m(e){if(e&&(e==="physical"||e==="digital"))return e}function km(e){const t=[];if(Array.isArray(e))for(const n of e)typeof n=="string"&&t.push(n);else if(typeof e=="string"){const n=e.trim();if(n.startsWith("["))try{const r=JSON.parse(n);if(Array.isArray(r))for(const o of r)typeof o=="string"&&t.push(o);else t.push(e)}catch{t.push(e)}else t.push(e)}return t.flatMap(n=>n.split(",")).map(n=>n.trim().toUpperCase()).filter(Boolean)}function Tn(e){const t=bm(e.fiatCurrency),n=e.images&&e.images.length?e.images:e.imageUrl?[{url:e.imageUrl,alt:e.title}]:[],r=e.effectiveFiatAmountCents??e.fiatAmountCents??0,o=e.compareAtAmountCents,a=e.metadata?.shippingCountries??e.metadata?.shipping_countries,i=km(a);return{id:e.id,slug:e.slug??e.id,title:e.title??Bc(e.id),description:e.description??"",images:n,price:r/100,currency:t,tags:e.tags??[],categoryIds:e.categoryIds??[],inventoryStatus:wm(e.inventoryStatus),inventoryQuantity:typeof e.inventoryQuantity=="number"?e.inventoryQuantity:void 0,compareAtPrice:typeof o=="number"?o/100:void 0,shippingProfile:_m(e.shippingProfile),checkoutRequirements:e.checkoutRequirements,fulfillment:e.fulfillment,attributes:i.length?{shippingCountries:i.join(",")}:void 0}}function Hr(e){if(Array.isArray(e))return{products:e};const t=e.products??e.items??[],n=e.total??e.count;return{products:t,total:n}}async function Kt(e,t,n,r={}){const{body:o,headers:a,method:i="GET",retryableRead:c=!1,timeoutMs:l=vm}=r,d={};n&&(d["X-API-Key"]=n),a&&Object.assign(d,a);const f=async()=>{const u=await Je.fetchWithTimeout(`${e}${t}`,{body:o,headers:d,method:i},l);if(!u.ok){const h=await u.text().catch(()=>""),g=new Error(`Request failed (${u.status}): ${h}`);throw g.status=u.status,g}return u.json()};return c?Je.retryWithBackoff(f,{...ym,name:`paywall-read-${i.toLowerCase()}`}):f()}async function jm(e,t,n,r){const o=await Kt(e,`/paywall/v1/products?limit=${n}&offset=${r}`,t,{retryableRead:!0});return Hr(o)}async function li(e,t,n,r){const{maxPages:o,pageSize:a}=n;for(let i=0;i<o;i+=1){const c=i*a,{products:l,total:d}=await jm(e,t,a,c);if(l.length===0||r(l))return;const f=typeof d=="number"&&c+l.length>=d,u=l.length<a;if(f||u)return}}function Sm(e){const t=async d=>{const f=d.page??1,u=d.pageSize??24,h=u,g=(f-1)*u,y=new URLSearchParams;y.set("limit",String(h)),y.set("offset",String(g)),d.search&&y.set("search",d.search),d.category&&y.set("category",d.category),d.sort&&y.set("sort",d.sort),d.filters?.inStock&&y.set("in_stock","true"),d.filters?.minPrice!=null&&y.set("min_price",String(d.filters.minPrice)),d.filters?.maxPrice!=null&&y.set("max_price",String(d.filters.maxPrice));const x=d.filters?.tags,p=Array.isArray(x)?x:typeof x=="string"?[x]:[];p.length&&y.set("tags",p.join(","));const v=await Kt(e.serverUrl,`/paywall/v1/products?${y.toString()}`,e.apiKey,{retryableRead:!0}),{products:_,total:w}=Hr(v);return{items:_.map(Tn),page:f,pageSize:u,total:w,hasNextPage:typeof w=="number"?g+h<w:_.length===h}},n=async d=>{try{const f=await Kt(e.serverUrl,`/paywall/v1/products/by-slug/${encodeURIComponent(d)}`,e.apiKey,{retryableRead:!0});return Tn(f)}catch(f){const u=f?.status;if(u!==404&&u!==405)throw f;try{const h=await Kt(e.serverUrl,`/paywall/v1/products/${encodeURIComponent(d)}`,e.apiKey,{retryableRead:!0});return Tn(h)}catch(h){const g=h?.status;if(g!==404&&g!==405)throw h;let y;return await li(e.serverUrl,e.apiKey,{maxPages:gm,pageSize:ci},x=>(y=x.find(p=>p.slug===d||p.id===d),!!y)),y?Tn(y):null}}};return{listProducts:t,getProductBySlug:n,getProductsByIds:async d=>{const f=Array.from(new Set(d.filter(Boolean)));if(f.length===0)return new Map;const u=new Map;try{const y=new URLSearchParams;y.set("ids",f.join(",")),y.set("limit",String(f.length)),y.set("offset","0");const x=await Kt(e.serverUrl,`/paywall/v1/products?${y.toString()}`,e.apiKey,{retryableRead:!0}),{products:p}=Hr(x);for(const v of p){const _=Tn(v);u.set(_.id,_),_.slug&&_.slug!==_.id&&u.set(_.slug,_)}}catch{}const h=f.filter(y=>!u.has(y));if(h.length===0)return u;let g=h;try{const y=new Set(g);if(await li(e.serverUrl,e.apiKey,{maxPages:xm,pageSize:ci},x=>{for(const p of x){const v=Tn(p);!y.has(v.id)&&!(v.slug&&y.has(v.slug))||(u.set(v.id,v),v.slug&&v.slug!==v.id&&u.set(v.slug,v),y.delete(v.id),v.slug&&y.delete(v.slug))}return y.size===0}),g=Array.from(y),g.length===0)return u}catch{}for(const y of g)try{const x=await n(y);x&&(u.set(x.id,x),x.slug&&x.slug!==x.id&&u.set(x.slug,x))}catch{}return u},listCategories:async()=>{const d=await Kt(e.serverUrl,"/paywall/v1/products?limit=500&offset=0",e.apiKey,{retryableRead:!0}),{products:f}=Hr(d),u=new Set;for(const h of f)for(const g of h.categoryIds??[])u.add(g);return Array.from(u).map(h=>({id:h,slug:h,name:Bc(h)}))},getOrderHistory:async()=>[],createCheckoutSession:async d=>{throw new Error("createCheckoutSession is not implemented for paywall adapter")},getStorefrontSettings:async()=>{try{return(await Kt(e.serverUrl,"/paywall/v1/storefront",e.apiKey,{retryableRead:!0})).config??null}catch{return null}},getPaymentMethodsConfig:async()=>{try{const f=(await Kt(e.serverUrl,"/paywall/v1/storefront",e.apiKey,{retryableRead:!0})).paymentMethods;return f?{card:!!f.stripe,crypto:!!f.x402,credits:!!f.credits}:null}catch{return null}},getAIRelatedProducts:async d=>Kt(e.serverUrl,"/admin/ai/related-products",e.apiKey,{method:"POST",body:JSON.stringify(d),headers:{"Content-Type":"application/json"},retryableRead:!1})}}function Cm(e){throw new Error(`Unhandled cart action: ${JSON.stringify(e)}`)}function gn(e){return`${e.productId}::${e.variantId??""}`}const Nm={items:[]};function Am(e,t){switch(t.type){case"cart/hydrate":return t.state;case"cart/add":{const n=Math.max(1,Math.floor(t.qty??1)),r=gn(t.item);return e.items.find(a=>gn(a)===r)?{...e,items:e.items.map(a=>gn(a)===r?{...a,qty:a.qty+n}:a)}:{...e,items:[...e.items,{...t.item,qty:n}]}}case"cart/remove":{const n=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.filter(r=>gn(r)!==n)}}case"cart/setQty":{const n=Math.max(0,Math.floor(t.qty)),r=`${t.productId}::${t.variantId??""}`;return n===0?{...e,items:e.items.filter(o=>gn(o)!==r)}:{...e,items:e.items.map(o=>gn(o)===r?{...o,qty:n}:o)}}case"cart/clear":return{items:[],promoCode:void 0};case"cart/setPromoCode":return{...e,promoCode:t.promoCode||void 0};case"cart/updateHold":{const n=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.map(r=>gn(r)===n?{...r,holdId:t.holdId,holdExpiresAt:t.holdExpiresAt}:r)}}default:return Cm(t)}}function Em(e){return e.reduce((t,n)=>t+n.qty,0)}function Im(e){return e.reduce((t,n)=>t+n.qty*n.unitPrice,0)}function di(){try{return typeof window>"u"?null:window.localStorage}catch{return null}}function Tm(e,t){try{const n=e.getItem(t);return n?JSON.parse(n):null}catch{return null}}function Pm(e,t,n){try{return e.setItem(t,JSON.stringify(n)),!0}catch(r){return console.warn(`[cedros] Failed to write "${t}" to storage`,r),!1}}const Vc=k.createContext(null);function Pt(){const e=k.useContext(Vc);if(!e)throw new Error("useCart must be used within CartProvider");return e}function ui(e){return!!e&&typeof e=="object"&&typeof e.productId=="string"&&e.productId.length>0&&typeof e.qty=="number"&&e.qty>0&&typeof e.unitPrice=="number"&&typeof e.currency=="string"&&typeof e.titleSnapshot=="string"}function Rm({children:e}){const{config:t}=Ee(),n=t.cart?.storageKey??"cedros_shop_cart_v1",r=t.customer?.id,o=t.customer?.isSignedIn??!!r,a=t.cart?.syncDebounceMs??800,i=!!t.adapter.getCartInventoryStatus,[c,l]=k.useReducer(Am,Nm),d=k.useRef(c);d.current=c;const[f,u]=k.useState(!1),h=k.useRef(!1),g=k.useRef(null),y=k.useRef(null);k.useEffect(()=>{const _=di();if(!_)return;const w=Tm(_,n);if(w&&Array.isArray(w.items)){const b=w.items.filter(ui);l({type:"cart/hydrate",state:{items:b,promoCode:typeof w.promoCode=="string"?w.promoCode:void 0}})}u(!0)},[n]),k.useEffect(()=>{if(!f)return;const _=di();_&&Pm(_,n,c)},[c,n,f]),k.useEffect(()=>{if(!f||!o||!r||!t.adapter.mergeCart&&!t.adapter.getCart||(y.current!==r&&(h.current=!1,g.current=null,y.current=r),h.current))return;let _=!1;return(async()=>{try{const w=t.adapter.mergeCart?await t.adapter.mergeCart({customerId:r,cart:d.current}):await t.adapter.getCart({customerId:r});if(_)return;if(w&&Array.isArray(w.items)){h.current=!0;const b={...w,items:w.items.filter(ui)};l({type:"cart/hydrate",state:b}),g.current=JSON.stringify(b)}}catch{_||(h.current=!1)}})(),()=>{_=!0}},[t.adapter,r,f,o]),k.useEffect(()=>{if(!f||!o||!r||!t.adapter.updateCart||!h.current||typeof window>"u")return;const _=JSON.stringify(c);if(g.current===_)return;const w=window.setTimeout(()=>{t.adapter.updateCart({customerId:r,cart:c}).then(()=>{g.current=_}).catch(b=>{console.warn("[CedrosPay] Cart server sync failed:",b instanceof Error?b.message:b)})},a);return()=>window.clearTimeout(w)},[t.adapter,r,f,o,c,a]);const x=k.useCallback((_,w)=>{const b=c.items.find(j=>j.productId===_&&j.variantId===w);if(b)return{holdId:b.holdId,expiresAt:b.holdExpiresAt}},[c.items]),p=k.useCallback((_,w,b)=>{l({type:"cart/updateHold",productId:_,variantId:w,holdExpiresAt:b})},[]),v=k.useMemo(()=>{const _=Em(c.items),w=Im(c.items);return{items:c.items,promoCode:c.promoCode,count:_,subtotal:w,addItem:(b,j)=>l({type:"cart/add",item:b,qty:j}),removeItem:(b,j)=>l({type:"cart/remove",productId:b,variantId:j}),setQty:(b,j,R)=>l({type:"cart/setQty",productId:b,variantId:j,qty:R}),clear:()=>l({type:"cart/clear"}),setPromoCode:b=>l({type:"cart/setPromoCode",promoCode:b}),holdsSupported:i,getItemHold:x,updateItemHold:p}},[c.items,c.promoCode,i,x,p]);return s.jsx(Vc.Provider,{value:v,children:e})}function $(e,t,n){function r(c,l){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:l,constr:i,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,l);const d=i.prototype,f=Object.keys(d);for(let u=0;u<f.length;u++){const h=f[u];h in c||(c[h]=d[h].bind(c))}}const o=n?.Parent??Object;class a extends o{}Object.defineProperty(a,"name",{value:e});function i(c){var l;const d=n?.Parent?new a:this;r(d,c),(l=d._zod).deferred??(l.deferred=[]);for(const f of d._zod.deferred)f();return d}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class Dn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Wc extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const Hc={};function yn(e){return Hc}function Zc(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function ko(e,t){return typeof t=="bigint"?t.toString():t}function Yo(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Qo(e){return e==null}function Ko(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Om(e,t){const n=(e.toString().split(".")[1]||"").length,r=t.toString();let o=(r.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(r)){const l=r.match(/\d?e-(\d?)/);l?.[1]&&(o=Number.parseInt(l[1]))}const a=n>o?n:o,i=Number.parseInt(e.toFixed(a).replace(".","")),c=Number.parseInt(t.toFixed(a).replace(".",""));return i%c/10**a}const fi=Symbol("evaluating");function be(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==fi)return r===void 0&&(r=fi,r=n()),r},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Sn(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function ln(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function mi(e){return JSON.stringify(e)}function Mm(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const qc="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Jr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Lm=Yo(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function mr(e){if(Jr(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Jr(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Gc(e){return mr(e)?{...e}:Array.isArray(e)?[...e]:e}const Dm=new Set(["string","number","symbol"]);function Fn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dn(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function ie(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function $m(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const zm={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Fm(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const a=ln(e._zod.def,{get shape(){const i={};for(const c in t){if(!(c in n.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(i[c]=n.shape[c])}return Sn(this,"shape",i),i},checks:[]});return dn(e,a)}function Um(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const a=ln(e._zod.def,{get shape(){const i={...e._zod.def.shape};for(const c in t){if(!(c in n.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&delete i[c]}return Sn(this,"shape",i),i},checks:[]});return dn(e,a)}function Bm(e,t){if(!mr(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const a=e._zod.def.shape;for(const i in t)if(Object.getOwnPropertyDescriptor(a,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=ln(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return Sn(this,"shape",a),a}});return dn(e,o)}function Vm(e,t){if(!mr(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=ln(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return Sn(this,"shape",r),r}});return dn(e,n)}function Wm(e,t){const n=ln(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return Sn(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:[]});return dn(e,n)}function Hm(e,t,n){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const i=ln(t._zod.def,{get shape(){const c=t._zod.def.shape,l={...c};if(n)for(const d in n){if(!(d in c))throw new Error(`Unrecognized key: "${d}"`);n[d]&&(l[d]=e?new e({type:"optional",innerType:c[d]}):c[d])}else for(const d in c)l[d]=e?new e({type:"optional",innerType:c[d]}):c[d];return Sn(this,"shape",l),l},checks:[]});return dn(t,i)}function Zm(e,t,n){const r=ln(t._zod.def,{get shape(){const o=t._zod.def.shape,a={...o};if(n)for(const i in n){if(!(i in a))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(a[i]=new e({type:"nonoptional",innerType:o[i]}))}else for(const i in o)a[i]=new e({type:"nonoptional",innerType:o[i]});return Sn(this,"shape",a),a}});return dn(t,r)}function Ln(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Yc(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Ir(e){return typeof e=="string"?e:e?.message}function bn(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const o=Ir(e.inst?._zod.def?.error?.(e))??Ir(t?.error?.(e))??Ir(n.customError?.(e))??Ir(n.localeError?.(e))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function Jo(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function pr(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const Qc=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ko,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Kc=$("$ZodError",Qc),Jc=$("$ZodError",Qc,{Parent:Error});function qm(e,t=n=>n.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}function Gm(e,t=n=>n.message){const n={_errors:[]},r=o=>{for(const a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>r({issues:i}));else if(a.code==="invalid_key")r({issues:a.issues});else if(a.code==="invalid_element")r({issues:a.issues});else if(a.path.length===0)n._errors.push(t(a));else{let i=n,c=0;for(;c<a.path.length;){const l=a.path[c];c===a.path.length-1?(i[l]=i[l]||{_errors:[]},i[l]._errors.push(t(a))):i[l]=i[l]||{_errors:[]},i=i[l],c++}}};return r(e),n}const Xo=e=>(t,n,r,o)=>{const a=r?Object.assign(r,{async:!1}):{async:!1},i=t._zod.run({value:n,issues:[]},a);if(i instanceof Promise)throw new Dn;if(i.issues.length){const c=new(o?.Err??e)(i.issues.map(l=>bn(l,a,yn())));throw qc(c,o?.callee),c}return i.value},ea=e=>async(t,n,r,o)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){const c=new(o?.Err??e)(i.issues.map(l=>bn(l,a,yn())));throw qc(c,o?.callee),c}return i.value},hs=e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},o);if(a instanceof Promise)throw new Dn;return a.issues.length?{success:!1,error:new(e??Kc)(a.issues.map(i=>bn(i,o,yn())))}:{success:!0,data:a.value}},Ym=hs(Jc),gs=e=>async(t,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},o);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(i=>bn(i,o,yn())))}:{success:!0,data:a.value}},Qm=gs(Jc),Km=e=>(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Xo(e)(t,n,o)},Jm=e=>(t,n,r)=>Xo(e)(t,n,r),Xm=e=>async(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return ea(e)(t,n,o)},ep=e=>async(t,n,r)=>ea(e)(t,n,r),tp=e=>(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return hs(e)(t,n,o)},np=e=>(t,n,r)=>hs(e)(t,n,r),rp=e=>async(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return gs(e)(t,n,o)},sp=e=>async(t,n,r)=>gs(e)(t,n,r),op=/^[cC][^\s-]{8,}$/,ap=/^[0-9a-z]+$/,ip=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,cp=/^[0-9a-vA-V]{20}$/,lp=/^[A-Za-z0-9]{27}$/,dp=/^[a-zA-Z0-9_-]{21}$/,up=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,fp=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,pi=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,mp=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,pp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function hp(){return new RegExp(pp,"u")}const gp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,xp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,vp=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,yp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,bp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Xc=/^[A-Za-z0-9_-]*$/,wp=/^\+[1-9]\d{6,14}$/,el="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",_p=new RegExp(`^${el}$`);function tl(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function kp(e){return new RegExp(`^${tl(e)}$`)}function jp(e){const t=tl({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${el}T(?:${r})$`)}const Sp=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Cp=/^-?\d+$/,Np=/^-?\d+(?:\.\d+)?$/,Ap=/^[^A-Z]*$/,Ep=/^[^a-z]*$/,ut=$("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),nl={number:"number",bigint:"bigint",object:"date"},rl=$("$ZodCheckLessThan",(e,t)=>{ut.init(e,t);const n=nl[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,a=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<a&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),sl=$("$ZodCheckGreaterThan",(e,t)=>{ut.init(e,t);const n=nl[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,a=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>a&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ip=$("$ZodCheckMultipleOf",(e,t)=>{ut.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):Om(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Tp=$("$ZodCheckNumberFormat",(e,t)=>{ut.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[o,a]=zm[t.format];e._zod.onattach.push(i=>{const c=i._zod.bag;c.format=t.format,c.minimum=o,c.maximum=a,n&&(c.pattern=Cp)}),e._zod.check=i=>{const c=i.value;if(n){if(!Number.isInteger(c)){i.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?i.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):i.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}c<o&&i.issues.push({origin:"number",input:c,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),c>a&&i.issues.push({origin:"number",input:c,code:"too_big",maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Pp=$("$ZodCheckMaxLength",(e,t)=>{var n;ut.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!Qo(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const o=r.value;if(o.length<=t.maximum)return;const i=Jo(o);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Rp=$("$ZodCheckMinLength",(e,t)=>{var n;ut.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!Qo(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const o=r.value;if(o.length>=t.minimum)return;const i=Jo(o);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Op=$("$ZodCheckLengthEquals",(e,t)=>{var n;ut.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!Qo(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=r=>{const o=r.value,a=o.length;if(a===t.length)return;const i=Jo(o),c=a>t.length;r.issues.push({origin:i,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),xs=$("$ZodCheckStringFormat",(e,t)=>{var n,r;ut.init(e,t),e._zod.onattach.push(o=>{const a=o._zod.bag;a.format=t.format,t.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Mp=$("$ZodCheckRegex",(e,t)=>{xs.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Lp=$("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ap),xs.init(e,t)}),Dp=$("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Ep),xs.init(e,t)}),$p=$("$ZodCheckIncludes",(e,t)=>{ut.init(e,t);const n=Fn(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(o=>{const a=o._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(r)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),zp=$("$ZodCheckStartsWith",(e,t)=>{ut.init(e,t);const n=new RegExp(`^${Fn(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),Fp=$("$ZodCheckEndsWith",(e,t)=>{ut.init(e,t);const n=new RegExp(`.*${Fn(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),Up=$("$ZodCheckOverwrite",(e,t)=>{ut.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class Bp{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
|
|
2
2
|
`).filter(i=>i),o=Math.min(...r.map(i=>i.length-i.trimStart().length)),a=r.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(const i of a)this.content.push(i)}compile(){const t=Function,n=this?.args,o=[...(this?.content??[""]).map(a=>` ${a}`)];return new t(...n,o.join(`
|
|
3
3
|
`))}}const Vp={major:4,minor:3,patch:6},Oe=$("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Vp;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const o of r)for(const a of o._zod.onattach)a(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(i,c,l)=>{let d=Ln(i),f;for(const u of c){if(u._zod.def.when){if(!u._zod.def.when(i))continue}else if(d)continue;const h=i.issues.length,g=u._zod.check(i);if(g instanceof Promise&&l?.async===!1)throw new Dn;if(f||g instanceof Promise)f=(f??Promise.resolve()).then(async()=>{await g,i.issues.length!==h&&(d||(d=Ln(i,h)))});else{if(i.issues.length===h)continue;d||(d=Ln(i,h))}}return f?f.then(()=>i):i},a=(i,c,l)=>{if(Ln(i))return i.aborted=!0,i;const d=o(c,r,l);if(d instanceof Promise){if(l.async===!1)throw new Dn;return d.then(f=>e._zod.parse(f,l))}return e._zod.parse(d,l)};e._zod.run=(i,c)=>{if(c.skipChecks)return e._zod.parse(i,c);if(c.direction==="backward"){const d=e._zod.parse({value:i.value,issues:[]},{...c,skipChecks:!0});return d instanceof Promise?d.then(f=>a(f,i,c)):a(d,i,c)}const l=e._zod.parse(i,c);if(l instanceof Promise){if(c.async===!1)throw new Dn;return l.then(d=>o(d,r,c))}return o(l,r,c)}}be(e,"~standard",()=>({validate:o=>{try{const a=Ym(e,o);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return Qm(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),ta=$("$ZodString",(e,t)=>{Oe.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Sp(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Ne=$("$ZodStringFormat",(e,t)=>{xs.init(e,t),ta.init(e,t)}),Wp=$("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=fp),Ne.init(e,t)}),Hp=$("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=pi(r))}else t.pattern??(t.pattern=pi());Ne.init(e,t)}),Zp=$("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=mp),Ne.init(e,t)}),qp=$("$ZodURL",(e,t)=>{Ne.init(e,t),e._zod.check=n=>{try{const r=n.value.trim(),o=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=o.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Gp=$("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=hp()),Ne.init(e,t)}),Yp=$("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=dp),Ne.init(e,t)}),Qp=$("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=op),Ne.init(e,t)}),Kp=$("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=ap),Ne.init(e,t)}),Jp=$("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ip),Ne.init(e,t)}),Xp=$("$ZodXID",(e,t)=>{t.pattern??(t.pattern=cp),Ne.init(e,t)}),eh=$("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=lp),Ne.init(e,t)}),th=$("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=jp(t)),Ne.init(e,t)}),nh=$("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=_p),Ne.init(e,t)}),rh=$("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=kp(t)),Ne.init(e,t)}),sh=$("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=up),Ne.init(e,t)}),oh=$("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=gp),Ne.init(e,t),e._zod.bag.format="ipv4"}),ah=$("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=xp),Ne.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),ih=$("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=vp),Ne.init(e,t)}),ch=$("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=yp),Ne.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[o,a]=r;if(!a)throw new Error;const i=Number(a);if(`${i}`!==a)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function ol(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const lh=$("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=bp),Ne.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{ol(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function dh(e){if(!Xc.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return ol(n)}const uh=$("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Xc),Ne.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{dh(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),fh=$("$ZodE164",(e,t)=>{t.pattern??(t.pattern=wp),Ne.init(e,t)});function mh(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const ph=$("$ZodJWT",(e,t)=>{Ne.init(e,t),e._zod.check=n=>{mh(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),al=$("$ZodNumber",(e,t)=>{Oe.init(e,t),e._zod.pattern=e._zod.bag.pattern??Np,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const a=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...a?{received:a}:{}}),n}}),hh=$("$ZodNumberFormat",(e,t)=>{Tp.init(e,t),al.init(e,t)}),gh=$("$ZodUnknown",(e,t)=>{Oe.init(e,t),e._zod.parse=n=>n}),xh=$("$ZodNever",(e,t)=>{Oe.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function hi(e,t,n){e.issues.length&&t.issues.push(...Yc(n,e.issues)),t.value[n]=e.value}const vh=$("$ZodArray",(e,t)=>{Oe.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const a=[];for(let i=0;i<o.length;i++){const c=o[i],l=t.element._zod.run({value:c,issues:[]},r);l instanceof Promise?a.push(l.then(d=>hi(d,n,i))):hi(l,n,i)}return a.length?Promise.all(a).then(()=>n):n}});function Xr(e,t,n,r,o){if(e.issues.length){if(o&&!(n in r))return;t.issues.push(...Yc(n,e.issues))}e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function il(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=$m(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function cl(e,t,n,r,o,a){const i=[],c=o.keySet,l=o.catchall._zod,d=l.def.type,f=l.optout==="optional";for(const u in t){if(c.has(u))continue;if(d==="never"){i.push(u);continue}const h=l.run({value:t[u],issues:[]},r);h instanceof Promise?e.push(h.then(g=>Xr(g,n,u,t,f))):Xr(h,n,u,t,f)}return i.length&&n.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}const yh=$("$ZodObject",(e,t)=>{if(Oe.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const c=t.shape;Object.defineProperty(t,"shape",{get:()=>{const l={...c};return Object.defineProperty(t,"shape",{value:l}),l}})}const r=Yo(()=>il(t));be(e._zod,"propValues",()=>{const c=t.shape,l={};for(const d in c){const f=c[d]._zod;if(f.values){l[d]??(l[d]=new Set);for(const u of f.values)l[d].add(u)}}return l});const o=Jr,a=t.catchall;let i;e._zod.parse=(c,l)=>{i??(i=r.value);const d=c.value;if(!o(d))return c.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),c;c.value={};const f=[],u=i.shape;for(const h of i.keys){const g=u[h],y=g._zod.optout==="optional",x=g._zod.run({value:d[h],issues:[]},l);x instanceof Promise?f.push(x.then(p=>Xr(p,c,h,d,y))):Xr(x,c,h,d,y)}return a?cl(f,d,c,l,r.value,e):f.length?Promise.all(f).then(()=>c):c}}),bh=$("$ZodObjectJIT",(e,t)=>{yh.init(e,t);const n=e._zod.parse,r=Yo(()=>il(t)),o=h=>{const g=new Bp(["shape","payload","ctx"]),y=r.value,x=w=>{const b=mi(w);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`};g.write("const input = payload.value;");const p=Object.create(null);let v=0;for(const w of y.keys)p[w]=`key_${v++}`;g.write("const newResult = {};");for(const w of y.keys){const b=p[w],j=mi(w),I=h[w]?._zod?.optout==="optional";g.write(`const ${b} = ${x(w)};`),I?g.write(`
|
|
4
4
|
if (${b}.issues.length) {
|