@cedros/pay-react 1.1.29 → 1.1.31

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.
Files changed (120) hide show
  1. package/README.md +53 -22
  2. package/dist/{AISettingsSection-B7qrycfY.js → AISettingsSection-B12x5sV5.js} +2 -2
  3. package/dist/{AISettingsSection-DtAgMsDw.mjs → AISettingsSection-DXWDF4Cf.mjs} +4 -4
  4. package/dist/AutosaveIndicator-CJdkhZis.js +1 -0
  5. package/dist/{AutosaveIndicator-BEvABoKU.mjs → AutosaveIndicator-D966vOrP.mjs} +1 -1
  6. package/dist/CedrosContext-3Dz7_9Ct.js +3 -0
  7. package/dist/{CedrosContext-5Gjveoba.mjs → CedrosContext-DQc_k5PG.mjs} +430 -314
  8. package/dist/ChatLogsSection-CH37u0nX.js +1 -0
  9. package/dist/{ChatLogsSection-Ber5o8hF.mjs → ChatLogsSection-DR7mpuQS.mjs} +2 -2
  10. package/dist/{ComplianceSection-ZCr0wsvw.mjs → ComplianceSection-C61_Hf-X.mjs} +3 -3
  11. package/dist/ComplianceSection-DS4e2IBp.js +1 -0
  12. package/dist/CryptoButton-BQceZhbn.js +1 -0
  13. package/dist/{CryptoButton-Cl2kZbOP.mjs → CryptoButton-BuO_RZLj.mjs} +4 -5
  14. package/dist/CustomersSection-Bzs9Qon3.js +1 -0
  15. package/dist/{CustomersSection-D9UknSKC.mjs → CustomersSection-CWWvusxs.mjs} +2 -2
  16. package/dist/DisputesSection-ClcYIHga.js +1 -0
  17. package/dist/{DisputesSection-C_eySK-W.mjs → DisputesSection-D8rcS5Vs.mjs} +2 -2
  18. package/dist/{Dropdown-B90Zabxr.mjs → Dropdown-0y3S40Xf.mjs} +1 -1
  19. package/dist/Dropdown-BuKiVR_L.js +1 -0
  20. package/dist/{ErrorBanner-CZXsHi3H.mjs → ErrorBanner-DAjYj6Dx.mjs} +1 -1
  21. package/dist/ErrorBanner-DxrRVqwe.js +1 -0
  22. package/dist/FAQSection-0UnN2BZs.js +1 -0
  23. package/dist/{FAQSection-Bv_Hdt8B.mjs → FAQSection-Dck0NM-A.mjs} +3 -3
  24. package/dist/{ImagesSection-DpdXQ6qu.mjs → ImagesSection-Bn9GrRRa.mjs} +2 -2
  25. package/dist/ImagesSection-CSwBHvNl.js +1 -0
  26. package/dist/{InventorySection-DZMu9DMw.mjs → InventorySection-Dytfmtn8.mjs} +2 -2
  27. package/dist/InventorySection-ymxaMcIg.js +1 -0
  28. package/dist/{MessagingSection-D_cOBfFt.mjs → MessagingSection-CHFbSxJL.mjs} +3 -3
  29. package/dist/MessagingSection-Dtfv0DvU.js +1 -0
  30. package/dist/OrdersSection-BuzTs9XG.js +1 -0
  31. package/dist/{OrdersSection-wfPavit9.mjs → OrdersSection-vYNuVF5X.mjs} +2 -2
  32. package/dist/{PaymentSettingsSection-BdBDgaRg.js → PaymentSettingsSection-BOaW8lLv.js} +1 -1
  33. package/dist/{PaymentSettingsSection-DunzBo9n.mjs → PaymentSettingsSection-BqdGrXen.mjs} +3 -3
  34. package/dist/{ReturnsSection-B4FL7bUv.mjs → ReturnsSection-CRzhXKtI.mjs} +2 -2
  35. package/dist/ReturnsSection-i5W_3so1.js +1 -0
  36. package/dist/{SettingsSection-DoeNDbqd.mjs → SettingsSection-6o3d8DrH.mjs} +1 -1
  37. package/dist/{SettingsSection-Cz2Yjdhr.js → SettingsSection-CIhO51Zj.js} +1 -1
  38. package/dist/ShippingSection-BUzPW1AG.js +1 -0
  39. package/dist/{ShippingSection-BlVsYC6B.mjs → ShippingSection-CbNzGyCP.mjs} +2 -2
  40. package/dist/SingleCategorySettings-BxVUUy8R.js +3 -0
  41. package/dist/{SingleCategorySettings-B406nnF-.mjs → SingleCategorySettings-Qj_ptB_x.mjs} +4 -4
  42. package/dist/{StatsBar-D4v-I_Dj.mjs → StatsBar-CwCBHBn-.mjs} +1 -1
  43. package/dist/StatsBar-DDUWoizP.js +1 -0
  44. package/dist/StorefrontSection-CZZj5he9.js +1 -0
  45. package/dist/{StorefrontSection-BK_rhrAi.mjs → StorefrontSection-DIYDmj59.mjs} +4 -4
  46. package/dist/SubscriptionsSection-Bof5MElz.js +1 -0
  47. package/dist/{SubscriptionsSection-D8V9RBv-.mjs → SubscriptionsSection-lMVHdV5X.mjs} +3 -3
  48. package/dist/TaxSection-Be-9v60Z.js +1 -0
  49. package/dist/{TaxSection-Cj6TXL6x.mjs → TaxSection-dD7PzQvG.mjs} +2 -2
  50. package/dist/Token22Section-Di5fHsrU.js +1 -0
  51. package/dist/{Token22Section-DtYAcT54.mjs → Token22Section-Dos0CYEk.mjs} +2 -2
  52. package/dist/{WalletManager-D-eoqUDy.mjs → WalletManager-CGR69MiR.mjs} +1 -1
  53. package/dist/{WalletManager-DXChB9LA.js → WalletManager-ZJbGQHrn.js} +1 -1
  54. package/dist/{WebhooksSection-DBAIxtBy.mjs → WebhooksSection-5gqXzIhq.mjs} +2 -2
  55. package/dist/WebhooksSection-CiLDyl7c.js +1 -0
  56. package/dist/admin.js +1 -1
  57. package/dist/admin.mjs +4 -5
  58. package/dist/crypto-only.js +1 -1
  59. package/dist/crypto-only.mjs +102 -104
  60. package/dist/{index-9QF_UfSN.mjs → index-CU6M10Rs.mjs} +13 -14
  61. package/dist/{index-Cq9ya93W.js → index-DVxx_62C.js} +10 -10
  62. package/dist/index.js +1 -1
  63. package/dist/index.mjs +21 -23
  64. package/dist/pay-react.css +1 -1
  65. package/dist/plugin-BIkt3boU.mjs +339 -0
  66. package/dist/plugin-Dw8_Q8rE.js +1 -0
  67. package/dist/sections-D1d83mfH.js +1 -0
  68. package/dist/{sections-more-CMFgfU4d.mjs → sections-DcUfZQNE.mjs} +263 -270
  69. package/dist/src/admin/plugin.d.ts.map +1 -1
  70. package/dist/src/admin/sectionIds.d.ts.map +1 -1
  71. package/dist/src/admin.d.ts +0 -7
  72. package/dist/src/admin.d.ts.map +1 -1
  73. package/dist/src/components/admin/index.d.ts +0 -1
  74. package/dist/src/components/admin/index.d.ts.map +1 -1
  75. package/dist/src/index.d.ts +0 -1
  76. package/dist/src/index.d.ts.map +1 -1
  77. package/dist/stripe-only.js +1 -1
  78. package/dist/stripe-only.mjs +18 -19
  79. package/dist/styles-BwaDljnz.js +1 -0
  80. package/dist/{styles-DGagylUj.mjs → styles-fihm6qVA.mjs} +51 -52
  81. package/dist/testing/index.js +1 -1
  82. package/dist/testing/index.mjs +1 -1
  83. package/package.json +6 -2
  84. package/dist/AutosaveIndicator-DiyeAg93.js +0 -1
  85. package/dist/CedrosContext-CCakH2SZ.js +0 -3
  86. package/dist/CedrosPayAdminDashboard-CAwEvn66.js +0 -1
  87. package/dist/CedrosPayAdminDashboard-CBuvNAtB.mjs +0 -250
  88. package/dist/ChatLogsSection-DLxMMi9I.js +0 -1
  89. package/dist/ComplianceSection-Buu0zTiL.js +0 -1
  90. package/dist/CryptoButton-DxFCYDlJ.js +0 -1
  91. package/dist/CustomersSection-BywmMLur.js +0 -1
  92. package/dist/DisputesSection-DwkHGv2a.js +0 -1
  93. package/dist/Dropdown-CtY91emj.js +0 -1
  94. package/dist/ErrorBanner-Cx2dUhps.js +0 -1
  95. package/dist/FAQSection-DlPLnIJD.js +0 -1
  96. package/dist/ImagesSection-B4Jzet79.js +0 -1
  97. package/dist/InventorySection-BgRdpn1l.js +0 -1
  98. package/dist/MessagingSection-CxV-pf-f.js +0 -1
  99. package/dist/OrdersSection-BbAX79Ff.js +0 -1
  100. package/dist/ReturnsSection-7k4LZ8yp.js +0 -1
  101. package/dist/ShippingSection-C-HI8rOb.js +0 -1
  102. package/dist/SingleCategorySettings-BqC2UXt3.js +0 -3
  103. package/dist/StatsBar-m6GSRNxs.js +0 -1
  104. package/dist/StorefrontSection-Axvh_KeS.js +0 -1
  105. package/dist/SubscriptionsSection-EeULMWIB.js +0 -1
  106. package/dist/TaxSection-CzHPhaHl.js +0 -1
  107. package/dist/ThemeContext-CFXyYx7A.js +0 -1
  108. package/dist/ThemeContext-l0bqcOGW.mjs +0 -126
  109. package/dist/Token22Section-DqRKVG_G.js +0 -1
  110. package/dist/WebhooksSection-D--iPZuM.js +0 -1
  111. package/dist/sectionIds-B_tFiNvF.js +0 -1
  112. package/dist/sectionIds-DBavltrL.mjs +0 -359
  113. package/dist/sections-BHph7CYj.mjs +0 -9
  114. package/dist/sections-C2zEJr5G.js +0 -1
  115. package/dist/sections-more-C1VNVwkp.js +0 -1
  116. package/dist/src/components/admin/CedrosPayAdminDashboard.d.ts +0 -40
  117. package/dist/src/components/admin/CedrosPayAdminDashboard.d.ts.map +0 -1
  118. package/dist/src/components/admin/LazyCedrosPayAdminDashboard.d.ts +0 -4
  119. package/dist/src/components/admin/LazyCedrosPayAdminDashboard.d.ts.map +0 -1
  120. package/dist/styles--fxb3lCl.js +0 -1
@@ -1 +0,0 @@
1
- "use strict";const e=require("react/jsx-runtime"),r=require("react"),$=require("./sectionIds-B_tFiNvF.js"),ne=require("./ErrorBanner-Cx2dUhps.js"),ce=require("./StatsBar-m6GSRNxs.js"),M=require("./Dropdown-CtY91emj.js"),de=require("./dateHelpers-BKW_lGND.js"),te=require("./fetchWithTimeout-CG0EKbhf.js");function _e({serverUrl:p,productId:o,apiKey:b,authManager:u}){const[g,A]=r.useState(null),[N,T]=r.useState(!1),[f,V]=r.useState(!1),[k,v]=r.useState(null),S=r.useCallback(async()=>{if(o){T(!0),v(null);try{let c;if(u?.isAuthenticated())c=await u.fetchWithAuth(`/admin/products/${o}/variations`);else{const a={"Content-Type":"application/json"};b&&(a["X-API-Key"]=b);const l=await fetch(`${p}/admin/products/${o}/variations`,{headers:a});if(!l.ok)throw new Error(`Failed to fetch variations: ${l.status}`);c=await l.json()}c.variationConfig||(c.variationConfig={variationTypes:[]}),c.variants||(c.variants=[]),A(c)}catch(c){const a=c instanceof Error?c.message:"Failed to fetch variations";v(a),A({productId:o,variationConfig:{variationTypes:[]},variants:[]})}finally{T(!1)}}},[p,o,b,u]),R=r.useCallback(async c=>{if(!o)return null;V(!0),v(null);try{let a;if(u?.isAuthenticated())a=await u.fetchWithAuth(`/admin/products/${o}/variations`,{method:"PUT",body:JSON.stringify(c)});else{const l={"Content-Type":"application/json"};b&&(l["X-API-Key"]=b);const C=await fetch(`${p}/admin/products/${o}/variations`,{method:"PUT",headers:l,body:JSON.stringify(c)});if(!C.ok)throw new Error(`Failed to save variations: ${C.status}`);a=await C.json()}return A({productId:o,variationConfig:a.variationConfig,variants:a.variants}),{variantsCreated:a.variantsCreated}}catch(a){const l=a instanceof Error?a.message:"Failed to save variations";return v(l),null}finally{V(!1)}},[p,o,b,u]),_=r.useCallback(async c=>{if(!o||c.length===0)return!1;V(!0),v(null);try{if(u?.isAuthenticated())await u.fetchWithAuth(`/admin/products/${o}/variants/inventory`,{method:"PUT",body:JSON.stringify({updates:c})});else{const a={"Content-Type":"application/json"};b&&(a["X-API-Key"]=b);const l=await fetch(`${p}/admin/products/${o}/variants/inventory`,{method:"PUT",headers:a,body:JSON.stringify({updates:c})});if(!l.ok)throw new Error(`Failed to update inventory: ${l.status}`)}if(g){const a=new Map(c.map(l=>[l.variantId,l]));A({...g,variants:g.variants.map(l=>{const C=a.get(l.id);return C?{...l,inventoryQuantity:C.inventoryQuantity,inventoryStatus:C.inventoryStatus??l.inventoryStatus}:l})})}return!0}catch(a){const l=a instanceof Error?a.message:"Failed to update inventory";return v(l),!1}finally{V(!1)}},[p,o,b,u,g]);return{data:g,isLoading:N,error:k,fetch:S,save:R,bulkUpdateInventory:_,isSaving:f}}function pe(){return`var_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function ye({value:p,onChange:o,maxTypes:b=5,maxValuesPerType:u=20,disabled:g=!1}){const[A,N]=r.useState(null),[T,f]=r.useState(""),[V,k]=r.useState({}),v=p.variationTypes,S=r.useCallback(()=>{if(!T.trim()||v.length>=b)return;const y={id:pe(),name:T.trim(),displayOrder:v.length,values:[]};o({variationTypes:[...v,y]}),f(""),N(y.id)},[T,v,b,o]),R=r.useCallback(y=>{o({variationTypes:v.filter(D=>D.id!==y).map((D,j)=>({...D,displayOrder:j}))}),A===y&&N(null)},[v,o,A]),_=r.useCallback((y,D)=>{o({variationTypes:v.map(j=>j.id===y?{...j,name:D}:j)})},[v,o]),c=r.useCallback((y,D)=>{const j=v.findIndex(I=>I.id===y);if(j===-1||D==="up"&&j===0||D==="down"&&j===v.length-1)return;const s=[...v],h=D==="up"?j-1:j+1;[s[j],s[h]]=[s[h],s[j]],o({variationTypes:s.map((I,d)=>({...I,displayOrder:d}))})},[v,o]),a=r.useCallback(y=>{const D=(V[y]||"").trim();if(!D)return;const j=v.find(h=>h.id===y);if(!j||j.values.length>=u)return;const s={id:pe(),label:D};o({variationTypes:v.map(h=>h.id===y?{...h,values:[...h.values,s]}:h)}),k(h=>({...h,[y]:""}))},[v,V,u,o]),l=r.useCallback((y,D)=>{o({variationTypes:v.map(j=>j.id===y?{...j,values:j.values.filter(s=>s.id!==D)}:j)})},[v,o]),C=r.useCallback((y,D,j)=>{o({variationTypes:v.map(s=>s.id===y?{...s,values:s.values.map(h=>h.id===D?{...h,label:j}:h)}:s)})},[v,o]);return e.jsxs("div",{className:"cedros-admin__variation-editor",children:[e.jsxs("div",{className:"cedros-admin__variation-editor-header",children:[e.jsx("h4",{className:"cedros-admin__field-label",style:{marginBottom:0},children:"Variation Types"}),e.jsxs("span",{style:{fontSize:12,opacity:.7},children:[v.length,"/",b," types"]})]}),v.length===0?e.jsx("div",{className:"cedros-admin__variation-empty",children:'No variation types defined. Add types like "Size" or "Color" to create product variants.'}):e.jsx("div",{className:"cedros-admin__variation-type-list",children:v.map((y,D)=>e.jsxs("div",{className:"cedros-admin__variation-type-item",children:[e.jsxs("div",{className:"cedros-admin__variation-type-header",children:[e.jsxs("div",{className:"cedros-admin__variation-type-controls",children:[e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>c(y.id,"up"),disabled:g||D===0,title:"Move up",children:$.Icons.arrowUp}),e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>c(y.id,"down"),disabled:g||D===v.length-1,title:"Move down",children:$.Icons.arrowDown})]}),e.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__variation-type-name",value:y.name,onChange:j=>_(y.id,j.target.value),disabled:g,placeholder:"Type name"}),e.jsxs("span",{className:"cedros-admin__variation-value-count",children:[y.values.length," values"]}),e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>N(A===y.id?null:y.id),children:A===y.id?"Collapse":"Edit values"}),e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>R(y.id),disabled:g,title:"Remove type",children:$.Icons.delete})]}),A===y.id&&e.jsxs("div",{className:"cedros-admin__variation-values",children:[e.jsxs("div",{className:"cedros-admin__variation-values-header",children:[e.jsxs("span",{style:{fontSize:12,fontWeight:600},children:['Values for "',y.name,'"']}),e.jsxs("span",{style:{fontSize:11,opacity:.7},children:[y.values.length,"/",u]})]}),y.values.length===0?e.jsx("div",{className:"cedros-admin__variation-empty",style:{padding:"8px 0"},children:'No values yet. Add values like "Small", "Medium", "Large".'}):e.jsx("div",{className:"cedros-admin__variation-value-list",children:y.values.map(j=>e.jsxs("div",{className:"cedros-admin__variation-value-item",children:[e.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:j.label,onChange:s=>C(y.id,j.id,s.target.value),disabled:g}),e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon cedros-admin__button--danger",onClick:()=>l(y.id,j.id),disabled:g,title:"Remove value",children:$.Icons.close})]},j.id))}),y.values.length<u&&e.jsxs("div",{className:"cedros-admin__variation-add-value",children:[e.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:V[y.id]||"",onChange:j=>k(s=>({...s,[y.id]:j.target.value})),placeholder:"Add value...",disabled:g,onKeyDown:j=>{j.key==="Enter"&&(j.preventDefault(),a(y.id))}}),e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary cedros-admin__button--sm",onClick:()=>a(y.id),disabled:g||!V[y.id]?.trim(),children:"Add"})]})]})]},y.id))}),v.length<b&&e.jsxs("div",{className:"cedros-admin__variation-add-type",children:[e.jsx("input",{type:"text",className:"cedros-admin__input",value:T,onChange:y=>f(y.target.value),placeholder:"New variation type (e.g., Size, Color)",disabled:g,onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),S())}}),e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary",onClick:S,disabled:g||!T.trim(),children:"Add Type"})]})]})}function ge(){return`variant_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function xe(p){if(p.length===0)return[];const o=[...p].sort((u,g)=>u.displayOrder-g.displayOrder),b=(u,g)=>{if(u>=o.length){const T=g.valueIds.sort().join("|"),f=Object.values(g.options).join(" / ");return[{key:T,title:f,optionValueIds:[...g.valueIds],options:{...g.options}}]}const A=o[u],N=[];for(const T of A.values)N.push(...b(u+1,{valueIds:[...g.valueIds,T.id],options:{...g.options,[A.name]:T.label}}));return N};return b(0,{valueIds:[],options:{}})}function be(p){return p.optionValueIds?.length?[...p.optionValueIds].sort().join("|"):Object.entries(p.options).sort(([o],[b])=>o.localeCompare(b)).map(([o,b])=>`${o}:${b}`).join("|")}function ve({variationConfig:p,variants:o,onChange:b,defaultPrice:u=0,currencySymbol:g="$",maxVariants:A=100,disabled:N=!1}){const T=r.useMemo(()=>xe(p.variationTypes),[p.variationTypes]),f=r.useMemo(()=>{const c=new Map;for(const a of o)c.set(be(a),a);return c},[o]),{existingRows:V,possibleRows:k}=r.useMemo(()=>{const c=[],a=[];for(const l of T){const C=f.get(l.key);C?c.push({combo:l,variant:C}):a.push(l)}return{existingRows:c,possibleRows:a}},[T,f]),v=r.useCallback((c,a)=>{b(o.map(l=>l.id===c?{...l,...a}:l))},[o,b]),S=r.useCallback(c=>{b(o.filter(a=>a.id!==c))},[o,b]),R=r.useCallback(c=>{if(o.length>=A)return;const a={id:ge(),title:c.title,options:c.options,optionValueIds:c.optionValueIds,price:u,inventoryQuantity:0,inventoryStatus:"in_stock",autoGenerated:!1};b([...o,a])},[o,b,A,u]),_=r.useCallback(()=>{const c=A-o.length,l=k.slice(0,c).map(C=>({id:ge(),title:C.title,options:C.options,optionValueIds:C.optionValueIds,price:u,inventoryQuantity:0,inventoryStatus:"in_stock",autoGenerated:!0}));b([...o,...l])},[o,b,k,A,u]);return p.variationTypes.length===0?e.jsx("div",{className:"cedros-admin__variant-grid-empty",children:"Add variation types above to create product variants."}):T.length===0?e.jsx("div",{className:"cedros-admin__variant-grid-empty",children:"Add values to your variation types to create product variants."}):e.jsxs("div",{className:"cedros-admin__variant-grid",children:[e.jsxs("div",{className:"cedros-admin__variant-grid-header",children:[e.jsx("h4",{className:"cedros-admin__field-label",style:{marginBottom:0},children:"Variants"}),e.jsxs("span",{style:{fontSize:12,opacity:.7},children:[o.length,"/",A," variants (",T.length," ","possible)"]})]}),k.length>0&&o.length<A&&e.jsxs("div",{className:"cedros-admin__variant-grid-actions",children:[e.jsxs("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary",onClick:_,disabled:N,children:["Generate All (",Math.min(k.length,A-o.length),")"]}),e.jsx("span",{style:{fontSize:11,opacity:.7},children:"Creates variants with default price and 0 inventory"})]}),e.jsx("div",{className:"cedros-admin__table-container",children:e.jsxs("table",{className:"cedros-admin__table cedros-admin__variant-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Variant"}),e.jsx("th",{style:{width:100},children:"Price"}),e.jsx("th",{style:{width:80},children:"Qty"}),e.jsx("th",{style:{width:100},children:"SKU"}),e.jsx("th",{style:{width:100},children:"Status"}),e.jsx("th",{style:{width:80},children:"Actions"})]})}),e.jsxs("tbody",{children:[V.map(({combo:c,variant:a})=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[e.jsx("span",{style:{fontWeight:600},children:c.title}),e.jsx("span",{style:{fontSize:11,opacity:.6},children:Object.entries(c.options).map(([l,C])=>`${l}: ${C}`).join(", ")})]})}),e.jsx("td",{children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[e.jsx("span",{children:g}),e.jsx("input",{type:"number",className:"cedros-admin__input cedros-admin__input--sm",value:a.price??"",onChange:l=>v(a.id,{price:l.target.value===""?void 0:parseFloat(l.target.value)||0}),disabled:N,min:"0",step:"0.01",style:{width:70}})]})}),e.jsx("td",{children:e.jsx("input",{type:"number",className:"cedros-admin__input cedros-admin__input--sm",value:a.inventoryQuantity??"",onChange:l=>v(a.id,{inventoryQuantity:l.target.value===""?void 0:parseInt(l.target.value)||0}),disabled:N,min:"0",style:{width:60}})}),e.jsx("td",{children:e.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:a.sku??"",onChange:l=>v(a.id,{sku:l.target.value||void 0}),disabled:N,placeholder:"SKU",style:{width:80}})}),e.jsx("td",{children:e.jsx(M.FilterDropdown,{value:a.inventoryStatus??"in_stock",onChange:l=>v(a.id,{inventoryStatus:l}),options:[{value:"in_stock",label:"In stock"},{value:"low",label:"Low"},{value:"out_of_stock",label:"Out of stock"},{value:"backorder",label:"Backorder"}],disabled:N})}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon cedros-admin__button--danger",onClick:()=>S(a.id),disabled:N,title:"Remove variant",children:$.Icons.trash})})]},a.id)),k.length>0&&o.length<A&&e.jsxs(e.Fragment,{children:[e.jsx("tr",{className:"cedros-admin__variant-separator",children:e.jsx("td",{colSpan:6,children:e.jsxs("span",{style:{fontSize:11,opacity:.6},children:["Uncreated combinations (",k.length,")"]})})}),k.slice(0,10).map(c=>e.jsxs("tr",{className:"cedros-admin__variant-possible",children:[e.jsx("td",{children:e.jsx("span",{style:{opacity:.6},children:c.title})}),e.jsx("td",{colSpan:4,style:{opacity:.5},children:"Not created"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>R(c),disabled:N,title:"Create variant",children:$.Icons.plus})})]},c.key)),k.length>10&&e.jsx("tr",{className:"cedros-admin__variant-more",children:e.jsxs("td",{colSpan:6,style:{textAlign:"center",opacity:.6},children:["+",k.length-10," more combinations"]})})]})]})]})})]})}function je({serverUrl:p,productId:o,productTitle:b,defaultPrice:u=0,currencySymbol:g="$",apiKey:A,authManager:N,onClose:T}){const{data:f,isLoading:V,error:k,fetch:v,save:S,isSaving:R}=_e({serverUrl:p,productId:o,apiKey:A,authManager:N}),[_,c]=r.useState({variationTypes:[]}),[a,l]=r.useState([]),[C,y]=r.useState(!1),[D,j]=r.useState(!1);r.useEffect(()=>{v()},[v]),r.useEffect(()=>{f&&(c(f.variationConfig),l(f.variants),y(!1))},[f]);const s=r.useCallback(d=>{c(d),y(!0),j(!1)},[]),h=r.useCallback(d=>{l(d),y(!0),j(!1)},[]),I=r.useCallback(async()=>{const d=new Set((f?.variants??[]).map(F=>F.id)),m=a.filter(F=>!d.has(F.id)),L=a.filter(F=>d.has(F.id)),E=(f?.variants??[]).filter(F=>!a.some(H=>H.id===F.id)).map(F=>F.id);await S({variationConfig:_,createVariants:m.map(F=>({optionValueIds:F.optionValueIds??[],inventoryQuantity:F.inventoryQuantity,sku:F.sku,price:F.price})),updateVariants:L.map(F=>({id:F.id,inventoryQuantity:F.inventoryQuantity,sku:F.sku,price:F.price,inventoryStatus:F.inventoryStatus})),deleteVariantIds:E.length>0?E:void 0})&&(y(!1),j(!0),setTimeout(()=>j(!1),3e3))},[_,a,f?.variants,S]);return V?e.jsxs("div",{className:"cedros-admin__variations-editor",children:[e.jsxs("div",{className:"cedros-admin__variations-editor-header",children:[e.jsx("h3",{className:"cedros-admin__section-title",children:b?`Variations: ${b}`:"Product Variations"}),T&&e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:T,children:$.Icons.close})]}),e.jsxs("div",{className:"cedros-admin__loading",children:[$.Icons.loading," Loading variations..."]})]}):e.jsxs("div",{className:"cedros-admin__variations-editor",children:[e.jsxs("div",{className:"cedros-admin__variations-editor-header",children:[e.jsx("h3",{className:"cedros-admin__section-title",children:b?`Variations: ${b}`:"Product Variations"}),e.jsxs("div",{className:"cedros-admin__variations-editor-actions",children:[D&&e.jsxs("span",{className:"cedros-admin__success-text",children:[$.Icons.check," Saved"]}),C&&e.jsx("span",{className:"cedros-admin__unsaved-text",children:"Unsaved changes"}),e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--primary",onClick:I,disabled:R||!C,children:R?"Saving...":"Save Changes"}),T&&e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:T,children:$.Icons.close})]})]}),k&&e.jsx("div",{className:"cedros-admin__error-banner",children:k}),e.jsxs("div",{className:"cedros-admin__variations-editor-content",children:[e.jsx("div",{className:"cedros-admin__variations-editor-section",children:e.jsx(ye,{value:_,onChange:s,disabled:R})}),_.variationTypes.length>0&&e.jsx("div",{className:"cedros-admin__variations-editor-section",children:e.jsx(ve,{variationConfig:_,variants:a,onChange:h,defaultPrice:u,currencySymbol:g,disabled:R})})]})]})}const fe={requireSanctionsClear:!0,requireKyc:!1,requireAccreditedInvestor:!1,tokenGates:[]};function Ce({value:p,onChange:o}){const[b,u]=r.useState(p!==null),[g,A]=r.useState(""),[N,T]=r.useState("fungible_token"),[f,V]=r.useState(1),k=p??fe,v=()=>{p?(o(null),u(!1)):(o({...fe}),u(!0))},S=c=>{o({...k,...c})},R=()=>{if(!g.trim())return;const c={address:g.trim(),gateType:N,minAmount:f},a=[...k.tokenGates??[],c];S({tokenGates:a}),A(""),V(1)},_=c=>{const a=(k.tokenGates??[]).filter((l,C)=>C!==c);S({tokenGates:a.length>0?a:[]})};return e.jsxs("div",{style:{border:"1px solid var(--cedros-admin-border, #e0e0e0)",borderRadius:"4px",padding:"0.75rem",marginTop:"0.5rem"},children:[e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.9rem",fontWeight:600,cursor:"pointer"},children:[e.jsx("input",{type:"checkbox",checked:p!==null,onChange:v}),"Enable compliance gates"]}),p!==null&&b&&e.jsxs("div",{style:{marginTop:"0.75rem",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.85rem"},children:[e.jsx("input",{type:"checkbox",checked:k.requireSanctionsClear,onChange:c=>S({requireSanctionsClear:c.target.checked})}),"Require sanctions clearance"]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.85rem"},children:[e.jsx("input",{type:"checkbox",checked:k.requireKyc,onChange:c=>S({requireKyc:c.target.checked})}),"Require KYC verification"]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.85rem"},children:[e.jsx("input",{type:"checkbox",checked:k.requireAccreditedInvestor,onChange:c=>S({requireAccreditedInvestor:c.target.checked})}),"Require accredited investor status"]}),e.jsxs("div",{style:{marginTop:"0.5rem"},children:[e.jsx("span",{style:{fontSize:"0.85rem",fontWeight:600},children:"Token Gates"}),(k.tokenGates??[]).length>0&&e.jsx("div",{style:{marginTop:"0.25rem"},children:(k.tokenGates??[]).map((c,a)=>e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.8rem",padding:"0.25rem 0"},children:[e.jsxs("code",{style:{fontSize:"0.75rem"},children:[c.address.slice(0,8),"..."]}),e.jsx("span",{className:"cedros-admin__badge cedros-admin__badge--muted",children:c.gateType==="fungible_token"?"Fungible":"NFT"}),e.jsxs("span",{children:["min: ",c.minAmount]}),e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--sm",onClick:()=>_(a),style:{padding:"0 0.25rem"},children:"×"})]},a))}),e.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"flex-end",marginTop:"0.25rem",flexWrap:"wrap"},children:[e.jsx("input",{type:"text",className:"cedros-admin__input",placeholder:"Mint or collection address",value:g,onChange:c=>A(c.target.value),style:{flex:1,minWidth:"200px",fontSize:"0.8rem"}}),e.jsxs("select",{className:"cedros-admin__input",value:N,onChange:c=>T(c.target.value),style:{width:"auto",fontSize:"0.8rem"},children:[e.jsx("option",{value:"fungible_token",children:"Fungible"}),e.jsx("option",{value:"nft_collection",children:"NFT"})]}),e.jsx("input",{type:"number",className:"cedros-admin__input",min:1,value:f,onChange:c=>V(Number(c.target.value)),style:{width:"80px",fontSize:"0.8rem"}}),e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--sm",onClick:R,disabled:!g.trim(),children:"Add Gate"})]})]})]})]})}function Ne({serverUrl:p,productId:o,productTitle:b,apiKey:u,authManager:g,onClose:A}){const[N,T]=r.useState(null),[f,V]=r.useState(!0),[k,v]=r.useState(null),S=r.useCallback(async()=>{V(!0),v(null);try{const R=`/paywall/v1/products/${encodeURIComponent(o)}/nft-metadata`;let _;if(g?.isAuthenticated())_=await g.fetchWithAuth(R);else{const c={"Content-Type":"application/json"};u&&(c["X-API-Key"]=u);const a=await fetch(`${p}${R}`,{headers:c});if(!a.ok)throw new Error(`Request failed: ${a.status}`);_=await a.json()}T(_)}catch{v("Failed to load NFT metadata. Ensure this product exists and the server is running.")}finally{V(!1)}},[p,o,u,g]);return r.useEffect(()=>{S()},[S]),e.jsxs("div",{children:[e.jsxs("div",{className:"cedros-admin__section-header",style:{marginBottom:"1rem"},children:[e.jsxs("h3",{className:"cedros-admin__section-title",style:{fontSize:"1rem"},children:["NFT Metadata — ",b]}),e.jsxs("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:A,children:[$.Icons.close," Close"]})]}),e.jsx(ne.ErrorBanner,{message:k,onRetry:S}),f?e.jsxs("div",{className:"cedros-admin__loading",children:[$.Icons.loading," Loading metadata..."]}):N?e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[e.jsxs("div",{style:{display:"flex",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e0e0e0)",borderRadius:"8px"},children:[N.image&&e.jsx("img",{src:N.image,alt:N.name,style:{width:120,height:120,borderRadius:8,objectFit:"cover",flexShrink:0}}),e.jsxs("div",{style:{flex:1},children:[e.jsx("h4",{style:{margin:"0 0 0.25rem",fontSize:"1rem",fontWeight:600},children:N.name}),e.jsx("p",{style:{margin:"0 0 0.5rem",fontSize:"0.85rem",color:"var(--cedros-admin-text-muted, #888)"},children:N.description}),N.external_url&&e.jsxs("p",{style:{margin:"0 0 0.5rem",fontSize:"0.8rem"},children:[e.jsx("strong",{children:"URL:"})," ",e.jsx("code",{children:N.external_url})]}),N.attributes.length>0&&e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.5rem"},children:N.attributes.map(R=>e.jsxs("div",{style:{padding:"0.25rem 0.5rem",border:"1px solid var(--cedros-admin-border, #e0e0e0)",borderRadius:"4px",fontSize:"0.8rem"},children:[e.jsxs("span",{style:{color:"var(--cedros-admin-text-muted, #888)"},children:[R.trait_type,":"]})," ",e.jsx("strong",{children:R.value})]},R.trait_type))})]})]}),e.jsxs("div",{children:[e.jsx("h4",{style:{margin:"0 0 0.5rem",fontSize:"0.85rem",fontWeight:600},children:"Raw JSON (stored on-chain URI)"}),e.jsx("pre",{style:{background:"var(--cedros-admin-bg-muted, #f5f5f5)",border:"1px solid var(--cedros-admin-border, #e0e0e0)",borderRadius:"4px",padding:"0.75rem",fontSize:"0.8rem",overflow:"auto",maxHeight:"300px"},children:JSON.stringify(N,null,2)})]})]}):null]})}function ke({serverUrl:p,apiKey:o,pageSize:b=20,authManager:u}){const[g,A]=r.useState([]),[N,T]=r.useState(!0),[f,V]=r.useState(!1),[k,v]=r.useState(!1),[S,R]=r.useState(null),[_,c]=r.useState(null),[a,l]=r.useState(null),[C,y]=r.useState(null),[D,j]=r.useState(null),[s,h]=r.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",storePolicyFulfillment:"physical_goods",storeManagedKind:"none",appleProductId:"",googleProductId:"",googlePackageName:"",googleBasePlanId:"",googleOfferId:"",fulfillmentNotes:"",shippingCountriesCsv:"",inventoryQuantity:"",giftCardConfig:null,tokenizedAssetConfig:null,complianceRequirements:null}),I=t=>{const n=t.tagsCsv.split(",").map(J=>J.trim()).filter(Boolean),P=t.categoryIdsCsv.split(",").map(J=>J.trim()).filter(Boolean),W={email:t.checkoutEmail,name:t.checkoutName,phone:t.checkoutPhone,shippingAddress:t.checkoutShippingAddress,billingAddress:t.checkoutBillingAddress},B=t.fulfillmentType==="shipping"?"physical":"digital",z={title:t.title,slug:t.slug||t.id,shipping_profile:B,inventory_status:t.inventoryStatus,checkout_requirements:JSON.stringify(W),fulfillment_type:t.fulfillmentType,store_policy_fulfillment_type:t.storePolicyFulfillment};t.imageUrl&&(z.image_url=t.imageUrl);const X=t.compareAtUsd?Math.round(Number(t.compareAtUsd)*100):0;X&&(z.compare_at_amount_cents=String(X)),n.length&&(z.tags=JSON.stringify(n)),P.length&&(z.category_ids=JSON.stringify(P)),t.fulfillmentNotes&&(z.fulfillment_notes=t.fulfillmentNotes);const U=t.shippingCountriesCsv.split(",").map(J=>J.trim().toUpperCase()).filter(Boolean);return U.length&&(z.shippingCountries=U.join(","),z.shipping_countries=U.join(",")),z},[d,m]=r.useState([]),L=t=>t.title||t.metadata?.title||t.description||t.id,E=t=>t.imageUrl||t.images?.[0]?.url||t.metadata?.image_url,O=t=>{const n=t.metadata?.store_policy_fulfillment_type;if(n==="digital_in_app"||n==="physical_goods"||n==="real_world_service"||n==="reader_content"||n==="other")return n;switch(t.fulfillment?.type){case"shipping":return"physical_goods";case"service":return"real_world_service";case"digital_download":return"digital_in_app";default:return}},F=t=>{switch(t){case"digital_in_app":return"Digital in-app";case"physical_goods":return"Physical goods";case"real_world_service":return"Real-world service";case"reader_content":return"Reader content";case"other":return"Other";default:return"Not set"}},H=t=>{switch(t){case"consumable":return"Consumable";case"non_consumable":return"Non-consumable";case"auto_renewable_subscription":return"Auto-renewing subscription";default:return"External billing only"}},le=t=>{if(t.storeManagedKind==="none")return;const n=t.appleProductId.trim(),P=t.googleProductId.trim(),W=t.googlePackageName.trim(),B=t.googleBasePlanId.trim(),z=t.googleOfferId.trim();if(!(!n&&!P))return{kind:t.storeManagedKind,apple:n?{productId:n}:void 0,google:P?{productId:P,packageName:W||void 0,basePlanId:B||void 0,offerId:z||void 0}:void 0}},ae=t=>{const n=[],P=O(t);return P&&n.push(F(P)),t.storeBilling?.kind&&n.push(H(t.storeBilling.kind)),t.storeBilling?.apple?.productId&&n.push(`Apple ${t.storeBilling.apple.productId}`),t.storeBilling?.google?.productId&&n.push(`Google ${t.storeBilling.google.productId}`),n.join(" • ")},Z=r.useCallback(async()=>{try{j(null);let t;if(u?.isAuthenticated())t=await u.fetchWithAuth(`/admin/products?limit=${b}`);else{const n={"Content-Type":"application/json"};o&&(n["X-API-Key"]=o);const P=await fetch(`${p}/admin/products?limit=${b}`,{headers:n});if(!P.ok)throw new Error(`Failed to fetch products: ${P.status}`);t=await P.json()}A(t.products||[])}catch{A([]),j("Failed to load products")}finally{T(!1)}},[p,o,b,u]);r.useEffect(()=>{Z(),(async()=>{try{let t;if(u?.isAuthenticated())t=await u.fetchWithAuth("/admin/collections");else{const n={"Content-Type":"application/json"};o&&(n["X-API-Key"]=o);const P=await fetch(`${p}/admin/collections`,{headers:n});if(!P.ok)return;t=await P.json()}m((t.collections||[]).filter(n=>n.tokenizationConfig).map(n=>({id:n.id,name:n.name})))}catch{}})()},[Z,p,o,u]);const ue=async t=>{if(t.preventDefault(),!(!s.id||!s.description)){if(R(null),s.fulfillmentType==="shipping"&&s.checkoutShippingAddress&&!s.shippingCountriesCsv.split(",").map(P=>P.trim()).filter(Boolean).length){R("Shipping countries are required when collecting shipping address. Example: US,CA");return}if(s.storeManagedKind!=="none"&&!s.appleProductId.trim()&&!s.googleProductId.trim()){R("Add at least one Apple or Google store product ID for store-managed products.");return}if(s.googleBasePlanId.trim()&&!s.googleProductId.trim()){R("Google base plan ID requires a Google product ID.");return}if(s.storeManagedKind==="auto_renewable_subscription"&&s.googleProductId.trim()&&!s.googleBasePlanId.trim()){R("Google Play subscriptions require a base plan ID.");return}v(!0);try{const{productType:n}=s,P=s.inventoryQuantity===""?void 0:Number.isFinite(Number(s.inventoryQuantity))?Number(s.inventoryQuantity):void 0,W=Number(s.priceUsd)||0,B=Math.round(W*100),z=Math.round(W*1e6),X=s.tagsCsv.split(",").map(x=>x.trim()).filter(Boolean),U=s.categoryIdsCsv.split(",").map(x=>x.trim()).filter(Boolean),J={email:s.checkoutEmail,name:s.checkoutName,phone:s.checkoutPhone,shippingAddress:s.checkoutShippingAddress,billingAddress:s.checkoutBillingAddress},oe=le(s),re=s.compareAtUsd===""?void 0:Math.round(Number(s.compareAtUsd)*100),i={id:s.id,title:s.title||void 0,slug:s.slug||void 0,description:s.description,tags:X,categoryIds:U,images:s.imageUrl?[{url:s.imageUrl,alt:s.title||s.id}]:[],shippingProfile:s.fulfillmentType==="shipping"?"physical":"digital",checkoutRequirements:J,fulfillment:{type:s.fulfillmentType,notes:s.fulfillmentNotes||void 0},fiatAmountCents:B,fiatCurrency:s.fiatCurrency,compareAtFiatAmountCents:re,compareAtFiatCurrency:re?s.fiatCurrency:void 0,cryptoAtomicAmount:z,cryptoToken:s.cryptoToken,inventoryStatus:s.fulfillmentType==="shipping"?s.inventoryStatus:void 0,...P!==void 0?{inventoryQuantity:P}:{},...oe?{storeBilling:oe}:{},metadata:{...n?{product_type:n}:{},...I(s)}};if(n==="gift_card"&&s.giftCardConfig&&(i.giftCardConfig=s.giftCardConfig),n==="tokenized_asset"&&s.tokenizedAssetConfig&&(i.tokenizedAssetConfig=s.tokenizedAssetConfig),s.complianceRequirements&&(i.complianceRequirements=s.complianceRequirements),u?.isAuthenticated())await u.fetchWithAuth("/admin/products",{method:"POST",body:JSON.stringify(i)});else{const x={"Content-Type":"application/json"};o&&(x["X-API-Key"]=o);const w=await fetch(`${p}/admin/products`,{method:"POST",headers:x,body:JSON.stringify(i)});if(!w.ok)throw new Error(`Failed to create product: ${w.status}`)}h({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",storePolicyFulfillment:"physical_goods",storeManagedKind:"none",appleProductId:"",googleProductId:"",googlePackageName:"",googleBasePlanId:"",googleOfferId:"",fulfillmentNotes:"",shippingCountriesCsv:"",inventoryQuantity:"",giftCardConfig:null,tokenizedAssetConfig:null,complianceRequirements:null}),V(!1),Z()}catch(n){R(n instanceof Error?n.message:"Failed to create product")}finally{v(!1)}}},me=t=>`$${(t/100).toFixed(2)}`,se=t=>{switch(t){case"subscription":return"Subscription";case"pay_per_access":return"Pay per access";case"one_time":return"One-time purchase";case"gift_card":return"Gift card";default:return"One-time purchase"}},ie=s.storePolicyFulfillment==="digital_in_app"||s.storePolicyFulfillment==="reader_content"||s.storePolicyFulfillment==="other"||s.productType==="subscription"||s.storeManagedKind!=="none",ee=r.useMemo(()=>{const t=g.filter(P=>P.active).length,n=g.reduce((P,W)=>{const B=W.variations?.length??0;return P+(B>0?B:1)},0);return{activeCount:t,totalSkus:n}},[g]),K=t=>{y(n=>!n||n.key!==t?{key:t,direction:"asc"}:{key:t,direction:n.direction==="asc"?"desc":"asc"})},Y=t=>!C||C.key!==t?e.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:$.Icons.chevronUp}):e.jsx("span",{className:"cedros-admin__sort-icon",children:C.direction==="asc"?$.Icons.chevronUp:$.Icons.chevronDown}),he=r.useMemo(()=>{if(!C)return g;const t=C.direction==="asc"?1:-1,n=P=>{switch(C.key){case"product":return L(P);case"type":return se(P.metadata?.product_type);case"price":return P.fiatAmountCents??0;case"status":return P.active?1:0;case"id":default:return P.id}};return[...g].sort((P,W)=>{const B=n(P),z=n(W);return typeof B=="number"&&typeof z=="number"?(B-z)*t:String(B).localeCompare(String(z),void 0,{sensitivity:"base"})*t})},[g,C]);return e.jsxs("div",{className:"cedros-admin__page",children:[e.jsx(ne.ErrorBanner,{message:D,onRetry:Z}),e.jsx(ce.StatsBar,{stats:[{label:"Total Products",value:g.length},{label:"Active",value:ee.activeCount,variant:ee.activeCount>0?"success":"muted"},{label:"Total SKUs",value:ee.totalSkus}],isLoading:N}),e.jsxs("div",{className:"cedros-admin__section-header",children:[e.jsx("h3",{className:"cedros-admin__section-title",children:"Paywall Products"}),e.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:()=>{R(null),V(!f)},children:[f?$.Icons.close:$.Icons.plus,f?"Cancel":"Add Product"]})]}),f&&e.jsxs("form",{onSubmit:ue,className:"cedros-admin__add-form",children:[S&&e.jsx("div",{style:{marginBottom:"0.75rem",color:"#B42318",fontWeight:600},children:S}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Product ID"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.id,onChange:t=>h(n=>({...n,id:t.target.value})),placeholder:"e.g., premium-article",required:!0})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Product name"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.title,onChange:t=>h(n=>({...n,title:t.target.value})),placeholder:"e.g., Cedros Hoodie"})]})]}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Slug"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.slug,onChange:t=>h(n=>({...n,slug:t.target.value})),placeholder:"e.g., cedros-hoodie (defaults to ID)"})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Primary image URL"}),e.jsx("input",{type:"url",className:"cedros-admin__input",value:s.imageUrl,onChange:t=>h(n=>({...n,imageUrl:t.target.value})),placeholder:"https://..."})]})]}),e.jsx("div",{className:"cedros-admin__form-row",children:e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Short description"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.description,onChange:t=>h(n=>({...n,description:t.target.value})),placeholder:"e.g., Midweight fleece with relaxed fit",required:!0})]})}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsx(M.FormDropdown,{value:s.productType,onChange:t=>h(n=>({...n,productType:t,storeManagedKind:t==="subscription"?"auto_renewable_subscription":n.storeManagedKind==="auto_renewable_subscription"?"non_consumable":n.storeManagedKind,giftCardConfig:t==="gift_card"?n.giftCardConfig??{faceValueCents:0,currency:"usd",secondaryMarket:!1,expiresInDays:null}:null,tokenizedAssetConfig:t==="tokenized_asset"?n.tokenizedAssetConfig??{assetClassCollectionId:"",backingValueCents:0,backingCurrency:"usd",assetIdentifier:"",tokensPerUnit:1,custodyProofUrl:null}:null})),options:[{value:"one_time",label:"One-time purchase"},{value:"pay_per_access",label:"Pay per access"},{value:"subscription",label:"Subscription"},{value:"gift_card",label:"Gift card"},{value:"tokenized_asset",label:"Tokenized asset"}],label:"Product Type"}),e.jsx(M.FormDropdown,{value:s.fulfillmentType,onChange:t=>{const n=t;h(P=>({...P,fulfillmentType:n,storePolicyFulfillment:n==="shipping"?"physical_goods":n==="service"?"real_world_service":"digital_in_app",storeManagedKind:n==="shipping"||n==="service"?"none":P.productType==="subscription"?"auto_renewable_subscription":P.storeManagedKind==="none"?"non_consumable":P.storeManagedKind,checkoutShippingAddress:n==="shipping"?P.checkoutShippingAddress:!1}))},options:[{value:"shipping",label:"Physical (shipped)"},{value:"digital_download",label:"Digital download"},{value:"service",label:"Service"}],label:"Fulfillment"})]}),e.jsxs("div",{style:{padding:"0.9rem 1rem",borderRadius:"0.75rem",border:"1px solid var(--cedros-admin-border, #e5e7eb)",background:"var(--cedros-admin-surface, #ffffff)",marginBottom:"1rem"},children:[e.jsx("div",{style:{fontWeight:700,marginBottom:"0.35rem"},children:"Store policy and app billing"}),e.jsx("div",{style:{fontSize:"0.9rem",lineHeight:1.6,opacity:.8},children:"This controls how Cedros routes payments across the web, Apple App Store, and Google Play. For digital app functionality, choose the explicit store policy classification here instead of relying on generic product type labels."})]}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsx(M.FormDropdown,{value:s.storePolicyFulfillment,onChange:t=>h(n=>({...n,storePolicyFulfillment:t,storeManagedKind:t==="physical_goods"||t==="real_world_service"?"none":n.storeManagedKind})),options:[{value:"digital_in_app",label:"Digital in-app"},{value:"physical_goods",label:"Physical goods"},{value:"real_world_service",label:"Real-world service"},{value:"reader_content",label:"Reader content"},{value:"other",label:"Other / review manually"}],label:"Store policy classification"}),e.jsx(M.FormDropdown,{value:s.storeManagedKind,onChange:t=>h(n=>({...n,storeManagedKind:t})),options:[{value:"none",label:"External billing only"},{value:"consumable",label:"Consumable"},{value:"non_consumable",label:"Non-consumable"},{value:"auto_renewable_subscription",label:"Auto-renewing subscription"}],label:"Store-managed product kind"})]}),ie&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Apple product ID"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.appleProductId,onChange:t=>h(n=>({...n,appleProductId:t.target.value})),placeholder:"e.g., com.cedros.pro.monthly"}),e.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Create the matching product in App Store Connect and paste the product ID here."})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Google product ID"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.googleProductId,onChange:t=>h(n=>({...n,googleProductId:t.target.value})),placeholder:"e.g., pro_monthly"}),e.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Create the matching one-time product or subscription in Google Play Console."})]})]}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Google package name"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.googlePackageName,onChange:t=>h(n=>({...n,googlePackageName:t.target.value})),placeholder:"e.g., com.cedros.app"})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Google base plan ID"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.googleBasePlanId,onChange:t=>h(n=>({...n,googleBasePlanId:t.target.value})),placeholder:"Required for Google subscriptions"})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Google offer ID"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.googleOfferId,onChange:t=>h(n=>({...n,googleOfferId:t.target.value})),placeholder:"Optional"})]})]})]}),s.productType==="gift_card"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Gift card face value (USD cents)"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:s.giftCardConfig?.faceValueCents??"",onChange:t=>h(n=>({...n,giftCardConfig:{faceValueCents:parseInt(t.target.value)||0,currency:n.giftCardConfig?.currency??"usd",secondaryMarket:n.giftCardConfig?.secondaryMarket??!1,expiresInDays:n.giftCardConfig?.expiresInDays??null}})),placeholder:"e.g., 5000 for $50.00",min:"1",required:!0}),e.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Face value in cents (e.g. 5000 = $50.00). Must be greater than 0."})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Gift card currency"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.giftCardConfig?.currency??"",onChange:t=>h(n=>({...n,giftCardConfig:{faceValueCents:n.giftCardConfig?.faceValueCents??0,currency:t.target.value.toLowerCase().slice(0,3),secondaryMarket:n.giftCardConfig?.secondaryMarket??!1,expiresInDays:n.giftCardConfig?.expiresInDays??null}})),placeholder:"usd",maxLength:3,required:!0}),e.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"ISO 4217 3-letter currency code (e.g. usd, eur, gbp)."})]})]}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Expiration (days)"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:s.giftCardConfig?.expiresInDays??"",onChange:t=>h(n=>({...n,giftCardConfig:{faceValueCents:n.giftCardConfig?.faceValueCents??0,currency:n.giftCardConfig?.currency??"usd",secondaryMarket:n.giftCardConfig?.secondaryMarket??!1,expiresInDays:t.target.value===""?null:parseInt(t.target.value)||0}})),placeholder:"Leave blank for no expiry",min:"0"}),e.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Number of days until gift card expires. Leave blank for no expiry."})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Secondary market (Token-22)"}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginTop:8},children:[e.jsx("input",{type:"checkbox",checked:s.giftCardConfig?.secondaryMarket??!1,onChange:t=>h(n=>({...n,giftCardConfig:{faceValueCents:n.giftCardConfig?.faceValueCents??0,currency:n.giftCardConfig?.currency??"usd",secondaryMarket:t.target.checked,expiresInDays:n.giftCardConfig?.expiresInDays??null}}))}),"Enable Token-22 secondary market trading"]}),e.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Mints store credit tokens to recipient's embedded wallet for peer-to-peer trading with transfer fees."})]})]})]}),s.productType==="tokenized_asset"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Asset class collection"}),d.length>0?e.jsxs("select",{className:"cedros-admin__input",value:s.tokenizedAssetConfig?.assetClassCollectionId??"",onChange:t=>h(n=>({...n,tokenizedAssetConfig:{...n.tokenizedAssetConfig,assetClassCollectionId:t.target.value}})),required:!0,children:[e.jsx("option",{value:"",children:"Select asset class..."}),d.map(t=>e.jsx("option",{value:t.id,children:t.name},t.id))]}):e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.tokenizedAssetConfig?.assetClassCollectionId??"",onChange:t=>h(n=>({...n,tokenizedAssetConfig:{...n.tokenizedAssetConfig,assetClassCollectionId:t.target.value}})),placeholder:"Collection ID of the asset class",required:!0})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Backing value (cents)"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:s.tokenizedAssetConfig?.backingValueCents??0,onChange:t=>h(n=>({...n,tokenizedAssetConfig:{...n.tokenizedAssetConfig,backingValueCents:Number(t.target.value)}})),min:0})]})]}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Backing currency"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.tokenizedAssetConfig?.backingCurrency??"usd",onChange:t=>h(n=>({...n,tokenizedAssetConfig:{...n.tokenizedAssetConfig,backingCurrency:t.target.value}})),placeholder:"usd",maxLength:3})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Asset identifier"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.tokenizedAssetConfig?.assetIdentifier??"",onChange:t=>h(n=>({...n,tokenizedAssetConfig:{...n.tokenizedAssetConfig,assetIdentifier:t.target.value}})),placeholder:"e.g., ISIN, lot number"})]})]}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Tokens per unit"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:s.tokenizedAssetConfig?.tokensPerUnit??1,onChange:t=>h(n=>({...n,tokenizedAssetConfig:{...n.tokenizedAssetConfig,tokensPerUnit:Number(t.target.value)}})),min:1})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Custody proof URL"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.tokenizedAssetConfig?.custodyProofUrl??"",onChange:t=>h(n=>({...n,tokenizedAssetConfig:{...n.tokenizedAssetConfig,custodyProofUrl:t.target.value||null}})),placeholder:"https://..."})]})]})]}),s.fulfillmentType==="shipping"&&e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsx(M.FormDropdown,{value:s.inventoryStatus,onChange:t=>h(n=>({...n,inventoryStatus:t})),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"}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Inventory quantity (tracked)"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:s.inventoryQuantity,onChange:t=>h(n=>({...n,inventoryQuantity:t.target.value===""?"":parseInt(t.target.value)||0})),placeholder:"Leave blank for untracked",min:"0"})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Compare-at price (USD)"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:s.compareAtUsd===""?"":s.compareAtUsd,onChange:t=>h(n=>({...n,compareAtUsd:t.target.value===""?"":parseFloat(t.target.value)||0})),placeholder:"e.g., 78.00",min:"0",step:"0.01"})]})]}),e.jsx("div",{className:"cedros-admin__form-row",children:e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Price (USD)"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:s.priceUsd===""?"":s.priceUsd,onChange:t=>h(n=>({...n,priceUsd:t.target.value===""?"":parseFloat(t.target.value)||0})),placeholder:"e.g., 5.00",min:"0",step:"0.01",required:!0})]})}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Tags (comma-separated)"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.tagsCsv,onChange:t=>h(n=>({...n,tagsCsv:t.target.value})),placeholder:"e.g., core, new, gift"})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Category IDs (comma-separated)"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.categoryIdsCsv,onChange:t=>h(n=>({...n,categoryIdsCsv:t.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"})]})]}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsx(M.FormDropdown,{value:s.checkoutEmail,onChange:t=>h(n=>({...n,checkoutEmail:t})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Email"}),e.jsx(M.FormDropdown,{value:s.checkoutName,onChange:t=>h(n=>({...n,checkoutName:t})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Name"}),e.jsx(M.FormDropdown,{value:s.checkoutPhone,onChange:t=>h(n=>({...n,checkoutPhone:t})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Phone"})]}),e.jsxs("div",{className:"cedros-admin__form-row",children:[s.fulfillmentType==="shipping"&&e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Checkout: Shipping address"}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[e.jsx("input",{type:"checkbox",checked:s.checkoutShippingAddress,onChange:t=>h(n=>({...n,checkoutShippingAddress:t.target.checked}))}),"Collect shipping address"]})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Checkout: Billing address"}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[e.jsx("input",{type:"checkbox",checked:s.checkoutBillingAddress,onChange:t=>h(n=>({...n,checkoutBillingAddress:t.target.checked}))}),"Collect billing address"]})]})]}),e.jsx("div",{className:"cedros-admin__form-row",children:e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Fulfillment notes"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.fulfillmentNotes,onChange:t=>h(n=>({...n,fulfillmentNotes:t.target.value})),placeholder:s.fulfillmentType==="shipping"?"e.g., Ships within 3-5 business days":"e.g., Downloadable from your account after purchase"})]})}),s.fulfillmentType==="shipping"&&s.checkoutShippingAddress&&e.jsx("div",{className:"cedros-admin__form-row",children:e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Shipping countries"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.shippingCountriesCsv,onChange:t=>h(n=>({...n,shippingCountriesCsv:t.target.value})),placeholder:"e.g., US,CA"}),e.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"ISO 2-letter country codes, comma-separated. Required for shipping address collection."})]})}),e.jsx(Ce,{value:s.complianceRequirements,onChange:t=>h(n=>({...n,complianceRequirements:t}))}),e.jsx("div",{className:"cedros-admin__form-actions",children:e.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:k,children:k?"Creating...":"Create Product"})})]}),N?e.jsxs("div",{className:"cedros-admin__loading",children:[$.Icons.loading," Loading products..."]}):e.jsx("div",{className:"cedros-admin__table-container",children:e.jsxs("table",{className:"cedros-admin__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{"aria-sort":C?.key==="id"?C?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>K("id"),children:["ID",Y("id")]})}),e.jsx("th",{"aria-sort":C?.key==="product"?C?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>K("product"),children:["Product",Y("product")]})}),e.jsx("th",{"aria-sort":C?.key==="type"?C?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>K("type"),children:["Type",Y("type")]})}),e.jsx("th",{"aria-sort":C?.key==="price"?C?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>K("price"),children:["Price",Y("price")]})}),e.jsx("th",{"aria-sort":C?.key==="status"?C?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>K("status"),children:["Status",Y("status")]})}),e.jsx("th",{children:"Actions"})]})}),e.jsx("tbody",{children:he.map(t=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("code",{children:t.id})}),e.jsx("td",{children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[E(t)?e.jsx("img",{src:E(t),alt:"",style:{width:28,height:28,borderRadius:6,objectFit:"cover"}}):e.jsx("div",{style:{width:28,height:28,borderRadius:6,background:"rgba(0,0,0,0.06)"}}),e.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[e.jsx("span",{style:{fontWeight:600},children:L(t)}),e.jsx("span",{style:{opacity:.8},children:t.description}),ae(t)?e.jsx("span",{style:{opacity:.7,fontSize:"0.8rem"},children:ae(t)}):null]})]})}),e.jsx("td",{children:se(t.metadata?.product_type)}),e.jsx("td",{children:me(t.fiatAmountCents)}),e.jsx("td",{children:e.jsx("span",{className:`cedros-admin__badge ${t.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:t.active?"Active":"Inactive"})}),e.jsx("td",{children:e.jsxs("div",{style:{display:"flex",gap:"0.25rem"},children:[e.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>c(t),children:"Variations"}),t.metadata?.product_type==="tokenized_asset"&&e.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>l(t),children:"NFT"})]})})]},t.id))})]})}),_&&e.jsx("div",{className:"cedros-admin__modal-overlay",onClick:()=>c(null),children:e.jsx("div",{className:"cedros-admin__modal cedros-admin__modal--lg",onClick:t=>t.stopPropagation(),children:e.jsx(je,{serverUrl:p,productId:_.id,productTitle:L(_),defaultPrice:_.fiatAmountCents/100,apiKey:o,authManager:u,onClose:()=>c(null)})})}),a&&e.jsx("div",{className:"cedros-admin__modal-overlay",onClick:()=>l(null),children:e.jsx("div",{className:"cedros-admin__modal cedros-admin__modal--lg",onClick:t=>t.stopPropagation(),children:e.jsx(Ne,{serverUrl:p,productId:a.id,productTitle:L(a),apiKey:o,authManager:u,onClose:()=>l(null)})})})]})}function Se({serverUrl:p,apiKey:o,pageSize:b=20,authManager:u}){const[g,A]=r.useState([]),[N,T]=r.useState(null),[f,V]=r.useState(!0),[k,v]=r.useState(!0),[S,R]=r.useState(null),[_,c]=r.useState(""),[a,l]=r.useState(null),C=r.useCallback(async()=>{v(!0);try{R(null);let I;if(u?.isAuthenticated())I=await u.fetchWithAuth("/admin/stats");else{const d={"Content-Type":"application/json"};o&&(d["X-API-Key"]=o);const m=await fetch(`${p}/admin/stats`,{headers:d});if(!m.ok)throw new Error(`Failed to fetch stats: ${m.status}`);I=await m.json()}T(I)}catch{T(null),R("Failed to load payment stats")}finally{v(!1)}},[p,o,u]);r.useEffect(()=>{C()},[C]);const y=r.useCallback(async()=>{try{R(null);let I;const d=new URLSearchParams({limit:b.toString()});_&&d.set("method",_);const m=`/admin/transactions?${d}`;if(u?.isAuthenticated())I=await u.fetchWithAuth(m);else{const L={"Content-Type":"application/json"};o&&(L["X-API-Key"]=o);const E=await fetch(`${p}${m}`,{headers:L});if(!E.ok)throw new Error(`Failed to fetch transactions: ${E.status}`);I=await E.json()}A(I.transactions||[])}catch{A([]),R("Failed to load transactions")}finally{V(!1)}},[p,o,b,_,u]);r.useEffect(()=>{y()},[y]);const D=(I,d="USD")=>new Intl.NumberFormat("en-US",{style:"currency",currency:d}).format(I),j=I=>{l(d=>!d||d.key!==I?{key:I,direction:"asc"}:{key:I,direction:d.direction==="asc"?"desc":"asc"})},s=I=>!a||a.key!==I?e.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:$.Icons.chevronUp}):e.jsx("span",{className:"cedros-admin__sort-icon",children:a.direction==="asc"?$.Icons.chevronUp:$.Icons.chevronDown}),h=r.useMemo(()=>{if(!a)return g;const I=a.direction==="asc"?1:-1,d=m=>{switch(a.key){case"resource":return m.resourceId;case"method":return m.method;case"amount":return m.amount;case"status":return m.status;case"date":return new Date(m.paidAt).getTime();case"id":default:return m.id}};return[...g].sort((m,L)=>{const E=d(m),O=d(L);return typeof E=="number"&&typeof O=="number"?(E-O)*I:String(E).localeCompare(String(O),void 0,{sensitivity:"base"})*I})},[g,a]);return e.jsxs("div",{className:"cedros-admin__page",children:[e.jsx(ne.ErrorBanner,{message:S,onRetry:()=>{C(),y()}}),e.jsx(ce.StatsBar,{stats:[{label:"Revenue",value:D(N?.totalRevenue??0)},{label:"Orders",value:N?.totalTransactions??0},{label:"Card",value:D(N?.revenueByMethod.stripe??0),description:`${N?.transactionsByMethod.stripe??0} orders`},{label:"Crypto",value:D(N?.revenueByMethod.x402??0),description:`${N?.transactionsByMethod.x402??0} orders`},{label:"Credits",value:D(N?.revenueByMethod.credits??0),description:`${N?.transactionsByMethod.credits??0} orders`}],isLoading:k,onRefresh:C}),e.jsxs("div",{className:"cedros-admin__section-header",children:[e.jsx("h3",{className:"cedros-admin__section-title",children:"Transaction History"}),e.jsx(M.FilterDropdown,{value:_,onChange:c,options:[{value:"",label:"All"},{value:"stripe",label:"Card"},{value:"x402",label:"Crypto"},{value:"credits",label:"Credits"}]})]}),f?e.jsxs("div",{className:"cedros-admin__loading",children:[$.Icons.loading," Loading transactions..."]}):e.jsx("div",{className:"cedros-admin__table-container",children:e.jsxs("table",{className:"cedros-admin__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{"aria-sort":a?.key==="id"?a?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("id"),children:["ID",s("id")]})}),e.jsx("th",{"aria-sort":a?.key==="resource"?a?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("resource"),children:["Resource",s("resource")]})}),e.jsx("th",{"aria-sort":a?.key==="method"?a?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("method"),children:["Method",s("method")]})}),e.jsx("th",{"aria-sort":a?.key==="amount"?a?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("amount"),children:["Amount",s("amount")]})}),e.jsx("th",{"aria-sort":a?.key==="status"?a?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("status"),children:["Status",s("status")]})}),e.jsx("th",{"aria-sort":a?.key==="date"?a?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("date"),children:["Date",s("date")]})})]})}),e.jsx("tbody",{children:h.map(I=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("code",{children:I.id})}),e.jsx("td",{children:I.resourceId}),e.jsx("td",{children:e.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${I.method}`,children:I.method})}),e.jsxs("td",{children:["$",I.amount.toFixed(2)," ",I.currency.toUpperCase()]}),e.jsx("td",{children:e.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${I.status}`,children:I.status})}),e.jsx("td",{children:de.formatDateTime(I.paidAt)})]},I.id))})]})})]})}function we({serverUrl:p,apiKey:o,pageSize:b=20,authManager:u}){const[g,A]=r.useState([]),[N,T]=r.useState(!0),[f,V]=r.useState(!1),[k,v]=r.useState(!1),[S,R]=r.useState(null),[_,c]=r.useState(null),[a,l]=r.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}),C=r.useCallback(async()=>{try{c(null);let d;const m=`/admin/coupons?limit=${b}`;if(u?.isAuthenticated())d=await u.fetchWithAuth(m);else{const L={"Content-Type":"application/json"};o&&(L["X-API-Key"]=o);const E=await fetch(`${p}${m}`,{headers:L});if(!E.ok)throw new Error(`Failed to fetch coupons: ${E.status}`);d=await E.json()}A(d.coupons||[])}catch(d){te.getLogger().error("[CouponsSection] Failed to fetch coupons:",d,{serverUrl:p.slice(0,20)+"...",hasApiKey:!!o}),A([]),c("Failed to load coupons")}finally{T(!1)}},[p,o,b,u]);r.useEffect(()=>{C()},[C]);const y=async d=>{if(d.preventDefault(),!(!a.code||a.discountValue<=0)){v(!0);try{const m=a.minimumAmountUsd?Math.round(Number(a.minimumAmountUsd)*100):void 0,L=a.productIdsCsv.split(",").map(F=>F.trim()).filter(Boolean),E=a.categoryIdsCsv.split(",").map(F=>F.trim()).filter(Boolean),O={code:a.code,discountType:a.discountType,discountValue:a.discountValue,usageLimit:a.usageLimit,active:!0,usageCount:0,scope:a.scope,...L.length?{productIds:L}:{},...E.length?{categoryIds:E}:{},...a.paymentMethod!=="any"?{paymentMethod:a.paymentMethod}:{},...a.autoApply?{autoApply:!0}:{},...a.appliesAt!=="both"?{appliesAt:a.appliesAt}:{},...a.startsAt?{startsAt:a.startsAt}:{},...a.expiresAt?{expiresAt:a.expiresAt}:{},...m?{minimumAmountCents:m}:{},...a.usageLimitPerCustomer?{usageLimitPerCustomer:a.usageLimitPerCustomer}:{},...a.firstPurchaseOnly?{firstPurchaseOnly:!0}:{}};if(u?.isAuthenticated())await u.fetchWithAuth("/admin/coupons",{method:"POST",body:JSON.stringify(O)});else{const F={"Content-Type":"application/json"};o&&(F["X-API-Key"]=o);const H=await fetch(`${p}/admin/coupons`,{method:"POST",headers:F,body:JSON.stringify(O)});if(!H.ok)throw new Error(`Failed to create coupon: ${H.status}`)}l({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}),V(!1),C()}catch(m){te.getLogger().error("[CouponsSection] Failed to add coupon:",m,{serverUrl:p.slice(0,20)+"...",hasApiKey:!!o}),c("Failed to create coupon")}finally{v(!1)}}},D=g.filter(d=>d.active).length,j=g.reduce((d,m)=>d+(m.usageCount??0),0),s=d=>{R(m=>!m||m.key!==d?{key:d,direction:"asc"}:{key:d,direction:m.direction==="asc"?"desc":"asc"})},h=d=>!S||S.key!==d?e.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:$.Icons.chevronUp}):e.jsx("span",{className:"cedros-admin__sort-icon",children:S.direction==="asc"?$.Icons.chevronUp:$.Icons.chevronDown}),I=r.useMemo(()=>{if(!S)return g;const d=S.direction==="asc"?1:-1,m=L=>{switch(S.key){case"discount":return L.discountValue??0;case"usage":return L.usageCount??0;case"status":return L.active?1:0;case"code":default:return L.code}};return[...g].sort((L,E)=>{const O=m(L),F=m(E);return typeof O=="number"&&typeof F=="number"?(O-F)*d:String(O).localeCompare(String(F),void 0,{sensitivity:"base"})*d})},[g,S]);return e.jsxs("div",{className:"cedros-admin__page",children:[e.jsx(ne.ErrorBanner,{message:_,onRetry:C}),e.jsx(ce.StatsBar,{stats:[{label:"Total Coupons",value:g.length},{label:"Active",value:D,variant:D>0?"success":"muted"},{label:"Redemptions",value:j}],isLoading:N}),e.jsxs("div",{className:"cedros-admin__section-header",children:[e.jsx("h3",{className:"cedros-admin__section-title",children:"Discount Coupons"}),e.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:()=>V(!f),children:[f?$.Icons.close:$.Icons.plus,f?"Cancel":"Add Coupon"]})]}),f&&e.jsxs("form",{onSubmit:y,className:"cedros-admin__add-form",children:[e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Coupon Code"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:a.code,onChange:d=>l(m=>({...m,code:d.target.value.toUpperCase()})),placeholder:"e.g., SAVE20",required:!0})]}),e.jsx(M.FormDropdown,{value:a.discountType,onChange:d=>l(m=>({...m,discountType:d})),options:[{value:"percentage",label:"Percentage (%)"},{value:"fixed",label:"Fixed Amount ($)"}],label:"Discount Type"})]}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsxs("label",{className:"cedros-admin__field-label",children:["Discount Value ",a.discountType==="percentage"?"(%)":"($)"]}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:a.discountValue||"",onChange:d=>l(m=>({...m,discountValue:parseFloat(d.target.value)||0})),placeholder:a.discountType==="percentage"?"e.g., 20":"e.g., 10.00",min:"0",step:a.discountType==="percentage"?"1":"0.01",required:!0})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Usage Limit (optional)"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:a.usageLimit||"",onChange:d=>l(m=>({...m,usageLimit:d.target.value?parseInt(d.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Expiration Date (optional)"}),e.jsx("input",{type:"date",className:"cedros-admin__input",value:a.expiresAt,onChange:d=>l(m=>({...m,expiresAt:d.target.value}))})]})]}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsx(M.FormDropdown,{value:a.scope,onChange:d=>l(m=>({...m,scope:d})),options:[{value:"all_products",label:"All Products"},{value:"specific_products",label:"Specific Products"},{value:"specific_categories",label:"Specific Categories"}],label:"Scope"}),e.jsx(M.FormDropdown,{value:a.paymentMethod,onChange:d=>l(m=>({...m,paymentMethod:d})),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"}),e.jsx(M.FormDropdown,{value:a.appliesAt,onChange:d=>l(m=>({...m,appliesAt:d})),options:[{value:"both",label:"Cart & Checkout"},{value:"cart",label:"Cart Only"},{value:"checkout",label:"Checkout Only"}],label:"Applies At"})]}),a.scope==="specific_products"&&e.jsx("div",{className:"cedros-admin__form-row",children:e.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Product IDs"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:a.productIdsCsv,onChange:d=>l(m=>({...m,productIdsCsv:d.target.value})),placeholder:"e.g., prod_123, prod_456"}),e.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated product IDs this coupon applies to."})]})}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Start Date (optional)"}),e.jsx("input",{type:"date",className:"cedros-admin__input",value:a.startsAt,onChange:d=>l(m=>({...m,startsAt:d.target.value}))})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Auto Apply"}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[e.jsx("input",{type:"checkbox",checked:a.autoApply,onChange:d=>l(m=>({...m,autoApply:d.target.checked}))}),"Automatically apply when conditions met"]})]})]}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Minimum Purchase (USD)"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:a.minimumAmountUsd===""?"":a.minimumAmountUsd,onChange:d=>l(m=>({...m,minimumAmountUsd:d.target.value===""?"":parseFloat(d.target.value)||0})),placeholder:"e.g., 50.00",min:"0",step:"0.01"})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Per-Customer Limit"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:a.usageLimitPerCustomer||"",onChange:d=>l(m=>({...m,usageLimitPerCustomer:d.target.value?parseInt(d.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"First Purchase Only"}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[e.jsx("input",{type:"checkbox",checked:a.firstPurchaseOnly,onChange:d=>l(m=>({...m,firstPurchaseOnly:d.target.checked}))}),"New customers only"]})]})]}),a.scope==="specific_categories"&&e.jsx("div",{className:"cedros-admin__form-row",children:e.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Category IDs"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:a.categoryIdsCsv,onChange:d=>l(m=>({...m,categoryIdsCsv:d.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"}),e.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated category IDs this coupon applies to."})]})}),e.jsx("div",{className:"cedros-admin__form-actions",children:e.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:k,children:k?"Creating...":"Create Coupon"})})]}),N?e.jsxs("div",{className:"cedros-admin__loading",children:[$.Icons.loading," Loading coupons..."]}):e.jsx("div",{className:"cedros-admin__table-container",children:e.jsxs("table",{className:"cedros-admin__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{"aria-sort":S?.key==="code"?S?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>s("code"),children:["Code",h("code")]})}),e.jsx("th",{"aria-sort":S?.key==="discount"?S?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>s("discount"),children:["Discount",h("discount")]})}),e.jsx("th",{"aria-sort":S?.key==="usage"?S?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>s("usage"),children:["Usage",h("usage")]})}),e.jsx("th",{"aria-sort":S?.key==="status"?S?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>s("status"),children:["Status",h("status")]})}),e.jsx("th",{children:"Actions"})]})}),e.jsx("tbody",{children:I.map(d=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("code",{children:d.code})}),e.jsx("td",{children:d.discountType==="percentage"?`${d.discountValue}%`:`$${d.discountValue.toFixed(2)}`}),e.jsxs("td",{children:[d.usageCount,d.usageLimit?` / ${d.usageLimit}`:""]}),e.jsx("td",{children:e.jsx("span",{className:`cedros-admin__badge ${d.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:d.active?"Active":"Inactive"})}),e.jsx("td",{children:e.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",children:"Edit"})})]},d.code))})]})})]})}function Ae({serverUrl:p,apiKey:o,pageSize:b=20,authManager:u}){const[g,A]=r.useState([]),[N,T]=r.useState(!0),[f,V]=r.useState(null),[k,v]=r.useState([]),[S,R]=r.useState(!0),[_,c]=r.useState(null),[a,l]=r.useState([]),[C,y]=r.useState(!0),[D,j]=r.useState(null),[s,h]=r.useState(null),[I,d]=r.useState(null),m=r.useCallback(async()=>{try{let i;const x=`/admin/refunds?limit=${b}`;if(u?.isAuthenticated())i=await u.fetchWithAuth(x);else{const w={"Content-Type":"application/json"};o&&(w["X-API-Key"]=o);const q=await fetch(`${p}${x}`,{headers:w});if(!q.ok)throw new Error(`Failed to fetch x402 refunds: ${q.status}`);i=await q.json()}A(i.refunds||[])}catch(i){te.getLogger().error("[RefundsSection] Failed to fetch x402 refunds:",i,{serverUrl:p.slice(0,20)+"...",hasApiKey:!!o}),A([]),d("Failed to load x402 refunds")}finally{T(!1)}},[p,o,b,u]);r.useEffect(()=>{m()},[m]);const L=r.useCallback(async()=>{try{let i;const x=`/admin/credits/refund-requests?status=pending&limit=${b}&offset=0`;if(u?.isAuthenticated())i=await u.fetchWithAuth(x);else{const q={"Content-Type":"application/json"};o&&(q["X-API-Key"]=o);const G=await fetch(`${p}${x}`,{headers:q});if(!G.ok)throw new Error(`Failed to fetch credits refund requests: ${G.status}`);i=await G.json()}const w=Array.isArray(i)?i:"refundRequests"in i?i.refundRequests:i.requests||[];v(w)}catch(i){te.getLogger().error("[RefundsSection] Failed to fetch credits refunds:",i,{serverUrl:p.slice(0,20)+"...",hasApiKey:!!o}),v([]),d("Failed to load credits refunds")}finally{R(!1)}},[p,o,b,u]);r.useEffect(()=>{L()},[L]);const E=r.useCallback(async()=>{try{let i;const x=`/admin/stripe/refunds?limit=${b}`;if(u?.isAuthenticated())i=await u.fetchWithAuth(x);else{const w={"Content-Type":"application/json"};o&&(w["X-API-Key"]=o);const q=await fetch(`${p}${x}`,{headers:w});if(!q.ok)throw new Error(`Failed to fetch Stripe refunds: ${q.status}`);i=await q.json()}l(i.refunds||[])}catch(i){te.getLogger().error("[RefundsSection] Failed to fetch Stripe refunds:",i,{serverUrl:p.slice(0,20)+"...",hasApiKey:!!o}),l([]),d("Failed to load Stripe refunds")}finally{y(!1)}},[p,o,b,u]);r.useEffect(()=>{E()},[E]);const O=async i=>{j(i);try{const x=`/admin/stripe/refunds/${i}/process`;if(u?.isAuthenticated())await u.fetchWithAuth(x,{method:"POST"});else{const w={"Content-Type":"application/json"};o&&(w["X-API-Key"]=o);const q=await fetch(`${p}${x}`,{method:"POST",headers:w});if(!q.ok)throw new Error(`Failed to process refund: ${q.status}`)}await E()}catch(x){te.getLogger().error("[RefundsSection] Failed to process Stripe refund:",x,{serverUrl:p.slice(0,20)+"...",hasApiKey:!!o,refundId:i}),d("Failed to process Stripe refund")}finally{j(null)}},F=(i,x)=>new Intl.NumberFormat("en-US",{style:"currency",currency:x}).format(i/100),H=i=>i?i.replace(/_/g," ").replace(/\b\w/g,x=>x.toUpperCase()):"—",le=i=>{switch(i){case"processed":return"success";case"pending":return"pending";case"rejected":default:return"muted"}},ae=(i,x)=>x?x.toLowerCase()==="usd"?`${new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(i/1e6)} (USD credits)`:`${i.toLocaleString()} ${x.toUpperCase()} (atomic)`:`${i.toLocaleString()} (atomic)`,Z=i=>{switch(i){case"succeeded":return"success";case"failed":return"failed";case"pending":case"requires_action":return"pending";case"canceled":default:return"muted"}},ue=i=>i.stripeRefundId??"—",me=i=>i.chargeId??"—",se=a.filter(i=>i.status==="pending"||i.status==="requires_action").length,ie=k.filter(i=>i.status==="pending").length,ee=g.filter(i=>i.status==="pending").length,K=se+ie+ee,Y=a.filter(i=>i.status==="succeeded").reduce((i,x)=>i+x.amount,0),he=k.filter(i=>i.status==="processed").reduce((i,x)=>i+x.amountLamports,0),t=g.filter(i=>i.status==="completed").reduce((i,x)=>i+x.amount,0),n=Y/100+he/1e6+t,P=i=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(i),W=C||S||N,B=i=>{h(x=>!x||x.key!==i?{key:i,direction:"asc"}:{key:i,direction:x.direction==="asc"?"desc":"asc"})},z=i=>{c(x=>!x||x.key!==i?{key:i,direction:"asc"}:{key:i,direction:x.direction==="asc"?"desc":"asc"})},X=i=>{V(x=>!x||x.key!==i?{key:i,direction:"asc"}:{key:i,direction:x.direction==="asc"?"desc":"asc"})},U=(i,x)=>!i||!x?e.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:$.Icons.chevronUp}):e.jsx("span",{className:"cedros-admin__sort-icon",children:x==="asc"?$.Icons.chevronUp:$.Icons.chevronDown}),J=r.useMemo(()=>{if(!s)return a;const i=s.direction==="asc"?1:-1,x=w=>{switch(s.key){case"stripe":return w.stripeRefundId??"";case"charge":return w.chargeId??"";case"amount":return w.amount??0;case"reason":return w.reason??"";case"status":return w.status??"";case"date":return new Date(w.createdAt).getTime();case"id":default:return w.id}};return[...a].sort((w,q)=>{const G=x(w),Q=x(q);return typeof G=="number"&&typeof Q=="number"?(G-Q)*i:String(G).localeCompare(String(Q),void 0,{sensitivity:"base"})*i})},[a,s]),oe=r.useMemo(()=>{if(!_)return k;const i=_.direction==="asc"?1:-1,x=w=>{switch(_.key){case"original":return w.originalTransactionId??"";case"user":return w.userId??"";case"amount":return w.amountLamports??0;case"reason":return w.reason??"";case"status":return w.status??"";case"date":return new Date(w.createdAt).getTime();case"id":default:return w.id}};return[...k].sort((w,q)=>{const G=x(w),Q=x(q);return typeof G=="number"&&typeof Q=="number"?(G-Q)*i:String(G).localeCompare(String(Q),void 0,{sensitivity:"base"})*i})},[k,_]),re=r.useMemo(()=>{if(!f)return g;const i=f.direction==="asc"?1:-1,x=w=>{switch(f.key){case"transaction":return w.transactionId??"";case"amount":return w.amount??0;case"reason":return w.reason??"";case"status":return w.status??"";case"date":return new Date(w.createdAt).getTime();case"id":default:return w.id}};return[...g].sort((w,q)=>{const G=x(w),Q=x(q);return typeof G=="number"&&typeof Q=="number"?(G-Q)*i:String(G).localeCompare(String(Q),void 0,{sensitivity:"base"})*i})},[g,f]);return e.jsxs("div",{className:"cedros-admin__page",children:[e.jsx(ne.ErrorBanner,{message:I,onRetry:()=>{m(),L(),E()}}),e.jsx(ce.StatsBar,{stats:[{label:"Pending",value:K,variant:K>0?"warning":"muted"},{label:"Card Pending",value:se,description:"Stripe"},{label:"Credits Pending",value:ie},{label:"Crypto Pending",value:ee,description:"x402"},{label:"Total Refunded",value:P(n),variant:"success"}],isLoading:W}),e.jsx("div",{className:"cedros-admin__section-header",children:e.jsx("h3",{className:"cedros-admin__section-title",children:"Stripe Refund Requests"})}),C?e.jsxs("div",{className:"cedros-admin__loading",children:[$.Icons.loading," Loading Stripe refunds..."]}):a.length===0?e.jsx("div",{className:"cedros-admin__empty",children:"No Stripe refund requests found."}):e.jsx("div",{className:"cedros-admin__table-container",children:e.jsxs("table",{className:"cedros-admin__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{"aria-sort":s?.key==="id"?s?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>B("id"),children:["Request ID",U(s?.key==="id",s?.direction)]})}),e.jsx("th",{"aria-sort":s?.key==="stripe"?s?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>B("stripe"),children:["Stripe Refund ID",U(s?.key==="stripe",s?.direction)]})}),e.jsx("th",{"aria-sort":s?.key==="charge"?s?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>B("charge"),children:["Charge",U(s?.key==="charge",s?.direction)]})}),e.jsx("th",{"aria-sort":s?.key==="amount"?s?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>B("amount"),children:["Amount",U(s?.key==="amount",s?.direction)]})}),e.jsx("th",{"aria-sort":s?.key==="reason"?s?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>B("reason"),children:["Reason",U(s?.key==="reason",s?.direction)]})}),e.jsx("th",{"aria-sort":s?.key==="status"?s?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>B("status"),children:["Status",U(s?.key==="status",s?.direction)]})}),e.jsx("th",{"aria-sort":s?.key==="date"?s?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>B("date"),children:["Date",U(s?.key==="date",s?.direction)]})}),e.jsx("th",{children:"Actions"})]})}),e.jsx("tbody",{children:J.map(i=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("code",{children:i.id})}),e.jsx("td",{children:e.jsx("code",{children:ue(i)})}),e.jsx("td",{children:e.jsx("code",{children:me(i)})}),e.jsx("td",{children:F(i.amount,i.currency)}),e.jsx("td",{children:H(i.reason)}),e.jsx("td",{children:e.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${Z(i.status)}`,children:i.status})}),e.jsx("td",{children:de.formatDateTime(i.createdAt)}),e.jsx("td",{children:(i.status==="pending"||i.status==="requires_action")&&e.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",onClick:()=>O(i.id),disabled:D===i.id,children:D===i.id?"Processing...":"Process"})})]},i.id))})]})}),e.jsx("div",{className:"cedros-admin__section-header",style:{marginTop:"2rem"},children:e.jsx("h3",{className:"cedros-admin__section-title",children:"Credits Refund Requests"})}),e.jsx("p",{className:"cedros-admin__hint",style:{marginBottom:"0.75rem"},children:"Credits refund requests are read-only in this admin surface."}),S?e.jsxs("div",{className:"cedros-admin__loading",children:[$.Icons.loading," Loading credits refunds..."]}):k.length===0?e.jsx("div",{className:"cedros-admin__empty",children:"No credits refund requests found."}):e.jsx("div",{className:"cedros-admin__table-container",children:e.jsxs("table",{className:"cedros-admin__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{"aria-sort":_?.key==="id"?_?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>z("id"),children:["Request ID",U(_?.key==="id",_?.direction)]})}),e.jsx("th",{"aria-sort":_?.key==="original"?_?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>z("original"),children:["Original Tx",U(_?.key==="original",_?.direction)]})}),e.jsx("th",{"aria-sort":_?.key==="user"?_?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>z("user"),children:["User",U(_?.key==="user",_?.direction)]})}),e.jsx("th",{"aria-sort":_?.key==="amount"?_?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>z("amount"),children:["Amount",U(_?.key==="amount",_?.direction)]})}),e.jsx("th",{"aria-sort":_?.key==="reason"?_?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>z("reason"),children:["Reason",U(_?.key==="reason",_?.direction)]})}),e.jsx("th",{"aria-sort":_?.key==="status"?_?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>z("status"),children:["Status",U(_?.key==="status",_?.direction)]})}),e.jsx("th",{"aria-sort":_?.key==="date"?_?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>z("date"),children:["Date",U(_?.key==="date",_?.direction)]})})]})}),e.jsx("tbody",{children:oe.map(i=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("code",{children:i.id})}),e.jsx("td",{children:e.jsx("code",{children:i.originalTransactionId})}),e.jsx("td",{children:e.jsx("code",{children:i.userId??"—"})}),e.jsx("td",{children:ae(i.amountLamports,i.currency)}),e.jsx("td",{children:i.reason??"—"}),e.jsx("td",{children:e.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${le(i.status)}`,children:i.status})}),e.jsx("td",{children:de.formatDateTime(i.createdAt)})]},i.id))})]})}),e.jsx("div",{className:"cedros-admin__section-header",style:{marginTop:"2rem"},children:e.jsx("h3",{className:"cedros-admin__section-title",children:"x402 Refund Requests"})}),e.jsx("p",{className:"cedros-admin__hint",style:{marginBottom:"0.75rem"},children:"x402 refund approvals use the signed refund workflow, not this dashboard table."}),N?e.jsxs("div",{className:"cedros-admin__loading",children:[$.Icons.loading," Loading x402 refunds..."]}):g.length===0?e.jsx("div",{className:"cedros-admin__empty",children:"No x402 refund requests found."}):e.jsx("div",{className:"cedros-admin__table-container",children:e.jsxs("table",{className:"cedros-admin__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{"aria-sort":f?.key==="id"?f?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>X("id"),children:["ID",U(f?.key==="id",f?.direction)]})}),e.jsx("th",{"aria-sort":f?.key==="transaction"?f?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>X("transaction"),children:["Transaction",U(f?.key==="transaction",f?.direction)]})}),e.jsx("th",{"aria-sort":f?.key==="amount"?f?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>X("amount"),children:["Amount",U(f?.key==="amount",f?.direction)]})}),e.jsx("th",{"aria-sort":f?.key==="reason"?f?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>X("reason"),children:["Reason",U(f?.key==="reason",f?.direction)]})}),e.jsx("th",{"aria-sort":f?.key==="status"?f?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>X("status"),children:["Status",U(f?.key==="status",f?.direction)]})}),e.jsx("th",{"aria-sort":f?.key==="date"?f?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>X("date"),children:["Date",U(f?.key==="date",f?.direction)]})})]})}),e.jsx("tbody",{children:re.map(i=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("code",{children:i.id})}),e.jsx("td",{children:e.jsx("code",{children:i.transactionId})}),e.jsxs("td",{children:["$",i.amount.toFixed(2)]}),e.jsx("td",{children:i.reason||"—"}),e.jsx("td",{children:e.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${i.status}`,children:i.status})}),e.jsx("td",{children:de.formatDateTime(i.createdAt)})]},i.id))})]})})]})}const Ie=r.lazy(()=>Promise.resolve().then(()=>require("./SettingsSection-Cz2Yjdhr.js")).then(p=>({default:p.SettingsSection})));function Pe(p){return e.jsx(r.Suspense,{fallback:null,children:e.jsx(Ie,{...p})})}exports.CouponsSection=we;exports.ProductsSection=ke;exports.RefundsSection=Ae;exports.SettingsSection=Pe;exports.TransactionsSection=Se;
@@ -1,40 +0,0 @@
1
- /** Available dashboard sections */
2
- export type DashboardSection = 'products' | 'subscriptions' | 'transactions' | 'orders' | 'coupons' | 'refunds' | 'storefront' | 'ai-settings' | 'faqs' | 'payment-settings' | 'messaging' | 'token22' | 'compliance' | 'chat-logs' | 'customers' | 'disputes' | 'webhooks' | 'shipping' | 'tax' | 'returns' | 'images' | 'inventory' | 'settings';
3
- /** Theme mode for the dashboard */
4
- export type AdminThemeMode = 'light' | 'dark' | 'system';
5
- export interface CedrosPayAdminDashboardProps {
6
- /** Backend server URL */
7
- serverUrl: string;
8
- /** @deprecated Use wallet connection or cedrosLoginToken instead */
9
- apiKey?: string;
10
- /** Dashboard title */
11
- title?: string;
12
- /** Sections to display (defaults to all) */
13
- sections?: DashboardSection[];
14
- /** Initial active section */
15
- defaultSection?: DashboardSection;
16
- /**
17
- * @deprecated Stats are now embedded in individual sections
18
- * Auto-refresh interval for stats in ms (0 to disable)
19
- */
20
- refreshInterval?: number;
21
- /** Items per page for lists */
22
- pageSize?: number;
23
- /** Callback when section changes */
24
- onSectionChange?: (section: DashboardSection) => void;
25
- /** Additional CSS class */
26
- className?: string;
27
- /** JWT token from cedros-login for admin authentication */
28
- cedrosLoginToken?: string;
29
- /** Whether the cedros-login user is an admin (required if using cedrosLoginToken) */
30
- isAdmin?: boolean;
31
- /**
32
- * Theme mode: 'light', 'dark', or 'system' (default: 'system')
33
- * - If inside CedrosProvider: 'system' follows provider theme, explicit values override
34
- * - If outside CedrosProvider: 'system' follows OS preference
35
- */
36
- theme?: AdminThemeMode;
37
- }
38
- export declare function CedrosPayAdminDashboard({ serverUrl, apiKey, title, sections, defaultSection, refreshInterval: _refreshInterval, pageSize, onSectionChange, className, cedrosLoginToken, isAdmin, theme, }: CedrosPayAdminDashboardProps): import("react/jsx-runtime").JSX.Element;
39
- export default CedrosPayAdminDashboard;
40
- //# sourceMappingURL=CedrosPayAdminDashboard.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"CedrosPayAdminDashboard.d.ts","sourceRoot":"","sources":["../../../../src/components/admin/CedrosPayAdminDashboard.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAcH,OAAO,+BAA+B,CAAC;AAyDvC,mCAAmC;AACnC,MAAM,MAAM,gBAAgB,GACxB,UAAU,GACV,eAAe,GACf,cAAc,GACd,QAAQ,GACR,SAAS,GACT,SAAS,GACT,YAAY,GACZ,aAAa,GACb,MAAM,GACN,kBAAkB,GAClB,WAAW,GACX,SAAS,GACT,YAAY,GACZ,WAAW,GACX,WAAW,GACX,UAAU,GACV,UAAU,GACV,UAAU,GACV,KAAK,GACL,SAAS,GACT,QAAQ,GACR,WAAW,GACX,UAAU,CAAC;AAEf,mCAAmC;AACnC,MAAM,MAAM,cAAc,GAAG,OAAO,GAAG,MAAM,GAAG,QAAQ,CAAC;AAEzD,MAAM,WAAW,4BAA4B;IAC3C,yBAAyB;IACzB,SAAS,EAAE,MAAM,CAAC;IAClB,oEAAoE;IACpE,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,sBAAsB;IACtB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,4CAA4C;IAC5C,QAAQ,CAAC,EAAE,gBAAgB,EAAE,CAAC;IAC9B,6BAA6B;IAC7B,cAAc,CAAC,EAAE,gBAAgB,CAAC;IAClC;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,+BAA+B;IAC/B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,oCAAoC;IACpC,eAAe,CAAC,EAAE,CAAC,OAAO,EAAE,gBAAgB,KAAK,IAAI,CAAC;IACtD,2BAA2B;IAC3B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,2DAA2D;IAC3D,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,qFAAqF;IACrF,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB;;;;OAIG;IACH,KAAK,CAAC,EAAE,cAAc,CAAC;CACxB;AA2JD,wBAAgB,uBAAuB,CAAC,EACtC,SAAS,EACT,MAAM,EACN,KAAoB,EACpB,QAA0K,EAC1K,cAA+B,EAC/B,eAAe,EAAE,gBAAwB,EACzC,QAAa,EACb,eAAe,EACf,SAAc,EACd,gBAAgB,EAChB,OAAe,EACf,KAAgB,GACjB,EAAE,4BAA4B,2CAwI9B;AAED,eAAe,uBAAuB,CAAC"}
@@ -1,4 +0,0 @@
1
- import { CedrosPayAdminDashboardProps } from './CedrosPayAdminDashboard';
2
- export type { CedrosPayAdminDashboardProps, DashboardSection, } from './CedrosPayAdminDashboard';
3
- export declare function CedrosPayAdminDashboard(props: CedrosPayAdminDashboardProps): import("react/jsx-runtime").JSX.Element;
4
- //# sourceMappingURL=LazyCedrosPayAdminDashboard.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"LazyCedrosPayAdminDashboard.d.ts","sourceRoot":"","sources":["../../../../src/components/admin/LazyCedrosPayAdminDashboard.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,2BAA2B,CAAC;AAO9E,YAAY,EACV,4BAA4B,EAC5B,gBAAgB,GACjB,MAAM,2BAA2B,CAAC;AAEnC,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,4BAA4B,2CAM1E"}
@@ -1 +0,0 @@
1
- "use strict";var ze=Object.create;var Ce=Object.defineProperty;var Ue=Object.getOwnPropertyDescriptor;var Oe=Object.getOwnPropertyNames;var Fe=Object.getPrototypeOf,We=Object.prototype.hasOwnProperty;var He=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Oe(t))!We.call(e,n)&&n!==r&&Ce(e,n,{get:()=>t[n],enumerable:!(s=Ue(t,n))||s.enumerable});return e};var Ye=(e,t,r)=>(r=e!=null?ze(Fe(e)):{},He(t||!e||!e.__esModule?Ce(r,"default",{value:e,enumerable:!0}):r,e));const z=require("./CedrosContext-CCakH2SZ.js"),i=require("react/jsx-runtime"),f=require("react"),q=require("./fetchWithTimeout-CG0EKbhf.js"),H=require("./ThemeContext-CFXyYx7A.js");function Qe(e){return!e||!e.coupon_codes?[]:e.coupon_codes.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function Ve(e,t=", "){return e.join(t)}function Ge(e,t){return e<=0?0:(e-t)/e*100}function Ke(e,t){if(!t||t.length===0)return e;let r=e,s=0;for(const n of t)if(n.discountType==="percentage"){const u=1-n.discountValue/100;r=r*u}else n.discountType==="fixed"&&(s+=n.discountValue);return r=r-s,r<0&&(r=0),Math.ceil(r*100)/100}function we(e){const t=Number(e);if(!Number.isFinite(t)||t<=0)return 1;const r=Math.floor(t);return r>0?r:1}function ce(e){return e.map(t=>({resource:t.resource,quantity:we(t.quantity),variantId:t.variantId,metadata:t.metadata}))}function re(e){return e.reduce((t,r)=>t+we(r.quantity),0)}function Xe(e){return!!(e&&e.length>0&&(e.length>1||e.length===1&&(e[0].quantity??1)>1))}const X=new Map,de=new Map,Q=new Map,le=1e3,Se=200,pe=2e3;function Je(e){const t=Q.get(e);return t?Date.now()<t?!0:(Q.delete(e),!1):!1}function Ze(e,t=Se){const r=Date.now()+t;if(Q.set(e,r),Q.size>le){const s=Array.from(Q.keys()).slice(0,Q.size-le);for(const n of s)Q.delete(n)}}function et(e,t=pe){const r=X.get(e);if(!r)return!1;const n=Date.now()-r;return n<t?(q.getLogger().debug(`[Deduplication] Duplicate request blocked: ${e} (${n}ms ago)`),!0):!1}function tt(e){if(X.set(e,Date.now()),X.size>le){const t=Array.from(X.keys()).slice(0,X.size-le);for(const r of t)X.delete(r)}}function rt(e){return de.get(e)||null}function st(e,t){de.set(e,t);const r=()=>{de.delete(e),tt(e)};return t.then(r,r),t}async function nt(e,t,r={}){const{windowMs:s=pe,throwOnDuplicate:n=!0}=r,u=rt(e);if(u)return q.getLogger().debug(`[Deduplication] Reusing in-flight request: ${e}`),u;if(et(e,s)){if(n)throw new Error(`Duplicate request blocked: ${e}`);q.getLogger().warn(`[Deduplication] Duplicate request blocked but not throwing: ${e}`);return}const h=t();return st(e,h)}function J(e,t,r={}){const{cooldownMs:s=Se,deduplicationWindowMs:n=pe}=r;return async()=>{if(Je(e)){q.getLogger().debug(`[Deduplication] Button in cooldown: ${e}`);return}Ze(e,s);try{await nt(e,async()=>{const u=t();u instanceof Promise&&await u},{windowMs:n,throwOnDuplicate:!1})}catch(u){if(u instanceof Error&&u.message.includes("Duplicate request"))return;throw u}}}function Pe(e){return{background:"none",border:"none",fontSize:"1.5rem",cursor:"pointer",color:e,opacity:.6,padding:"0.25rem",lineHeight:1}}const Y={PAYMENT_START:"cedros:payment:start",WALLET_CONNECT:"cedros:wallet:connect",WALLET_CONNECTED:"cedros:wallet:connected",WALLET_ERROR:"cedros:wallet:error",PAYMENT_PROCESSING:"cedros:payment:processing",PAYMENT_SUCCESS:"cedros:payment:success",PAYMENT_ERROR:"cedros:payment:error"};function G(e,t){if(typeof window>"u")return;const r=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!1});window.dispatchEvent(r)}function Z(e,t,r){G(Y.PAYMENT_START,{timestamp:Date.now(),method:e,resource:t,itemCount:r})}function ot(e){G(Y.WALLET_CONNECT,{timestamp:Date.now(),wallet:e})}function it(e,t){G(Y.WALLET_CONNECTED,{timestamp:Date.now(),wallet:e,publicKey:t})}function at(e,t){G(Y.WALLET_ERROR,{timestamp:Date.now(),wallet:t,error:e})}function ee(e,t,r){G(Y.PAYMENT_PROCESSING,{timestamp:Date.now(),method:e,resource:t,itemCount:r})}function te(e,t,r,s){G(Y.PAYMENT_SUCCESS,{timestamp:Date.now(),method:e,transactionId:t,resource:r,itemCount:s})}function W(e,t,r,s){G(Y.PAYMENT_ERROR,{timestamp:Date.now(),method:e,error:t,resource:r,itemCount:s})}function ct(e){return e instanceof z.PaymentError&&e.canRetry()}function lt(e){return e instanceof z.PaymentError?e.getUserMessage():e instanceof Error?e.message:String(e)}function ut(e){switch(e){case"mainnet-beta":return"https://api.mainnet-beta.solana.com";case"devnet":return"https://api.devnet.solana.com";case"testnet":return"https://api.testnet.solana.com";default:return"https://api.mainnet-beta.solana.com"}}function dt(e){try{const t=new URL(e);return`${t.protocol}//${t.host}`}catch{return e}}function ve(e={}){const{solanaCluster:t="mainnet-beta",solanaEndpoint:r,customRpcProviders:s=[],allowUnsafeScripts:n=!1,additionalScriptSrc:u=[],additionalConnectSrc:h=[],additionalFrameSrc:x=[],includeStripe:C=!0,includeSolana:l=!0}=e;n&&console.warn("[CedrosPay] SECURITY WARNING: allowUnsafeScripts is enabled. This adds 'unsafe-inline' and 'unsafe-eval' to script-src, which significantly weakens CSP protection against XSS attacks. Only use this in development or if absolutely required by your framework.");const a=["'self'"];n&&a.push("'unsafe-inline'","'unsafe-eval'"),C&&a.push("https://js.stripe.com"),a.push(...u);const o=["'self'"];if(C&&o.push("https://api.stripe.com","https://*.stripe.com"),l){const p=ut(t);if(o.push(p),r){const c=dt(r);o.includes(c)||o.push(c)}s.forEach(c=>{o.includes(c)||o.push(c)})}o.push(...h);const d=["'self'"];return C&&d.push("https://js.stripe.com","https://checkout.stripe.com"),d.push(...x),{scriptSrc:a,connectSrc:o,frameSrc:d}}function je(e,t="header"){const{scriptSrc:r,connectSrc:s,frameSrc:n}=e;switch(t){case"header":case"meta":case"nextjs":case"nginx":{const u=[];return r.length>0&&u.push(`script-src ${r.join(" ")}`),s.length>0&&u.push(`connect-src ${s.join(" ")}`),n.length>0&&u.push(`frame-src ${n.join(" ")}`),u.join("; ")}case"helmet":{const u={};return r.length>0&&(u.scriptSrc=r),s.length>0&&(u.connectSrc=s),n.length>0&&(u.frameSrc=n),u}case"directives":return{scriptSrc:r,connectSrc:s,frameSrc:n};default:throw new Error(`Unknown CSP format: ${t}`)}}function pt(e={},t="header"){const r=ve(e);return je(r,t)}const ft={HELIUS:"https://*.helius-rpc.com",QUICKNODE:"https://*.quicknode.pro",ALCHEMY:"https://*.alchemy.com",ANKR:"https://rpc.ankr.com",TRITON:"https://*.rpcpool.com"},mt={MAINNET_CUSTOM_RPC:e=>({solanaCluster:"mainnet-beta",solanaEndpoint:e,allowUnsafeScripts:!1}),MAINNET_NEXTJS:e=>({solanaCluster:"mainnet-beta",solanaEndpoint:e,allowUnsafeScripts:!1}),DEVNET:()=>({solanaCluster:"devnet",allowUnsafeScripts:!1}),CRYPTO_ONLY:e=>({solanaCluster:"mainnet-beta",solanaEndpoint:e,includeStripe:!1}),STRIPE_ONLY:()=>({includeStripe:!0,includeSolana:!1})};function fe(){const{stripeManager:e}=z.useCedrosContext(),[t,r]=f.useState({status:"idle",error:null,transactionId:null}),s=f.useRef(!1),n=f.useCallback(async(x,C,l,a,o,d)=>{if(s.current)return{success:!1,error:"Payment already in progress"};s.current=!0,r({status:"loading",error:null,transactionId:null});const p={resource:x,successUrl:C,cancelUrl:l,metadata:a,customerEmail:o,couponCode:d};try{const c=await e.processPayment(p);return r({status:c.success?"success":"error",error:c.success?null:c.error||"Payment failed",transactionId:c.success&&c.transactionId||null}),c}catch(c){const m=c instanceof Error?c.message:"Payment failed";return r({status:"error",error:m,transactionId:null}),{success:!1,error:m}}finally{s.current=!1}},[e]),u=f.useCallback(async(x,C,l,a,o,d,p,c,m,g,y,b,M)=>{if(s.current)return{success:!1,error:"Payment already in progress"};s.current=!0,r({status:"loading",error:null,transactionId:null});const S=ce(x);try{const P=await e.processCartCheckout({items:S,successUrl:C,cancelUrl:l,metadata:a,customerEmail:o,customerName:p,customerPhone:c,shippingAddress:m,billingAddress:g,couponCode:d,tipAmount:y,shippingMethodId:b,paymentMethodId:M});return r({status:P.success?"success":"error",error:P.success?null:P.error||"Cart checkout failed",transactionId:P.success&&P.transactionId||null}),P}catch(P){const _=P instanceof Error?P.message:"Cart checkout failed";return r({status:"error",error:_,transactionId:null}),{success:!1,error:_}}finally{s.current=!1}},[e]),h=f.useCallback(()=>{r({status:"idle",error:null,transactionId:null}),s.current=!1},[]);return{...t,processPayment:n,processCartCheckout:u,reset:h}}function se(e,t){return f.useMemo(()=>{const r=Xe(t),s=e||(t?.length===1?t[0].resource:"");return{isCartMode:r,effectiveResource:s}},[e,t])}const gt=(e,t,r)=>{const s=e[t];return s?typeof s=="function"?s():Promise.resolve(s):new Promise((n,u)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(u.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==r?". Note that variables only represent file names one level deep.":""))))})},ue=new Map;let ae=null;async function xe(e){if(ue.has(e))return ue.get(e);try{const t=await gt(Object.assign({"./translations/ar.json":()=>Promise.resolve().then(()=>require("./ar-LVoQZTFI.js")),"./translations/bn.json":()=>Promise.resolve().then(()=>require("./bn-BR5Cv1T4.js")),"./translations/de.json":()=>Promise.resolve().then(()=>require("./de-pQxy-oD1.js")),"./translations/en.json":()=>Promise.resolve().then(()=>require("./en-Yikrt96u.js")),"./translations/es.json":()=>Promise.resolve().then(()=>require("./es-D24cg8dD.js")),"./translations/fil.json":()=>Promise.resolve().then(()=>require("./fil-BOBft9G-.js")),"./translations/fr.json":()=>Promise.resolve().then(()=>require("./fr-Ct9ub8Fa.js")),"./translations/he.json":()=>Promise.resolve().then(()=>require("./he-DtQqRKRq.js")),"./translations/id.json":()=>Promise.resolve().then(()=>require("./id-CiM2mL7C.js")),"./translations/in.json":()=>Promise.resolve().then(()=>require("./in-Bzcjmxcc.js")),"./translations/it.json":()=>Promise.resolve().then(()=>require("./it-Blb_pIJl.js")),"./translations/jp.json":()=>Promise.resolve().then(()=>require("./jp-9NHyIuwY.js")),"./translations/kr.json":()=>Promise.resolve().then(()=>require("./kr-DvzJ-0yX.js")),"./translations/ms.json":()=>Promise.resolve().then(()=>require("./ms-BOAu5pUB.js")),"./translations/nl.json":()=>Promise.resolve().then(()=>require("./nl-WHh_DfO8.js")),"./translations/pa.json":()=>Promise.resolve().then(()=>require("./pa-B7kIhZCF.js")),"./translations/pl.json":()=>Promise.resolve().then(()=>require("./pl-H0hBKdvF.js")),"./translations/pt.json":()=>Promise.resolve().then(()=>require("./pt-DwGrViQ3.js")),"./translations/ru.json":()=>Promise.resolve().then(()=>require("./ru-CB2m0UDT.js")),"./translations/ta.json":()=>Promise.resolve().then(()=>require("./ta-CAS197uN.js")),"./translations/th.json":()=>Promise.resolve().then(()=>require("./th-Cpz2cFcg.js")),"./translations/tr.json":()=>Promise.resolve().then(()=>require("./tr-hQrEFk86.js")),"./translations/uk.json":()=>Promise.resolve().then(()=>require("./uk-DrK2Sv8C.js")),"./translations/ur.json":()=>Promise.resolve().then(()=>require("./ur-D5-7mN9a.js")),"./translations/vn.json":()=>Promise.resolve().then(()=>require("./vn-B_iut9YL.js")),"./translations/zh.json":()=>Promise.resolve().then(()=>require("./zh-PR82dCHr.js"))}),`./translations/${e}.json`,3),r=t.default||t;return ue.set(e,r),r}catch{return null}}async function ht(){if(ae)return ae;const e=Object.assign({"./translations/ar.json":()=>Promise.resolve().then(()=>require("./ar-LVoQZTFI.js")),"./translations/bn.json":()=>Promise.resolve().then(()=>require("./bn-BR5Cv1T4.js")),"./translations/de.json":()=>Promise.resolve().then(()=>require("./de-pQxy-oD1.js")),"./translations/en.json":()=>Promise.resolve().then(()=>require("./en-Yikrt96u.js")),"./translations/es.json":()=>Promise.resolve().then(()=>require("./es-D24cg8dD.js")),"./translations/fil.json":()=>Promise.resolve().then(()=>require("./fil-BOBft9G-.js")),"./translations/fr.json":()=>Promise.resolve().then(()=>require("./fr-Ct9ub8Fa.js")),"./translations/he.json":()=>Promise.resolve().then(()=>require("./he-DtQqRKRq.js")),"./translations/id.json":()=>Promise.resolve().then(()=>require("./id-CiM2mL7C.js")),"./translations/in.json":()=>Promise.resolve().then(()=>require("./in-Bzcjmxcc.js")),"./translations/it.json":()=>Promise.resolve().then(()=>require("./it-Blb_pIJl.js")),"./translations/jp.json":()=>Promise.resolve().then(()=>require("./jp-9NHyIuwY.js")),"./translations/kr.json":()=>Promise.resolve().then(()=>require("./kr-DvzJ-0yX.js")),"./translations/ms.json":()=>Promise.resolve().then(()=>require("./ms-BOAu5pUB.js")),"./translations/nl.json":()=>Promise.resolve().then(()=>require("./nl-WHh_DfO8.js")),"./translations/pa.json":()=>Promise.resolve().then(()=>require("./pa-B7kIhZCF.js")),"./translations/pl.json":()=>Promise.resolve().then(()=>require("./pl-H0hBKdvF.js")),"./translations/pt.json":()=>Promise.resolve().then(()=>require("./pt-DwGrViQ3.js")),"./translations/ru.json":()=>Promise.resolve().then(()=>require("./ru-CB2m0UDT.js")),"./translations/ta.json":()=>Promise.resolve().then(()=>require("./ta-CAS197uN.js")),"./translations/th.json":()=>Promise.resolve().then(()=>require("./th-Cpz2cFcg.js")),"./translations/tr.json":()=>Promise.resolve().then(()=>require("./tr-hQrEFk86.js")),"./translations/uk.json":()=>Promise.resolve().then(()=>require("./uk-DrK2Sv8C.js")),"./translations/ur.json":()=>Promise.resolve().then(()=>require("./ur-D5-7mN9a.js")),"./translations/vn.json":()=>Promise.resolve().then(()=>require("./vn-B_iut9YL.js")),"./translations/zh.json":()=>Promise.resolve().then(()=>require("./zh-PR82dCHr.js"))}),t=[];for(const r in e){const s=r.match(/\.\/translations\/([a-z]{2,3}(?:-[A-Z]{2})?)\.json$/);s&&t.push(s[1])}return ae=t.length>0?t:["en"],ae}function ke(){return typeof navigator>"u"?"en":(navigator.language||navigator.userLanguage||"en").split("-")[0].toLowerCase()}async function Ee(e){let t=await xe(e);if(t||(t=await xe("en"),t))return t;throw new Error("Critical: No translation files found, not even en.json")}function Me(e){return(t,r)=>{const s=t.split(".");let n=e;for(const u of s)if(n&&typeof n=="object"&&u in n)n=n[u];else return t;return typeof n!="string"?t:r?Object.entries(r).reduce((u,[h,x])=>u.replace(new RegExp(`\\{${h}\\}`,"g"),x),n):n}}function yt(e,t,r=!0){const s=t.errors[e];if(!s){const n=z.getUserFriendlyError(e);return r&&n.action?`${n.message} ${n.action}`:n.message}return r&&s.action?`${s.message} ${s.action}`:s.message}function K(e){const[t,r]=f.useState(null),[s,n]=f.useState(!0),u=f.useMemo(()=>e||ke(),[e]);return f.useEffect(()=>{let x=!1;return(async()=>{n(!0);try{const l=await Ee(u);x||(r(l),n(!1))}catch(l){console.error("[CedrosPay] Failed to load translations:",l),x||n(!1)}})(),()=>{x=!0}},[u]),{t:f.useMemo(()=>t?Me(t):x=>({"ui.purchase":"Purchase","ui.pay_with_card":"Pay with Card","ui.pay_with_crypto":"Pay with USDC","ui.pay_with_usdc":"Pay with USDC","ui.card":"Card","ui.usdc_solana":"USDC (Solana)","ui.crypto":"Crypto","ui.processing":"Processing...","ui.loading":"Loading...","ui.connect_wallet":"Connect Wallet","ui.connecting":"Connecting..."})[x]||x,[t]),locale:u,isLoading:s,translations:t}}function bt(e,t=!0){const{translations:r}=K();if(!r){const n=z.getUserFriendlyError(e);return t&&n.action?`${n.message} ${n.action}`:n.message}const s=r.errors[e];if(!s){const n=z.getUserFriendlyError(e);return t&&n.action?`${n.message} ${n.action}`:n.message}return t&&s.action?`${s.message} ${s.action}`:s.message}function me({resource:e,items:t,successUrl:r,cancelUrl:s,metadata:n,customerEmail:u,couponCode:h,label:x,disabled:C=!1,onAttempt:l,onSuccess:a,onError:o,className:d=""}){const{status:p,error:c,transactionId:m,processPayment:g,processCartCheckout:y}=fe(),b=H.useCedrosTheme(),{isCartMode:M,effectiveResource:S}=se(e,t),{t:P,translations:_}=K(),B=x||P("ui.pay_with_card"),A=b.unstyled?d:`${b.className} cedros-theme__stripe-button ${d}`.trim(),$=c&&typeof c!="string"?c?.code??null:null,w=c?typeof c=="string"?c:(v=>{if(!v||!_)return"";const E=_.errors[v];return E?E.action?`${E.message} ${E.action}`:E.message:""})($):null,j=f.useCallback(async()=>{q.getLogger().debug("[StripeButton] executePayment with couponCode:",h);const v=M&&t?re(t):void 0;if(Z("stripe",S,v),l&&l("stripe"),!M&&!S){const O="Invalid payment configuration: missing resource or items";q.getLogger().error("[StripeButton]",O),W("stripe",O,S,v),o&&o(O);return}let E;ee("stripe",S,v),M&&t?(q.getLogger().debug("[StripeButton] Processing cart checkout with coupon:",h),E=await y(t,r,s,n,u,h)):S&&(q.getLogger().debug("[StripeButton] Processing single payment with coupon:",h),E=await g(S,r,s,n,u,h)),E&&E.success&&E.transactionId?(te("stripe",E.transactionId,S,v),a&&a(E.transactionId)):E&&!E.success&&E.error&&(W("stripe",E.error,S,v),o&&o(E.error))},[h,M,S,t,r,s,n,u,y,g,l,a,o]),D=f.useMemo(()=>M&&t?`stripe-cart-${t.map(v=>v.resource).join("-")}`:`stripe-${S||"unknown"}`,[M,t,S]),k=f.useMemo(()=>J(D,j),[D,j]),T=p==="loading",R=C||T;return i.jsxs("div",{className:A,style:b.unstyled?{}:b.style,children:[i.jsx("button",{onClick:k,disabled:R,className:b.unstyled?d:"cedros-theme__button cedros-theme__stripe",type:"button",children:T?P("ui.processing"):B}),w&&i.jsx("div",{className:b.unstyled?"":"cedros-theme__error",children:w}),m&&i.jsx("div",{className:b.unstyled?"":"cedros-theme__success",children:P("ui.payment_successful")})]})}function Re(){const{creditsManager:e}=z.useCedrosContext(),[t,r]=f.useState({status:"idle",error:null,transactionId:null,requirement:null,holdId:null}),s=f.useRef(!1),n=f.useCallback(async(l,a)=>{r(o=>({...o,status:"loading",error:null}));try{const o=await e.requestQuote(l,a);return r(d=>({...d,status:"idle",requirement:o})),o}catch(o){const d=o instanceof Error?o.message:"Failed to fetch credits quote";return r(p=>({...p,status:"error",error:d})),null}},[e]),u=f.useCallback(async(l,a)=>{r(o=>({...o,status:"loading",error:null}));try{const o=ce(l),d=await e.requestCartQuote(o,a);return r(p=>({...p,status:"idle"})),d}catch(o){const d=o instanceof Error?o.message:"Failed to fetch cart credits quote";return r(p=>({...p,status:"error",error:d})),null}},[e]),h=f.useCallback(async(l,a,o,d)=>{if(s.current)return{success:!1,error:"Payment already in progress"};s.current=!0,r({status:"loading",error:null,transactionId:null,requirement:null,holdId:null});try{const p=await e.processPayment(l,a,o,d);return r({status:p.success?"success":"error",error:p.success?null:p.error||"Credits payment failed",transactionId:p.success&&p.transactionId||null,requirement:null,holdId:null}),p}catch(p){const c=p instanceof Error?p.message:"Credits payment failed";return r({status:"error",error:c,transactionId:null,requirement:null,holdId:null}),{success:!1,error:c}}finally{s.current=!1}},[e]),x=f.useCallback(async(l,a,o,d)=>{if(s.current)return{success:!1,error:"Payment already in progress"};s.current=!0,r({status:"loading",error:null,transactionId:null,requirement:null,holdId:null});let p=null;try{const c=ce(l),m=await e.requestCartQuote(c,o);if(!m)return r({status:"error",error:"Credits payment not available for this cart",transactionId:null,requirement:null,holdId:null}),{success:!1,error:"Credits payment not available"};p=(await e.createCartHold({cartId:m.cartId,authToken:a})).holdId,r(b=>({...b,holdId:p}));const y=await e.authorizeCartPayment({cartId:m.cartId,holdId:p,authToken:a,metadata:d});if(!y.success&&p)try{await e.releaseHold(p,a)}catch(b){q.getLogger().warn("[useCreditsPayment] Hold release failed, will expire server-side",{holdId:p,error:b instanceof Error?b.message:String(b)})}return r({status:y.success?"success":"error",error:y.success?null:y.error||"Cart credits payment failed",transactionId:y.success&&y.transactionId||null,requirement:null,holdId:null}),{success:y.success,transactionId:y.transactionId,error:y.error}}catch(c){const m=c instanceof Error?c.message:"Cart credits payment failed";if(p)try{await e.releaseHold(p,a)}catch(g){q.getLogger().warn("[useCreditsPayment] Hold release failed, will expire server-side",{holdId:p,error:g instanceof Error?g.message:String(g)})}return r({status:"error",error:m,transactionId:null,requirement:null,holdId:null}),{success:!1,error:m}}finally{s.current=!1}},[e]),C=f.useCallback(()=>{r({status:"idle",error:null,transactionId:null,requirement:null,holdId:null}),s.current=!1},[]);return{...t,fetchQuote:n,fetchCartQuote:u,processPayment:h,processCartPayment:x,reset:C}}function ge({resource:e,items:t,authToken:r,metadata:s,couponCode:n,label:u,disabled:h=!1,onAttempt:x,onSuccess:C,onError:l,className:a=""}){const{status:o,error:d,transactionId:p,processPayment:c,processCartPayment:m}=Re(),g=H.useCedrosTheme(),{isCartMode:y,effectiveResource:b}=se(e,t),{t:M,translations:S}=K(),P=u||M("ui.pay_with_credits")||"Pay with Credits",_=g.unstyled?a:`${g.className} cedros-theme__credits-button ${a}`.trim(),B=d&&typeof d!="string"?d?.code??null:null,$=d?typeof d=="string"?d:(T=>{if(!T||!S)return"";const R=S.errors[T];return R?R.action?`${R.message} ${R.action}`:R.message:""})(B):null,I=f.useCallback(async()=>{q.getLogger().debug("[CreditsButton] executePayment");const T=y&&t?re(t):void 0;if(Z("credits",b,T),x&&x("credits"),!r){const v="Authentication required: please log in to pay with credits";q.getLogger().error("[CreditsButton]",v),W("credits",v,b,T),l&&l(v);return}if(!y&&!b){const v="Invalid payment configuration: missing resource";q.getLogger().error("[CreditsButton]",v),W("credits",v,b,T),l&&l(v);return}let R;ee("credits",b,T),y&&t?(q.getLogger().debug("[CreditsButton] Processing cart checkout"),R=await m(t,r,n,s)):b&&(q.getLogger().debug("[CreditsButton] Processing single payment"),R=await c(b,r,n,s)),R&&R.success&&R.transactionId?(te("credits",R.transactionId,b,T),C&&C(R.transactionId)):R&&!R.success&&R.error&&(W("credits",R.error,b,T),l&&l(R.error))},[r,y,b,t,n,s,c,m,x,C,l]),w=f.useMemo(()=>y&&t?`credits-cart-${t.map(T=>T.resource).join("-")}`:`credits-${b||"unknown"}`,[y,t,b]),j=f.useMemo(()=>J(w,I),[w,I]),D=o==="loading",k=h||D;return i.jsxs("div",{className:_,style:g.unstyled?{}:g.style,children:[i.jsx("button",{onClick:j,disabled:k,className:g.unstyled?a:"cedros-theme__button cedros-theme__credits",type:"button",children:D?M("ui.processing"):P}),$&&i.jsx("div",{className:g.unstyled?"":"cedros-theme__error",children:$}),p&&i.jsx("div",{className:g.unstyled?"":"cedros-theme__success",children:M("ui.payment_successful")})]})}const Ct=f.lazy(()=>Promise.resolve().then(()=>require("./CryptoButton-DxFCYDlJ.js")).then(e=>e.CryptoButton$1).then(e=>({default:e.CryptoButton}))),Te=({isOpen:e,onClose:t,resource:r,items:s,cardLabel:n="Card",cryptoLabel:u="USDC (Solana)",creditsLabel:h="Pay with Credits",showCard:x=!0,showCrypto:C=!0,showCredits:l=!1,onPaymentAttempt:a,onPaymentSuccess:o,onPaymentError:d,onStripeSuccess:p,onCryptoSuccess:c,onCreditsSuccess:m,onStripeError:g,onCryptoError:y,onCreditsError:b,customerEmail:M,successUrl:S,cancelUrl:P,metadata:_,couponCode:B,authToken:A,testPageUrl:$,hideMessages:I=!1})=>{const{tokens:w}=H.useCedrosTheme();return f.useEffect(()=>{const j=D=>{D.key==="Escape"&&e&&t()};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[e,t]),f.useEffect(()=>{if(e){const j=window.scrollY;return document.body.style.position="fixed",document.body.style.top=`-${j}px`,document.body.style.width="100%",document.body.style.overflowY="scroll",()=>{const D=document.body.style.top?Math.abs(parseInt(document.body.style.top.replace("px",""),10)):0;document.body.style.position="",document.body.style.top="",document.body.style.width="",document.body.style.overflowY="",window.scrollTo(0,D)}}},[e]),e?i.jsx("div",{className:"cedros-modal-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:w.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999,padding:"1rem"},onClick:t,children:i.jsxs("div",{className:"cedros-modal-content",style:{backgroundColor:w.modalBackground,borderRadius:"12px",padding:"2rem",maxWidth:"400px",width:"100%",boxShadow:"0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)",border:`1px solid ${w.modalBorder}`},onClick:j=>j.stopPropagation(),children:[i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},children:[i.jsx("h3",{style:{margin:0,fontSize:"1.25rem",fontWeight:600,color:w.surfaceText},children:"Choose Payment Method"}),i.jsx("button",{type:"button",onClick:t,style:Pe(w.surfaceText),"aria-label":"Close modal",children:"×"})]}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[x&&i.jsx(me,{resource:r,items:s,label:n,onAttempt:a,onSuccess:p||o,onError:g||d,customerEmail:M,successUrl:S,cancelUrl:P,metadata:_,couponCode:B}),C&&i.jsx(f.Suspense,{fallback:null,children:i.jsx(Ct,{resource:r,items:s,label:u,onAttempt:a,onSuccess:c||o,onError:y||d,testPageUrl:$,hideMessages:I,metadata:_,couponCode:B})}),l&&i.jsx(ge,{resource:r,items:s,label:h,authToken:A,onAttempt:a?()=>a("credits"):void 0,onSuccess:m||o,onError:b||d,metadata:_,couponCode:B})]})]})}):null},_e=({resource:e,items:t,label:r,cardLabel:s,cryptoLabel:n,creditsLabel:u,showCard:h=!0,showCrypto:x=!0,showCredits:C=!1,onPaymentAttempt:l,onPaymentSuccess:a,onPaymentError:o,onStripeSuccess:d,onCryptoSuccess:p,onCreditsSuccess:c,onStripeError:m,onCryptoError:g,onCreditsError:y,customerEmail:b,successUrl:M,cancelUrl:S,metadata:P,couponCode:_,authToken:B,autoDetectWallets:A=!0,testPageUrl:$,hideMessages:I=!1,renderModal:w})=>{const j=H.useCedrosTheme(),[D,k]=f.useState(!1),{status:T,processPayment:R,processCartCheckout:v}=fe(),{isCartMode:E,effectiveResource:O}=se(e,t),{t:L}=K(),F=r||L("ui.purchase"),De=s||L("ui.card"),Be=n||L("ui.usdc_solana"),$e=u||L("ui.pay_with_credits")||"Pay with Credits",he=f.useCallback(async()=>{if(A&&h){const{detectSolanaWallets:N}=await Promise.resolve().then(()=>require("./walletDetection-bNmV5ItZ.js"));if(!N()){const oe=E?void 0:O,ie=E&&t?re(t):void 0;Z("stripe",oe,ie),l&&l("stripe"),ee("stripe",oe,ie);let U;E&&t?U=await v(t,M,S,P,b,_):O&&(U=await R(O,M,S,P,b,_)),U&&U.success&&U.transactionId?(te("stripe",U.transactionId,oe,ie),d?d(U.transactionId):a&&a(U.transactionId)):U&&!U.success&&U.error&&(W("stripe",U.error,oe,ie),m?m(U.error):o&&o(U.error));return}}k(!0)},[A,h,E,t,O,v,R,M,S,P,b,_,a,o,d,m,l]),ye=f.useMemo(()=>E&&t?`purchase-cart-${t.map(N=>N.resource).join("-")}`:`purchase-${O||"unknown"}`,[E,t,O]),Ae=f.useMemo(()=>J(ye,he),[ye,he]),ne=T==="loading",be={isOpen:D,onClose:()=>k(!1),resource:E?void 0:O,items:E?t:void 0,cardLabel:De,cryptoLabel:Be,creditsLabel:$e,showCard:h,showCrypto:x,showCredits:C,onPaymentAttempt:l,onPaymentSuccess:N=>{k(!1),a?.(N)},onPaymentError:N=>{k(!1),o?.(N)},onStripeSuccess:N=>{k(!1),d?.(N)},onCryptoSuccess:N=>{k(!1),p?.(N)},onCreditsSuccess:N=>{k(!1),c?.(N)},onStripeError:N=>{k(!1),m?.(N)},onCryptoError:N=>{k(!1),g?.(N)},onCreditsError:N=>{k(!1),y?.(N)},customerEmail:b,successUrl:M,cancelUrl:S,metadata:P,couponCode:_,authToken:B,testPageUrl:$,hideMessages:I};return i.jsxs("div",{className:j.unstyled?"":j.className,style:j.unstyled?{}:j.style,children:[i.jsx("button",{onClick:Ae,disabled:ne,className:j.unstyled?"":"cedros-theme__button cedros-theme__stripe",style:{width:"100%",cursor:ne?"not-allowed":"pointer",opacity:ne?.6:1},type:"button",children:ne?L("ui.processing"):F}),w?w(be):i.jsx(Te,{...be})]})},xt={"mainnet-beta":"https://api.mainnet-beta.solana.com",devnet:"https://api.devnet.solana.com",testnet:"https://api.testnet.solana.com"};function wt(){const[e,t]=f.useState(null);return f.useEffect(()=>{let r=!1;return import("@solana/wallet-adapter-react").then(s=>{r||t(s)}),()=>{r=!0}},[]),e}function St({endpoint:e,wallets:t,children:r}){const s=wt();if(!s)return i.jsx(i.Fragment,{children:r});const{ConnectionProvider:n,WalletProvider:u}=s;return i.jsx(n,{endpoint:e,children:i.jsx(u,{wallets:t,autoConnect:!1,children:r})})}const Pt=f.lazy(()=>Promise.resolve().then(()=>require("./CryptoButton-DxFCYDlJ.js")).then(e=>e.CryptoButton$1).then(e=>({default:e.CryptoButton})));function vt(e){const{resource:t,items:r,checkout:s={},display:n={},callbacks:u={},advanced:h={}}=e,{config:x,walletPool:C}=z.useCedrosContext(),l=H.useCedrosTheme(),{isCartMode:a}=se(t,r),o=n.showCrypto??!0,d=f.useMemo(()=>({marginTop:"0.5rem",fontSize:"0.875rem",color:l.tokens.surfaceText,opacity:.7,textAlign:"center"}),[l.tokens.surfaceText]),p=f.useMemo(()=>o?h.wallets&&h.wallets.length>0?h.wallets:C.getAdapters():[],[h.wallets,C,o]),c=f.useMemo(()=>r?re(r):0,[r]),{onPaymentSuccess:m,onPaymentError:g,onPaymentAttempt:y}=u,b=f.useCallback(v=>m?.({transactionId:v,method:"stripe"}),[m]),M=f.useCallback(v=>m?.({transactionId:v,method:"crypto"}),[m]),S=f.useCallback(v=>g?.({message:v,method:"stripe"}),[g]),P=f.useCallback(v=>g?.({message:v,method:"crypto"}),[g]),_=f.useCallback(v=>m?.({transactionId:v,method:"credits"}),[m]),B=f.useCallback(v=>g?.({message:v,method:"credits"}),[g]),A=f.useCallback(()=>y?.("credits"),[y]),$=o?x.solanaEndpoint??xt[x.solanaCluster]:"";if(!t&&(!r||r.length===0))return q.getLogger().error('CedrosPay: Must provide either "resource" or "items" prop'),i.jsx("div",{className:n.className,style:{color:l.tokens.errorText},children:"Configuration error: No resource or items provided"});const I=n.showCard??!0,w=n.showCredits??!1,j=n.showPurchaseButton??!1,D=n.layout??"vertical",k=n.hideMessages??!1,T=h.autoDetectWallets??!0,R=i.jsx("div",{className:l.unstyled?n.className:`cedros-theme__pay ${n.className||""}`,children:i.jsxs("div",{className:l.unstyled?"":`cedros-theme__pay-content cedros-theme__pay-content--${D}`,children:[j?i.jsx(_e,{resource:a?void 0:t||r?.[0]?.resource,items:a?r:void 0,label:n.purchaseLabel,cardLabel:n.cardLabel,cryptoLabel:n.cryptoLabel,showCard:I,showCrypto:o,onPaymentAttempt:u.onPaymentAttempt,onPaymentSuccess:b,onPaymentError:S,onStripeSuccess:b,onCryptoSuccess:M,onStripeError:S,onCryptoError:P,customerEmail:s.customerEmail,successUrl:s.successUrl,cancelUrl:s.cancelUrl,metadata:s.metadata,couponCode:s.couponCode,autoDetectWallets:T,testPageUrl:h.testPageUrl,hideMessages:k,renderModal:n.renderModal}):i.jsxs(i.Fragment,{children:[I&&i.jsx(me,{resource:a?void 0:t||r?.[0]?.resource,items:a?r:void 0,customerEmail:s.customerEmail,successUrl:s.successUrl,cancelUrl:s.cancelUrl,metadata:s.metadata,couponCode:s.couponCode,label:n.cardLabel,onAttempt:u.onPaymentAttempt,onSuccess:b,onError:S}),o&&i.jsx(f.Suspense,{fallback:null,children:i.jsx(Pt,{resource:a?void 0:t||r?.[0]?.resource,items:a?r:void 0,metadata:s.metadata,couponCode:s.couponCode,label:n.cryptoLabel,onAttempt:u.onPaymentAttempt,onSuccess:M,onError:P,testPageUrl:h.testPageUrl,hideMessages:k})}),w&&i.jsx(ge,{resource:a?void 0:t||r?.[0]?.resource,items:a?r:void 0,authToken:s.authToken,metadata:s.metadata,couponCode:s.couponCode,label:n.creditsLabel,onAttempt:A,onSuccess:_,onError:B})]}),a&&r&&r.length>1&&!k&&i.jsxs("div",{style:d,children:["Checking out ",c," items"]})]})});return i.jsx("div",{className:l.unstyled?n.className:l.className,style:l.unstyled?{}:l.style,children:i.jsx(St,{endpoint:$||"https://api.devnet.solana.com",wallets:p,children:R})})}function jt({product:e,paymentMethod:t,showOriginalPrice:r=!1,className:s="",style:n={}}){const u=t==="stripe",h=u?e.fiatAmount:e.cryptoAmount,x=u?e.effectiveFiatAmount:e.effectiveCryptoAmount,C=u?e.fiatCurrency.toUpperCase():e.cryptoToken,l=u?e.hasStripeCoupon:e.hasCryptoCoupon,a=u?e.stripeDiscountPercent:e.cryptoDiscountPercent;return i.jsxs("div",{className:s,style:n,children:[r&&l&&i.jsxs("span",{style:{textDecoration:"line-through",opacity:.6,marginRight:"0.5rem",fontSize:"0.875em"},children:[h.toFixed(2)," ",C]}),i.jsxs("span",{style:{fontWeight:600},children:[x.toFixed(2)," ",C]}),l&&a>0&&i.jsxs("span",{style:{marginLeft:"0.5rem",padding:"0.125rem 0.375rem",backgroundColor:"#10b981",color:"white",borderRadius:"0.25rem",fontSize:"0.75em",fontWeight:600},children:[a,"% OFF"]})]})}function kt({product:e,paymentMethod:t,className:r="",style:s={}}){const n=t==="stripe",u=n?e.hasStripeCoupon:e.hasCryptoCoupon,h=n?e.stripeDiscountPercent:e.cryptoDiscountPercent,x=n?e.stripeCouponCode:e.cryptoCouponCode;if(!u||h===0)return null;const C=n?`${h}% off with card!`:`${h}% off with crypto!`;return i.jsxs("div",{className:r,style:{display:"inline-flex",alignItems:"center",padding:"0.5rem 0.75rem",backgroundColor:n?"#6366f1":"#10b981",color:"white",borderRadius:"0.375rem",fontSize:"0.875rem",fontWeight:600,...s},children:[C,x&&i.jsxs("span",{style:{marginLeft:"0.5rem",opacity:.8,fontSize:"0.75em",fontWeight:400},children:["(",x,")"]})]})}function Ie(){const{subscriptionManager:e}=z.useCedrosContext(),[t,r]=f.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null}),s=f.useRef(!1),n=f.useCallback(async C=>{if(s.current)return{success:!1,error:"Payment already in progress"};s.current=!0,r(l=>({...l,status:"loading",error:null}));try{const l=await e.processSubscription(C);return r(a=>({...a,status:l.success?"success":"error",error:l.success?null:l.error||"Subscription failed",sessionId:l.success&&l.transactionId||null})),l}catch(l){const a=z.formatError(l,"Subscription failed");return r(o=>({...o,status:"error",error:a})),{success:!1,error:a}}finally{s.current=!1}},[e]),u=f.useCallback(async C=>{r(l=>({...l,status:"checking",error:null}));try{const l=await e.checkSubscriptionStatus(C);return r(a=>({...a,status:l.active?"success":"idle",subscriptionStatus:l.status,expiresAt:l.expiresAt||l.currentPeriodEnd||null})),l}catch(l){const a=l instanceof Error?l.message:"Failed to check subscription status";throw r(o=>({...o,status:"error",error:a})),l}},[e]),h=f.useCallback(async(C,l,a)=>{r(o=>({...o,status:"loading",error:null}));try{const o=await e.requestSubscriptionQuote(C,l,a);return r(d=>({...d,status:"idle"})),o}catch(o){const d=o instanceof Error?o.message:"Failed to get subscription quote";throw r(p=>({...p,status:"error",error:d})),o}},[e]),x=f.useCallback(()=>{r({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null})},[]);return{...t,processSubscription:n,checkStatus:u,requestQuote:h,reset:x}}function Et({resource:e,interval:t,intervalDays:r,trialDays:s,successUrl:n,cancelUrl:u,customerEmail:h,label:x,disabled:C=!1,onAttempt:l,onSuccess:a,onError:o,className:d=""}){const{status:p,error:c,sessionId:m,processSubscription:g}=Ie(),y=H.useCedrosTheme(),{t:b,translations:M}=K(),S=x||b("ui.subscribe"),P=y.unstyled?d:`${y.className} cedros-theme__stripe-button ${d}`.trim(),_=c&&typeof c!="string"?c?.code??null:null,A=c?typeof c=="string"?c:(k=>{if(!k||!M)return"";const T=M.errors[k];return T?T.action?`${T.message} ${T.action}`:T.message:""})(_):null,$=f.useCallback(async()=>{q.getLogger().debug("[SubscribeButton] executeSubscription:",{resource:e,interval:t,intervalDays:r,trialDays:s}),Z("stripe",e),l&&l("stripe"),ee("stripe",e);const k=await g({resource:e,interval:t,intervalDays:r,trialDays:s,customerEmail:h,successUrl:n,cancelUrl:u});k.success&&k.transactionId?(te("stripe",k.transactionId,e),a&&a(k.transactionId)):!k.success&&k.error&&(W("stripe",k.error,e),o&&o(k.error))},[e,t,r,s,h,n,u,g,l,a,o]),I=f.useMemo(()=>`subscribe-${e}-${t}`,[e,t]),w=f.useMemo(()=>J(I,$),[I,$]),j=p==="loading",D=C||j;return i.jsxs("div",{className:P,style:y.unstyled?{}:y.style,children:[i.jsx("button",{onClick:w,disabled:D,className:y.unstyled?d:"cedros-theme__button cedros-theme__stripe",type:"button",children:j?b("ui.processing"):S}),A&&i.jsx("div",{className:y.unstyled?"":"cedros-theme__error",children:A}),m&&i.jsx("div",{className:y.unstyled?"":"cedros-theme__success",children:b("ui.redirecting_to_checkout")})]})}function qe(){const{subscriptionManager:e,creditsManager:t}=z.useCedrosContext(),[r,s]=f.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null}),n=f.useRef(!1),u=f.useCallback(async(l,a)=>{s(o=>({...o,status:"checking",error:null}));try{const o=await e.checkSubscriptionStatus({resource:l,userId:a});return s(d=>({...d,status:o.active?"success":"idle",subscriptionStatus:o.status,expiresAt:o.expiresAt||o.currentPeriodEnd||null})),o}catch(o){const d=z.formatError(o,"Failed to check subscription status");return s(p=>({...p,status:"error",error:d})),null}},[e]),h=f.useCallback(async(l,a,o)=>{s(d=>({...d,status:"loading",error:null}));try{const d=await t.requestQuote(l,o?.couponCode);return s(p=>({...p,status:"idle",creditsRequirement:d})),d}catch(d){const p=z.formatError(d,"Failed to get subscription quote");return s(c=>({...c,status:"error",error:p})),null}},[t]),x=f.useCallback(async(l,a,o,d)=>{if(n.current)return{success:!1,error:"Payment already in progress"};if(!o){const p="Authentication required for credits payment";return s(c=>({...c,status:"error",error:p})),{success:!1,error:p}}n.current=!0,s(p=>({...p,status:"loading",error:null}));try{const p=await t.processPayment(l,o,d?.couponCode,{interval:a,...d?.intervalDays&&{intervalDays:String(d.intervalDays)}});return p.success?s({status:"success",error:null,sessionId:p.transactionId||null,subscriptionStatus:"active",expiresAt:null,creditsRequirement:null}):s(c=>({...c,status:"error",error:p.error||"Credits subscription payment failed"})),p}catch(p){const c=z.formatError(p,"Credits subscription payment failed");return s(m=>({...m,status:"error",error:c})),{success:!1,error:c}}finally{n.current=!1}},[t]),C=f.useCallback(()=>{s({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null})},[]);return{...r,checkStatus:u,requestQuote:h,processPayment:x,reset:C}}function Mt({resource:e,interval:t,intervalDays:r,authToken:s,userId:n,couponCode:u,label:h,disabled:x=!1,onAttempt:C,onSuccess:l,onError:a,className:o="",hideMessages:d=!1,autoCheckStatus:p=!1}){const{status:c,error:m,subscriptionStatus:g,expiresAt:y,checkStatus:b,processPayment:M}=qe(),S=H.useCedrosTheme(),{t:P,translations:_}=K(),B=f.useRef(b);f.useEffect(()=>{B.current=b},[b]),f.useEffect(()=>{p&&n&&(q.getLogger().debug("[CreditsSubscribeButton] Auto-checking subscription status",{resource:e,userId:n}),B.current(e,n))},[p,n,e]);const A=h||P("ui.subscribe_with_credits")||"Subscribe with Credits",$=m&&typeof m!="string"?m?.code??null:null,w=m?typeof m=="string"?m:(L=>{if(!L||!_)return"";const F=_.errors[L];return F?F.action?`${F.message} ${F.action}`:F.message:""})($):null,j=f.useCallback(async()=>{if(q.getLogger().debug("[CreditsSubscribeButton] executeSubscriptionFlow",{resource:e,interval:t,intervalDays:r,hasAuthToken:!!s}),Z("credits",e),C&&C("credits"),!s){const F="Authentication required: please log in to subscribe with credits";q.getLogger().error("[CreditsSubscribeButton]",F),W("credits",F,e),a&&a(F);return}ee("credits",e);const L=await M(e,t,s,{couponCode:u,intervalDays:r});L.success&&L.transactionId?(te("credits",L.transactionId,e),l&&l(L.transactionId)):!L.success&&L.error&&(W("credits",L.error,e),a&&a(L.error))},[e,t,r,s,u,M,C,l,a]),D=f.useMemo(()=>`credits-subscribe-${e}-${t}`,[e,t]),k=f.useMemo(()=>J(D,j,{cooldownMs:200,deduplicationWindowMs:0}),[D,j]),T=c==="loading"||c==="checking",R=g==="active"||g==="trialing",v=x||T||R;let E=A;if(T)E=P("ui.processing");else if(R&&y){const L=new Date(y).toLocaleDateString();E=`${P("ui.subscribed_until")} ${L}`}else R&&(E=P("ui.subscribed"));const O=S.unstyled?o:`${S.className} cedros-theme__credits-button ${o}`.trim();return i.jsxs("div",{className:O,style:S.unstyled?{}:S.style,children:[i.jsx("button",{onClick:k,disabled:v,className:S.unstyled?o:"cedros-theme__button cedros-theme__credits",type:"button",children:E}),!d&&w&&i.jsx("div",{className:S.unstyled?"":"cedros-theme__error",children:w}),!d&&R&&i.jsx("div",{className:S.unstyled?"":"cedros-theme__success",children:P("ui.subscription_active")})]})}function Le(){const{subscriptionChangeManager:e}=z.useCedrosContext(),[t,r]=f.useState({status:"idle",error:null,subscription:null,changePreview:null,userId:null}),s=f.useRef(t);s.current=t;const n=f.useCallback(async(o,d)=>{r(p=>({...p,status:"loading",error:null}));try{const p=await e.getDetails(o,d);return r(c=>({...c,status:"success",subscription:p,userId:d})),p}catch(p){const c=p instanceof Error?p.message:"Failed to load subscription";return r(m=>({...m,status:"error",error:c})),null}},[e]),u=f.useCallback(async(o,d,p,c)=>{r(m=>({...m,status:"loading",error:null}));try{const m={currentResource:o,newResource:d,userId:p,newInterval:c},g=await e.previewChange(m);return r(y=>({...y,status:"idle",changePreview:g})),g}catch(m){const g=m instanceof Error?m.message:"Failed to preview change";return r(y=>({...y,status:"error",error:g})),null}},[e]),h=f.useCallback(async o=>{const{subscription:d,userId:p}=s.current;if(!d||!p)return r(c=>({...c,status:"error",error:"No subscription loaded"})),null;r(c=>({...c,status:"loading",error:null}));try{const c={subscriptionId:d.id,newResource:o.newResource,prorationBehavior:o.prorationBehavior},m=await e.changeSubscription(c);return m.success?r(g=>({...g,status:"success",subscription:g.subscription?{...g.subscription,resource:m.newResource,interval:g.subscription.interval,status:m.status,currentPeriodEnd:m.currentPeriodEnd}:null,changePreview:null})):r(g=>({...g,status:"error",error:m.error||"Failed to change subscription"})),m}catch(c){const m=c instanceof Error?c.message:"Failed to change subscription";return r(g=>({...g,status:"error",error:m})),null}},[e]),x=f.useCallback(async o=>{const{subscription:d,userId:p}=s.current;if(!d||!p)return r(c=>({...c,status:"error",error:"No subscription loaded"})),null;r(c=>({...c,status:"loading",error:null}));try{const c={subscriptionId:d.id,atPeriodEnd:!o},m=await e.cancel(c);if(m.success){const g=m.atPeriodEnd?d.status:"canceled";r(y=>({...y,status:"success",subscription:y.subscription?{...y.subscription,status:g,cancelAtPeriodEnd:m.atPeriodEnd}:null}))}else r(g=>({...g,status:"error",error:m.error||"Failed to cancel subscription"}));return m}catch(c){const m=c instanceof Error?c.message:"Failed to cancel subscription";return r(g=>({...g,status:"error",error:m})),null}},[e]),C=f.useCallback(async(o,d)=>{const p=s.current.subscription?.customerId??(o.startsWith("cus_")?o:null);if(!p)return r(c=>({...c,status:"error",error:"No Stripe customer ID available for billing portal"})),null;r(c=>({...c,status:"loading",error:null}));try{const c=await e.getBillingPortalUrl({customerId:p,returnUrl:d});try{if(new URL(c.url).protocol!=="https:")throw new Error("Billing portal URL must use HTTPS")}catch{throw new Error("Invalid billing portal URL")}return window.location.href=c.url,c}catch(c){const m=c instanceof Error?c.message:"Failed to open billing portal";return r(g=>({...g,status:"error",error:m})),null}},[e]),l=f.useCallback(()=>{r(o=>({...o,changePreview:null}))},[]),a=f.useCallback(()=>{r({status:"idle",error:null,subscription:null,changePreview:null,userId:null})},[]);return{...t,loadSubscription:n,previewChange:u,changeSubscription:h,cancelSubscription:x,openBillingPortal:C,clearPreview:l,reset:a}}const Rt={bg:"#fff",bgMuted:"#f9fafb",bgHighlight:"#eff6ff",text:"#111827",textMuted:"#6b7280",textFaint:"#9ca3af",border:"#e5e7eb",borderLight:"#f3f4f6",primary:"#3b82f6",error:"#ef4444",errorBg:"#fef2f2",errorBorder:"#fecaca",warningBg:"#fef3c7",warningBorder:"#fcd34d",warningText:"#92400e",buttonBg:"#f3f4f6",buttonBorder:"#d1d5db",buttonText:"#374151"},Tt={bg:"#1e293b",bgMuted:"#334155",bgHighlight:"rgba(59, 130, 246, 0.15)",text:"#f1f5f9",textMuted:"#94a3b8",textFaint:"#64748b",border:"#475569",borderLight:"#334155",primary:"#3b82f6",error:"#ef4444",errorBg:"rgba(239, 68, 68, 0.15)",errorBorder:"rgba(239, 68, 68, 0.3)",warningBg:"rgba(245, 158, 11, 0.15)",warningBorder:"rgba(245, 158, 11, 0.3)",warningText:"#fbbf24",buttonBg:"#334155",buttonBorder:"#475569",buttonText:"#e2e8f0"};function _t(e){const t=e?Tt:Rt;return{container:{padding:"24px",backgroundColor:t.bg,borderRadius:"8px",border:`1px solid ${t.border}`,fontFamily:"system-ui, -apple-system, sans-serif",color:t.text},error:{padding:"12px 16px",backgroundColor:t.errorBg,border:`1px solid ${t.errorBorder}`,borderRadius:"6px",color:t.error,marginBottom:"16px"},loading:{padding:"24px",textAlign:"center",color:t.textMuted},details:{marginBottom:"24px"},title:{margin:"0 0 16px 0",fontSize:"18px",fontWeight:600,color:t.text},detailRow:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"8px 0",borderBottom:`1px solid ${t.borderLight}`},label:{color:t.textMuted,fontSize:"14px"},value:{color:t.text,fontSize:"14px",fontWeight:500},statusBadge:{padding:"4px 8px",borderRadius:"4px",color:"#fff",fontSize:"12px",fontWeight:500,textTransform:"capitalize"},cancelNotice:{marginTop:"12px",padding:"8px 12px",backgroundColor:t.warningBg,border:`1px solid ${t.warningBorder}`,borderRadius:"6px",color:t.warningText,fontSize:"13px"},prorationPreview:{padding:"16px",backgroundColor:t.bgMuted,borderRadius:"8px",marginBottom:"24px"},previewTitle:{margin:"0 0 12px 0",fontSize:"16px",fontWeight:600,color:t.text},previewDetails:{marginBottom:"16px"},previewRow:{display:"flex",justifyContent:"space-between",padding:"6px 0",fontSize:"14px",color:t.textMuted},previewTotal:{borderTop:`1px solid ${t.border}`,marginTop:"8px",paddingTop:"12px",fontWeight:600,color:t.text},previewActions:{display:"flex",gap:"12px",justifyContent:"flex-end"},cancelButton:{padding:"8px 16px",backgroundColor:t.bg,border:`1px solid ${t.buttonBorder}`,borderRadius:"6px",color:t.buttonText,cursor:"pointer",fontSize:"14px"},confirmButton:{padding:"8px 16px",backgroundColor:t.primary,border:"none",borderRadius:"6px",color:"#fff",cursor:"pointer",fontSize:"14px",fontWeight:500},plansSection:{marginBottom:"24px"},plansTitle:{margin:"0 0 12px 0",fontSize:"16px",fontWeight:600,color:t.text},plansList:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(200px, 1fr))",gap:"16px"},planCard:{padding:"16px",backgroundColor:t.bg,border:`1px solid ${t.border}`,borderRadius:"8px",textAlign:"center"},currentPlan:{borderColor:t.primary,backgroundColor:t.bgHighlight},planName:{fontSize:"16px",fontWeight:600,color:t.text,marginBottom:"4px"},planPrice:{fontSize:"14px",color:t.textMuted,marginBottom:"8px"},planDescription:{fontSize:"12px",color:t.textFaint,marginBottom:"12px"},currentBadge:{display:"inline-block",padding:"4px 8px",backgroundColor:t.primary,color:"#fff",borderRadius:"4px",fontSize:"12px",fontWeight:500},changePlanButton:{padding:"8px 16px",backgroundColor:t.buttonBg,border:`1px solid ${t.buttonBorder}`,borderRadius:"6px",color:t.buttonText,cursor:"pointer",fontSize:"14px",width:"100%"},actions:{display:"flex",gap:"12px",justifyContent:"flex-end",paddingTop:"16px",borderTop:`1px solid ${t.border}`},portalButton:{padding:"10px 20px",backgroundColor:t.primary,border:"none",borderRadius:"6px",color:"#fff",cursor:"pointer",fontSize:"14px",fontWeight:500},cancelSubscriptionButton:{padding:"10px 20px",backgroundColor:t.bg,border:`1px solid ${t.error}`,borderRadius:"6px",color:t.error,cursor:"pointer",fontSize:"14px"}}}function V(e,t){return new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).format(e/100)}function Ne(e){return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}function It(e){switch(e){case"active":return"#22c55e";case"trialing":return"#3b82f6";case"past_due":return"#f59e0b";case"canceled":case"expired":return"#ef4444";default:return"#6b7280"}}function qt({preview:e,onConfirm:t,onCancel:r,isLoading:s,styles:n}){const u=e.immediateAmount<0;return i.jsxs("div",{className:"cedros-proration-preview",style:n.prorationPreview,children:[i.jsx("h4",{style:n.previewTitle,children:"Change Preview"}),i.jsxs("div",{style:n.previewDetails,children:[i.jsxs("div",{style:n.previewRow,children:[i.jsx("span",{children:"Current plan:"}),i.jsxs("span",{children:[V(e.currentPlanPrice,e.currency),"/period"]})]}),i.jsxs("div",{style:n.previewRow,children:[i.jsx("span",{children:"New plan:"}),i.jsxs("span",{children:[V(e.newPlanPrice,e.currency),"/period"]})]}),i.jsxs("div",{style:n.previewRow,children:[i.jsx("span",{children:"Days remaining:"}),i.jsxs("span",{children:[e.daysRemaining," days"]})]}),e.prorationDetails&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:n.previewRow,children:[i.jsx("span",{children:"Unused credit:"}),i.jsxs("span",{children:["-",V(e.prorationDetails.unusedCredit,e.currency)]})]}),i.jsxs("div",{style:n.previewRow,children:[i.jsx("span",{children:"New plan cost:"}),i.jsx("span",{children:V(e.prorationDetails.newPlanCost,e.currency)})]})]}),i.jsxs("div",{style:{...n.previewRow,...n.previewTotal},children:[i.jsx("span",{children:u?"Credit to account:":"Amount due now:"}),i.jsx("span",{style:{color:u?"#22c55e":"#ef4444"},children:V(Math.abs(e.immediateAmount),e.currency)})]}),i.jsxs("div",{style:n.previewRow,children:[i.jsx("span",{children:"Effective date:"}),i.jsx("span",{children:Ne(e.effectiveDate)})]})]}),i.jsxs("div",{style:n.previewActions,children:[i.jsx("button",{onClick:r,style:n.cancelButton,disabled:s,children:"Cancel"}),i.jsx("button",{onClick:t,style:n.confirmButton,disabled:s,children:s?"Processing...":"Confirm Change"})]})]})}function Lt({resource:e,userId:t,availablePlans:r=[],onSubscriptionChanged:s,onSubscriptionCanceled:n,billingPortalReturnUrl:u,showBillingPortal:h=!1,className:x,style:C}){const{mode:l}=H.useCedrosTheme(),a=f.useMemo(()=>_t(l==="dark"),[l]),{subscription:o,changePreview:d,status:p,error:c,loadSubscription:m,previewChange:g,changeSubscription:y,cancelSubscription:b,openBillingPortal:M,clearPreview:S}=Le();f.useEffect(()=>{m(e,t)},[e,t,m]);const P=f.useRef(null),_=f.useCallback(async(w,j)=>{P.current={resource:w,interval:j},await g(e,w,t,j)},[e,t,g]),B=f.useCallback(async()=>{if(!d)return;const w=P.current;(await y({newResource:w?.resource||e,newInterval:w?.interval,immediate:!0}))?.success&&w&&w.interval&&(s?.(w.resource,w.interval),P.current=null)},[d,e,y,s]),A=f.useCallback(async w=>{(await b(w))?.success&&n?.()},[b,n]),$=f.useCallback(()=>{M(t,u)},[t,u,M]),I=p==="loading";return i.jsxs("div",{className:`cedros-subscription-panel ${x||""}`,style:{...a.container,...C},children:[c&&i.jsx("div",{className:"cedros-subscription-error",style:a.error,children:c}),I&&!o&&i.jsx("div",{className:"cedros-subscription-loading",style:a.loading,children:"Loading subscription..."}),o&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"cedros-subscription-details",style:a.details,children:[i.jsx("h3",{style:a.title,children:"Current Subscription"}),i.jsxs("div",{style:a.detailRow,children:[i.jsx("span",{style:a.label,children:"Plan:"}),i.jsx("span",{style:a.value,children:o.resource})]}),i.jsxs("div",{style:a.detailRow,children:[i.jsx("span",{style:a.label,children:"Status:"}),i.jsx("span",{style:{...a.statusBadge,backgroundColor:It(o.status)},children:o.status})]}),i.jsxs("div",{style:a.detailRow,children:[i.jsx("span",{style:a.label,children:"Price:"}),i.jsxs("span",{style:a.value,children:[V(o.pricePerPeriod,o.currency),"/",o.interval]})]}),i.jsxs("div",{style:a.detailRow,children:[i.jsx("span",{style:a.label,children:"Current period ends:"}),i.jsx("span",{style:a.value,children:Ne(o.currentPeriodEnd)})]}),o.cancelAtPeriodEnd&&i.jsx("div",{style:a.cancelNotice,children:"Subscription will cancel at end of current period"})]}),d&&i.jsx(qt,{preview:d,onConfirm:B,onCancel:S,isLoading:I,styles:a}),r.length>0&&!d&&i.jsxs("div",{className:"cedros-available-plans",style:a.plansSection,children:[i.jsx("h4",{style:a.plansTitle,children:"Available Plans"}),i.jsx("div",{style:a.plansList,children:r.map(w=>{const j=w.resource===o.resource;return i.jsxs("div",{style:{...a.planCard,...j?a.currentPlan:{}},children:[i.jsx("div",{style:a.planName,children:w.name}),i.jsxs("div",{style:a.planPrice,children:[V(w.price,w.currency),"/",w.interval]}),w.description&&i.jsx("div",{style:a.planDescription,children:w.description}),j?i.jsx("span",{style:a.currentBadge,children:"Current Plan"}):i.jsx("button",{onClick:()=>_(w.resource,w.interval),style:a.changePlanButton,disabled:I,children:w.price>o.pricePerPeriod?"Upgrade":"Downgrade"})]},w.resource)})})]}),i.jsxs("div",{className:"cedros-subscription-actions",style:a.actions,children:[h&&o.paymentMethod==="stripe"&&i.jsx("button",{onClick:$,style:a.portalButton,disabled:I,children:"Manage Billing"}),o.status==="active"&&!o.cancelAtPeriodEnd&&i.jsx("button",{onClick:()=>A(!1),style:a.cancelSubscriptionButton,disabled:I,children:"Cancel Subscription"})]})]})]})}function Nt(){if(typeof window>"u")return{passed:!0,severity:"info",message:"HTTPS check skipped (SSR environment)"};const e=window.location.protocol==="https:",t=window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1";return e||t?{passed:!0,severity:"info",message:"HTTPS enforced"}:{passed:!1,severity:"error",message:"Page not served over HTTPS",recommendation:"Enable HTTPS for all payment pages. Stripe.js requires HTTPS in production."}}function Dt(){return typeof document>"u"?{passed:!0,severity:"info",message:"CSP check skipped (SSR environment)"}:document.querySelector('meta[http-equiv="Content-Security-Policy"]')?{passed:!0,severity:"info",message:"Content Security Policy detected"}:{passed:!1,severity:"warning",message:"No Content Security Policy detected",recommendation:"Configure CSP headers to protect against XSS and CDN compromise. Use generateCSP() helper from @cedros/pay-react."}}function Bt(){return process.env.NODE_ENV==="development"||typeof window<"u"&&window.location.hostname==="localhost"?{passed:!0,severity:"info",message:"Running in development mode (some security checks relaxed)"}:{passed:!0,severity:"info",message:"Running in production mode"}}function $t(){return{passed:!0,severity:"info",message:"Stripe.js loaded via @stripe/stripe-js package (CSP recommended, not SRI)",recommendation:"Ensure CSP script-src includes https://js.stripe.com"}}function At(){return typeof window>"u"?{passed:!0,severity:"info",message:"Mixed content check skipped (SSR environment)"}:window.location.protocol==="https:"?{passed:!0,severity:"info",message:"Mixed content protection active (HTTPS page)"}:{passed:!0,severity:"info",message:"Mixed content check skipped (HTTP page)"}}function zt(){const e=[Nt(),Dt(),Bt(),$t(),At()],t=e.some(u=>u.severity==="error"&&!u.passed),r=e.some(u=>u.severity==="warning"&&!u.passed);let s,n;return t?(s="vulnerable",n="Security issues detected. Review errors and apply recommendations."):r?(s="warnings",n="Minor security warnings detected. Consider applying recommendations."):(s="secure",n="All security checks passed."),{checks:e,overallStatus:s,summary:n}}function Ut(e){process.env.NODE_ENV!=="production"&&(console.group("🔒 Cedros Pay Security Report"),console.log(`Status: ${e.overallStatus.toUpperCase()}`),console.log(`Summary: ${e.summary}`),console.log(""),e.checks.forEach(t=>{const r=t.passed?"✅":t.severity==="error"?"❌":"⚠️";console.log(`${r} ${t.message}`),t.recommendation&&console.log(` → ${t.recommendation}`)}),console.groupEnd())}const Ot={CSP:"Use generateCSP() from @cedros/pay-react to generate Content Security Policy headers",HTTPS:"Always serve payment pages over HTTPS in production",PACKAGE_UPDATES:"Keep @stripe/stripe-js and @cedros/pay-react updated for security patches",AUDIT:"Run npm audit regularly to check for known vulnerabilities",MONITORING:"Monitor Stripe security advisories and apply updates promptly",NO_SRI:"Do NOT use SRI hashes for Stripe.js - use CSP instead"};exports.CEDROS_EVENTS=Y;exports.CSP_PRESETS=mt;exports.CedrosPay=vt;exports.CreditsButton=ge;exports.CreditsSubscribeButton=Mt;exports.PaymentMethodBadge=kt;exports.PaymentModal=Te;exports.ProductPrice=jt;exports.PurchaseButton=_e;exports.RPC_PROVIDERS=ft;exports.SECURITY_RECOMMENDATIONS=Ot;exports.StripeButton=me;exports.SubscribeButton=Et;exports.SubscriptionManagementPanel=Lt;exports.calculateDiscountPercentage=Ge;exports.createDedupedClickHandler=J;exports.createTranslator=Me;exports.detectLocale=ke;exports.emitPaymentError=W;exports.emitPaymentProcessing=ee;exports.emitPaymentStart=Z;exports.emitPaymentSuccess=te;exports.emitWalletConnect=ot;exports.emitWalletConnected=it;exports.emitWalletError=at;exports.formatCSP=je;exports.formatCouponCodes=Ve;exports.generateCSP=pt;exports.generateCSPDirectives=ve;exports.getAvailableLocales=ht;exports.getCartItemCount=re;exports.getLocalizedError=yt;exports.getModalCloseButtonStyles=Pe;exports.getUserErrorMessage=lt;exports.isRetryableError=ct;exports.loadLocale=Ee;exports.logSecurityReport=Ut;exports.normalizeCartItems=ce;exports.parseCouponCodes=Qe;exports.stackCheckoutCoupons=Ke;exports.useCreditsPayment=Re;exports.useCreditsSubscription=qe;exports.useLocalizedError=bt;exports.usePaymentMode=se;exports.useStripeCheckout=fe;exports.useSubscription=Ie;exports.useSubscriptionManagement=Le;exports.useTranslation=K;exports.validateSecurity=zt;