@cedros/pay-react 1.1.22 → 1.1.24

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 (115) hide show
  1. package/dist/{AISettingsSection-p3iikbSw.mjs → AISettingsSection-Dw0ZlxMf.mjs} +2 -2
  2. package/dist/{AISettingsSection-BtOxEweU.js → AISettingsSection-IXS1Wt_1.js} +1 -1
  3. package/dist/{AutosaveIndicator-CWbb-VXf.mjs → AutosaveIndicator-BJsg_kFZ.mjs} +1 -1
  4. package/dist/{AutosaveIndicator-C-CH-obR.js → AutosaveIndicator-CY_YHM1D.js} +1 -1
  5. package/dist/{CedrosContext-D-lnoEkR.js → CedrosContext-7dwmEeUY.js} +2 -2
  6. package/dist/{CedrosContext-BE6P5PQ0.mjs → CedrosContext-DQUbL8yP.mjs} +105 -88
  7. package/dist/{CryptoButton-Dy-g3bR0.js → CryptoButton-C1AAOOfj.js} +1 -1
  8. package/dist/{CryptoButton-CksMkZjL.mjs → CryptoButton-D1BCZBk4.mjs} +51 -51
  9. package/dist/{FAQSection-DQpF7hVx.js → FAQSection-BmgmzDN5.js} +1 -1
  10. package/dist/{FAQSection-byh7zfqI.mjs → FAQSection-C78MnK4k.mjs} +1 -1
  11. package/dist/{MessagingSection-B6EHvjDw.js → MessagingSection-CWLZcg11.js} +1 -1
  12. package/dist/{MessagingSection-CK208brx.mjs → MessagingSection-De3t8bSI.mjs} +2 -2
  13. package/dist/OrdersSection-BKOxsZw0.js +1 -0
  14. package/dist/OrdersSection-_xKVzjSZ.mjs +233 -0
  15. package/dist/{PaymentSettingsSection-Cmmuhmd4.js → PaymentSettingsSection-BTEn9Dxb.js} +1 -1
  16. package/dist/{PaymentSettingsSection-B9H253x1.mjs → PaymentSettingsSection-KjU_dN_d.mjs} +1 -1
  17. package/dist/{SettingsSection-DDLMaEPo.mjs → SettingsSection-8QHZB59k.mjs} +1 -1
  18. package/dist/{SettingsSection-DrzGdvHH.js → SettingsSection-cKF0tLnS.js} +1 -1
  19. package/dist/SingleCategorySettings--LK0TZW0.mjs +1006 -0
  20. package/dist/SingleCategorySettings-CRXTMTo5.js +3 -0
  21. package/dist/{StorefrontSection-DTpZ_GgO.js → StorefrontSection-C9DzCmOf.js} +1 -1
  22. package/dist/{StorefrontSection-Dr2ciBVg.mjs → StorefrontSection-CeCpr8hn.mjs} +2 -2
  23. package/dist/{SubscriptionsSection-CU3Ce8r9.mjs → SubscriptionsSection-C2xk8ApF.mjs} +1 -1
  24. package/dist/{SubscriptionsSection-CYJpArJ8.js → SubscriptionsSection-Dn5SY6S_.js} +1 -1
  25. package/dist/Token22Section-DUUl59dZ.js +1 -0
  26. package/dist/Token22Section-HygkDNtL.mjs +1685 -0
  27. package/dist/{WalletManager-QcfgQmap.js → WalletManager-Bwk3rgr1.js} +1 -1
  28. package/dist/{WalletManager-D78miaJ2.mjs → WalletManager-CXvQ0Zu9.mjs} +1 -1
  29. package/dist/bn-Bv2sKQMU.mjs +1185 -0
  30. package/dist/bn-CHyy7EgJ.js +1 -0
  31. package/dist/configApi-Ch0Rr7TD.mjs +554 -0
  32. package/dist/configApi-CxEbCAgG.js +1 -0
  33. package/dist/crypto-only.js +1 -1
  34. package/dist/crypto-only.mjs +54 -52
  35. package/dist/{index-CufXF9Yd.mjs → index-BHF82XBB.mjs} +6687 -5866
  36. package/dist/index-OaWkrl0G.js +84 -0
  37. package/dist/index.js +1 -1
  38. package/dist/index.mjs +34 -32
  39. package/dist/pay-react_false-CPX8Vyp9.mjs +5 -0
  40. package/dist/pay-react_false-DaeIe3_l.js +1 -0
  41. package/dist/{sections-CR7NRsjq.js → sections-8e5Y3ukY.js} +1 -1
  42. package/dist/sections-C1rb9YRh.mjs +9 -0
  43. package/dist/src/components/CreditsBalance.d.ts +24 -0
  44. package/dist/src/components/CreditsBalance.d.ts.map +1 -0
  45. package/dist/src/components/admin/AssetClassesTab.d.ts +20 -0
  46. package/dist/src/components/admin/AssetClassesTab.d.ts.map +1 -0
  47. package/dist/src/components/admin/AssetRedemptionManager.d.ts +21 -0
  48. package/dist/src/components/admin/AssetRedemptionManager.d.ts.map +1 -0
  49. package/dist/src/components/admin/CedrosPayAdminDashboard.d.ts +1 -1
  50. package/dist/src/components/admin/CedrosPayAdminDashboard.d.ts.map +1 -1
  51. package/dist/src/components/admin/GiftCardComplianceTab.d.ts +3 -0
  52. package/dist/src/components/admin/GiftCardComplianceTab.d.ts.map +1 -0
  53. package/dist/src/components/admin/LiquidityPoolTab.d.ts +11 -0
  54. package/dist/src/components/admin/LiquidityPoolTab.d.ts.map +1 -0
  55. package/dist/src/components/admin/OrdersSection.d.ts +3 -0
  56. package/dist/src/components/admin/OrdersSection.d.ts.map +1 -0
  57. package/dist/src/components/admin/ProductsSection.d.ts.map +1 -1
  58. package/dist/src/components/admin/RedemptionFormBuilder.d.ts +25 -0
  59. package/dist/src/components/admin/RedemptionFormBuilder.d.ts.map +1 -0
  60. package/dist/src/components/admin/Token22Section.d.ts +3 -0
  61. package/dist/src/components/admin/Token22Section.d.ts.map +1 -0
  62. package/dist/src/components/admin/configApi.d.ts.map +1 -1
  63. package/dist/src/components/admin/index.d.ts +3 -0
  64. package/dist/src/components/admin/index.d.ts.map +1 -1
  65. package/dist/src/ecommerce/adapters/mock/mockAdapter.d.ts.map +1 -1
  66. package/dist/src/ecommerce/adapters/paywall/paywallAdapter.d.ts.map +1 -1
  67. package/dist/src/ecommerce/components/catalog/AssetBadge.d.ts +13 -0
  68. package/dist/src/ecommerce/components/catalog/AssetBadge.d.ts.map +1 -0
  69. package/dist/src/ecommerce/components/catalog/ProductCard.d.ts.map +1 -1
  70. package/dist/src/ecommerce/components/checkout/CheckoutForm.d.ts.map +1 -1
  71. package/dist/src/ecommerce/components/checkout/CheckoutReceipt.d.ts +9 -2
  72. package/dist/src/ecommerce/components/checkout/CheckoutReceipt.d.ts.map +1 -1
  73. package/dist/src/ecommerce/components/checkout/CheckoutSuccessPage.d.ts +7 -1
  74. package/dist/src/ecommerce/components/checkout/CheckoutSuccessPage.d.ts.map +1 -1
  75. package/dist/src/ecommerce/components/checkout/RedemptionForm.d.ts +22 -0
  76. package/dist/src/ecommerce/components/checkout/RedemptionForm.d.ts.map +1 -0
  77. package/dist/src/ecommerce/components/gift-cards/GiftCardRedemptionPage.d.ts +36 -0
  78. package/dist/src/ecommerce/components/gift-cards/GiftCardRedemptionPage.d.ts.map +1 -0
  79. package/dist/src/ecommerce/components/orders/OrderCard.d.ts.map +1 -1
  80. package/dist/src/ecommerce/components/orders/OrderDetails.d.ts +5 -1
  81. package/dist/src/ecommerce/components/orders/OrderDetails.d.ts.map +1 -1
  82. package/dist/src/ecommerce/index.d.ts +6 -0
  83. package/dist/src/ecommerce/index.d.ts.map +1 -1
  84. package/dist/src/ecommerce/state/checkout/checkoutSchema.d.ts +1 -0
  85. package/dist/src/ecommerce/state/checkout/checkoutSchema.d.ts.map +1 -1
  86. package/dist/src/ecommerce/state/checkout/useCheckout.d.ts.map +1 -1
  87. package/dist/src/ecommerce/templates/ProductTemplate.d.ts.map +1 -1
  88. package/dist/src/ecommerce/templates/PurchaseHistoryTemplate.d.ts +5 -1
  89. package/dist/src/ecommerce/templates/PurchaseHistoryTemplate.d.ts.map +1 -1
  90. package/dist/src/ecommerce/types.d.ts +20 -0
  91. package/dist/src/ecommerce/types.d.ts.map +1 -1
  92. package/dist/src/ecommerce/utils/cartItemMetadata.d.ts.map +1 -1
  93. package/dist/src/ecommerce/utils/safeHref.d.ts +9 -0
  94. package/dist/src/ecommerce/utils/safeHref.d.ts.map +1 -0
  95. package/dist/src/hooks/useCreditsBalance.d.ts +32 -0
  96. package/dist/src/hooks/useCreditsBalance.d.ts.map +1 -0
  97. package/dist/src/index.d.ts +4 -0
  98. package/dist/src/index.d.ts.map +1 -1
  99. package/dist/src/managers/CreditsManager.d.ts +15 -0
  100. package/dist/src/managers/CreditsManager.d.ts.map +1 -1
  101. package/dist/src/managers/MeteoraPoolManager.d.ts +86 -0
  102. package/dist/src/managers/MeteoraPoolManager.d.ts.map +1 -0
  103. package/dist/stripe-only.js +1 -1
  104. package/dist/stripe-only.mjs +2 -2
  105. package/dist/{styles-BWrLnaUW.js → styles-21F1-oqx.js} +1 -1
  106. package/dist/{styles--eKKnfdj.mjs → styles-Ag-7ZvAB.mjs} +46 -46
  107. package/dist/testing/index.js +1 -1
  108. package/dist/testing/index.mjs +1 -1
  109. package/dist/{walletPool-DShNjCQ6.mjs → walletPool-C_0P4mTw.mjs} +1 -1
  110. package/dist/{walletPool-BqNfOhB0.js → walletPool-Ddv33tej.js} +1 -1
  111. package/package.json +10 -1
  112. package/dist/SingleCategorySettings-BU98SRFV.mjs +0 -1418
  113. package/dist/SingleCategorySettings-DqcXe-q4.js +0 -3
  114. package/dist/index-IZ4WcMd7.js +0 -84
  115. package/dist/sections-Bc6ARlND.mjs +0 -8
@@ -1 +1 @@
1
- "use strict";const p=require("react/jsx-runtime"),a=require("react"),ce=require("@solana/wallet-adapter-react"),le=require("@solana/wallet-adapter-base"),be=require("@solana/wallet-adapter-react-ui"),i=require("./styles-BWrLnaUW.js"),t=require("./CedrosContext-D-lnoEkR.js");function ie(){const{x402Manager:C,walletManager:l}=t.useCedrosContext(),{publicKey:W,signTransaction:j}=ce.useWallet(),[N,y]=a.useState({status:"idle",error:null,transactionId:null}),[R,L]=a.useState(null),[K,k]=a.useState(null),P=a.useRef(W);P.current=W;const h=a.useRef(j);h.current=j;const g=a.useRef(0),X=6e4,I=()=>{const o=g.current;return o>0&&Date.now()-o<X},S=a.useCallback(()=>{if(!W){const o="Wallet not connected";return y({status:"error",error:o,transactionId:null}),{valid:!1,error:o}}if(!j){const o="Wallet does not support signing";return y({status:"error",error:o,transactionId:null}),{valid:!1,error:o}}return{valid:!0}},[W,j]),q=a.useCallback(async o=>{try{y(d=>({...d,status:"loading"}));const c=await C.requestQuote({resource:o});if(!C.validateRequirement(c))throw new Error("Invalid requirement received from server");return L(c),y(d=>({...d,status:"idle"})),c}catch(c){const d=t.formatError(c,"Failed to fetch requirement");throw y({status:"error",error:d,transactionId:null}),c}},[C]),B=a.useCallback(async(o,c,d,x,n="regular")=>{const s=P.current,m=h.current;if(!s||!m)throw new Error("Wallet disconnected during payment flow");if(!!o.extra?.feePayer){t.getLogger().debug("[useX402Payment] Gasless flow enabled"),t.getLogger().debug("[useX402Payment] Building gasless transaction");const{transaction:b,blockhash:M}=await C.buildGaslessTransaction({resourceId:c,userWallet:s.toString(),feePayer:o.extra.feePayer,couponCode:d});t.getLogger().debug("[useX402Payment] Deserializing backend transaction");const A=l.deserializeTransaction(b);if(P.current?.toString()!==s.toString())throw new Error("Wallet changed during payment flow");t.getLogger().debug("[useX402Payment] Requesting partial signature");const E=await l.partiallySignTransaction({transaction:A,signTransaction:m,blockhash:M});t.getLogger().debug("[useX402Payment] Submitting partial transaction");const z=await C.submitGaslessTransaction({resource:c,partialTx:E,couponCode:d,metadata:x,resourceType:n,requirement:o});return z.success&&z.settlement&&k(z.settlement),z}else{const b=await l.buildTransaction({requirement:o,payerPublicKey:s});if(P.current?.toString()!==s.toString())throw new Error("Wallet changed during payment flow");const M=await l.signTransaction({transaction:b,signTransaction:m}),A=l.buildPaymentPayload({requirement:o,signedTx:M,payerPublicKey:s}),E=await C.submitPayment({resource:c,payload:A,couponCode:d,metadata:x,resourceType:n});return E.success&&E.settlement&&k(E.settlement),E}},[C,l]),w=a.useCallback(async(o,c,d)=>{if(I())return{success:!1,error:"Payment already in progress"};const x=S();if(!x.valid)return{success:!1,error:x.error};g.current=Date.now(),y({status:"loading",error:null,transactionId:null});try{t.getLogger().debug("[useX402Payment] Fetching fresh quote");const n=await C.requestQuote({resource:o,couponCode:c});t.getLogger().debug("[useX402Payment] Received quote",{amount:n.maxAmountRequired}),L(n),t.getLogger().debug("[useX402Payment] Executing payment flow");const s=await B(n,o,c,d,"regular");return s.success?y({status:"success",error:null,transactionId:s.transactionId||"payment-success"}):y({status:"error",error:s.error||"Payment failed",transactionId:null}),s}catch(n){const s=t.formatError(n,"Payment failed");return y({status:"error",error:s,transactionId:null}),{success:!1,error:s}}finally{g.current=0}},[S,C,B]),_=a.useCallback(async(o,c,d)=>{if(I())return{success:!1,error:"Payment already in progress"};const x=S();if(!x.valid)return{success:!1,error:x.error};g.current=Date.now(),y({status:"loading",error:null,transactionId:null});try{const n=i.normalizeCartItems(o),s=await C.requestCartQuote({items:n,metadata:c,couponCode:d}),m=s.cartId,u=s.quote;if(!C.validateRequirement(u))throw new Error("Invalid cart quote received from server");L(u);const b=await B(u,m,d,c,"cart");return b.success?y({status:"success",error:null,transactionId:b.transactionId||"cart-payment-success"}):y({status:"error",error:b.error||"Cart payment failed",transactionId:null}),b}catch(n){const s=t.formatError(n,"Cart payment failed");return y({status:"error",error:s,transactionId:null}),{success:!1,error:s}}finally{g.current=0}},[S,C,B]),T=a.useCallback(()=>{y({status:"idle",error:null,transactionId:null}),L(null),k(null),g.current=0},[]);return{...N,requirement:R,settlement:K,fetchQuote:q,processPayment:w,processCartPayment:_,reset:T}}function ue({resource:C,items:l,label:W,disabled:j=!1,onAttempt:N,onSuccess:y,onError:R,className:L="",testPageUrl:K,hideMessages:k=!1,metadata:P,couponCode:h}){const{connected:g,connecting:X,connect:I,disconnect:S,select:q,wallets:B,wallet:w,publicKey:_}=ce.useWallet(),{status:T,error:o,transactionId:c,processPayment:d,processCartPayment:x}=ie(),n=t.useCedrosTheme(),{solanaError:s}=t.useCedrosContext(),{isCartMode:m,effectiveResource:u}=i.usePaymentMode(C,l),{t:b,translations:M}=i.useTranslation(),A=W||b("ui.pay_with_crypto"),E=o&&typeof o!="string"?o?.code??null:null,z=s&&typeof s!="string"?s?.code??null:null,U=e=>{if(!e||!M)return"";const r=M.errors[e];return r?r.action?`${r.message} ${r.action}`:r.message:""},Y=o?typeof o=="string"?o:U(E):null,H=s?typeof s=="string"?s:U(z):null,J=a.useRef(y),V=a.useRef(R),Z=a.useRef(d),ee=a.useRef(x);J.current=y,V.current=R,Z.current=d,ee.current=x;const de=a.useMemo(()=>B.map(e=>`${e.adapter.name}-${e.readyState}`).join(","),[B]),G=a.useMemo(()=>B.filter(({readyState:e})=>e===le.WalletReadyState.Installed||e===le.WalletReadyState.Loadable),[de]);a.useEffect(()=>{if(T==="success"&&c){const e=m&&l?i.getCartItemCount(l):void 0;i.emitPaymentSuccess("crypto",c,u,e),J.current?.(c)}},[T,c,m,l,u]),a.useEffect(()=>{if(T==="error"&&o){const e=m&&l?i.getCartItemCount(l):void 0;i.emitPaymentError("crypto",o,u,e),V.current?.(o)}},[T,o,m,l,u]);const te=typeof window<"u"&&window.top!==window.self,[re,$]=a.useState(!1),[ne,Q]=a.useState(!1),[D,v]=a.useState(null),F=s;a.useEffect(()=>{let e=!1;return e||(async()=>{if(ne&&w&&!g&&!X){t.getLogger().debug("[CryptoButton] Wallet detected, attempting auto-connect:",w.adapter.name),Q(!1),i.emitWalletConnect(w.adapter.name);try{await I(),e||t.getLogger().debug("[CryptoButton] Auto-connect successful")}catch(f){if(!e){t.getLogger().error("[CryptoButton] Auto-connect failed:",f);const O=f instanceof Error?f.message:"Failed to connect wallet";i.emitWalletError(O,w.adapter.name),v(null)}}}})(),()=>{e=!0}},[w,ne,g,X,I]),a.useEffect(()=>{let e=!0;if(t.getLogger().debug("[CryptoButton] Payment useEffect triggered",{connected:g,hasPendingPayment:!!D,hasPublicKey:!!_,pendingPaymentType:D?.type}),g&&D&&_&&w&&e){i.emitWalletConnected(w.adapter.name,_.toString()),t.getLogger().debug("[CryptoButton] All conditions met! Processing pending payment:",D);const r=D;v(null),$(!1);const f=r.type==="cart"&&r.items?i.getCartItemCount(r.items):void 0;i.emitPaymentProcessing("crypto",r.resource,f),r.type==="cart"&&r.items?(t.getLogger().debug("[CryptoButton] Auto-processing cart payment"),ee.current(r.items,r.metadata,r.couponCode)):r.type==="single"&&r.resource&&(t.getLogger().debug("[CryptoButton] Auto-processing single payment"),Z.current(r.resource,r.couponCode,r.metadata))}return()=>{e=!1}},[g,D,_,w]);const oe=a.useCallback(async()=>{t.getLogger().debug("[CryptoButton] executePaymentFlow called",{connected:g,wallet:w?.adapter.name,couponCode:h,isCartMode:m,hasItems:!!l,effectiveResource:u});const e=m&&l?i.getCartItemCount(l):void 0;if(i.emitPaymentStart("crypto",u,e),N&&N("crypto"),F){t.getLogger().error("[CryptoButton] Solana dependencies missing:",F),i.emitPaymentError("crypto",F,u,e),R&&R(F);return}if(te){const r=K||window.location.href;try{if(new URL(r,window.location.origin).origin!==window.location.origin)throw t.getLogger().error("[CryptoButton] Blocked attempt to open external URL:",r),new Error("Cannot open external URLs from embedded context");window.open(r,"_blank","noopener,noreferrer")}catch(f){throw t.getLogger().error("[CryptoButton] URL validation failed:",f),f}return}if(g)i.emitPaymentProcessing("crypto",u,e),m&&l?(t.getLogger().debug("[CryptoButton] Processing cart payment with coupon:",h),await x(l,P,h)):u&&(t.getLogger().debug("[CryptoButton] Processing single payment with coupon:",h),await d(u,h,P));else{let r=!1;if(m&&l?(t.getLogger().debug("[CryptoButton] Setting pending cart payment with coupon:",h),v({type:"cart",items:l,metadata:P,couponCode:h}),r=!0):u&&(t.getLogger().debug("[CryptoButton] Setting pending single payment with coupon:",h),v({type:"single",resource:u,metadata:P,couponCode:h}),r=!0),!r){t.getLogger().error("[CryptoButton] No valid payment to process");return}try{if(w)t.getLogger().debug("[CryptoButton] Wallet already selected, connecting:",w.adapter.name),i.emitWalletConnect(w.adapter.name),await I();else{if(t.getLogger().debug("[CryptoButton] No wallet selected, showing selector. Available wallets:",G.map(f=>f.adapter.name)),G.length===0){v(null);const f="No wallets available";throw i.emitWalletError(f),new Error(f)}$(!0)}}catch(f){v(null);const O=f instanceof Error?f.message:"Failed to connect wallet";t.getLogger().error("[CryptoButton] Connection error:",O),i.emitWalletError(O,w?.adapter.name)}}},[g,w,h,m,l,u,te,K,G,I,P,x,d,F,N,R]),ae=a.useMemo(()=>m&&l?`crypto-cart-${l.map(e=>e.resource).join("-")}`:`crypto-${u||"unknown"}`,[m,l,u]),ge=a.useMemo(()=>i.createDedupedClickHandler(ae,oe,{cooldownMs:200,deduplicationWindowMs:0}),[ae,oe]),se=T==="loading",ye=j||se||X||!!F,me=se?b("ui.processing"):A,fe=a.useCallback(async()=>{try{Q(!1),g&&await S(),q(null),$(!0)}catch(e){t.getLogger().error("Failed to change wallet:",e)}},[g,S,q]),pe=a.useCallback(e=>{t.getLogger().debug("[CryptoButton] Wallet clicked:",e),$(!1),q(e),Q(!0),t.getLogger().debug("[CryptoButton] Wallet selected, useEffect will auto-connect")},[q]),we=a.useCallback(async()=>{try{if(await S(),v(null),typeof window<"u"&&window.localStorage)try{window.localStorage.removeItem("walletName")}catch(e){e instanceof Error&&e.name==="QuotaExceededError"?t.getLogger().warn("localStorage quota exceeded when removing wallet preference"):t.getLogger().error("Failed to clear wallet preference from localStorage:",e)}}catch(e){t.getLogger().error("Failed to disconnect wallet:",e)}},[S]);return p.jsxs("div",{className:n.unstyled?L:`${n.className} cedros-theme__crypto-button ${L||""}`,style:n.unstyled?{}:n.style,children:[p.jsx("button",{onClick:ge,disabled:ye,className:n.unstyled?L:"cedros-theme__button cedros-theme__crypto",type:"button",children:me}),re&&!k&&p.jsx("div",{className:"cedros-modal-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:n.tokens.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999,padding:"1rem"},onClick:()=>{$(!1),v(null)},children:p.jsxs("div",{className:"cedros-modal-content",style:{backgroundColor:n.tokens.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 ${n.tokens.modalBorder}`},onClick:e=>e.stopPropagation(),children:[p.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},children:[p.jsx("h3",{style:{margin:0,fontSize:"1.25rem",fontWeight:600,color:n.tokens.surfaceText},children:b("wallet.select_wallet")}),p.jsx("button",{onClick:()=>{$(!1),v(null)},style:i.getModalCloseButtonStyles(n.tokens.surfaceText),"aria-label":"Close modal",type:"button",children:"×"})]}),p.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:G.map(e=>p.jsxs("button",{onClick:()=>pe(e.adapter.name),style:{width:"100%",padding:"1rem",backgroundColor:n.tokens.surfaceBackground,border:`1px solid ${n.tokens.surfaceBorder}`,borderRadius:"0.5rem",cursor:"pointer",fontSize:"1rem",textAlign:"left",color:n.tokens.surfaceText,display:"flex",alignItems:"center",gap:"1rem",transition:"all 0.2s ease"},onMouseEnter:r=>{r.currentTarget.style.backgroundColor=n.tokens.modalBackground,r.currentTarget.style.borderColor=n.tokens.surfaceText,r.currentTarget.style.transform="translateY(-2px)"},onMouseLeave:r=>{r.currentTarget.style.backgroundColor=n.tokens.surfaceBackground,r.currentTarget.style.borderColor=n.tokens.surfaceBorder,r.currentTarget.style.transform="translateY(0)"},type:"button",children:[p.jsx(be.WalletIcon,{wallet:e,style:{width:"24px",height:"24px"}}),p.jsx("span",{style:{fontWeight:500},children:e.adapter.name})]},e.adapter.name))})]})}),g&&!k&&!re&&p.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"0.5rem",fontSize:"0.75rem",color:n.tokens.surfaceText,opacity:.7},children:[p.jsx("button",{onClick:fe,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:b("wallet.change")}),p.jsx("button",{onClick:we,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:b("ui.disconnect")})]}),!k&&H&&p.jsx("div",{className:n.unstyled?"":"cedros-theme__error",children:H}),!k&&Y&&p.jsx("div",{className:n.unstyled?"":"cedros-theme__error",children:Y}),!k&&c&&p.jsx("div",{className:n.unstyled?"":"cedros-theme__success",children:b("ui.payment_successful")})]})}const Ce=Object.freeze(Object.defineProperty({__proto__:null,CryptoButton:ue},Symbol.toStringTag,{value:"Module"}));exports.CryptoButton=ue;exports.CryptoButton$1=Ce;exports.useX402Payment=ie;
1
+ "use strict";const p=require("react/jsx-runtime"),a=require("react"),ce=require("@solana/wallet-adapter-react"),le=require("@solana/wallet-adapter-base"),be=require("@solana/wallet-adapter-react-ui"),i=require("./styles-21F1-oqx.js"),t=require("./CedrosContext-7dwmEeUY.js");function ie(){const{x402Manager:C,walletManager:l}=t.useCedrosContext(),{publicKey:W,signTransaction:j}=ce.useWallet(),[N,y]=a.useState({status:"idle",error:null,transactionId:null}),[R,L]=a.useState(null),[K,k]=a.useState(null),P=a.useRef(W);P.current=W;const h=a.useRef(j);h.current=j;const g=a.useRef(0),X=6e4,I=()=>{const o=g.current;return o>0&&Date.now()-o<X},S=a.useCallback(()=>{if(!W){const o="Wallet not connected";return y({status:"error",error:o,transactionId:null}),{valid:!1,error:o}}if(!j){const o="Wallet does not support signing";return y({status:"error",error:o,transactionId:null}),{valid:!1,error:o}}return{valid:!0}},[W,j]),q=a.useCallback(async o=>{try{y(d=>({...d,status:"loading"}));const c=await C.requestQuote({resource:o});if(!C.validateRequirement(c))throw new Error("Invalid requirement received from server");return L(c),y(d=>({...d,status:"idle"})),c}catch(c){const d=t.formatError(c,"Failed to fetch requirement");throw y({status:"error",error:d,transactionId:null}),c}},[C]),B=a.useCallback(async(o,c,d,x,n="regular")=>{const s=P.current,m=h.current;if(!s||!m)throw new Error("Wallet disconnected during payment flow");if(!!o.extra?.feePayer){t.getLogger().debug("[useX402Payment] Gasless flow enabled"),t.getLogger().debug("[useX402Payment] Building gasless transaction");const{transaction:b,blockhash:M}=await C.buildGaslessTransaction({resourceId:c,userWallet:s.toString(),feePayer:o.extra.feePayer,couponCode:d});t.getLogger().debug("[useX402Payment] Deserializing backend transaction");const A=l.deserializeTransaction(b);if(P.current?.toString()!==s.toString())throw new Error("Wallet changed during payment flow");t.getLogger().debug("[useX402Payment] Requesting partial signature");const E=await l.partiallySignTransaction({transaction:A,signTransaction:m,blockhash:M});t.getLogger().debug("[useX402Payment] Submitting partial transaction");const z=await C.submitGaslessTransaction({resource:c,partialTx:E,couponCode:d,metadata:x,resourceType:n,requirement:o});return z.success&&z.settlement&&k(z.settlement),z}else{const b=await l.buildTransaction({requirement:o,payerPublicKey:s});if(P.current?.toString()!==s.toString())throw new Error("Wallet changed during payment flow");const M=await l.signTransaction({transaction:b,signTransaction:m}),A=l.buildPaymentPayload({requirement:o,signedTx:M,payerPublicKey:s}),E=await C.submitPayment({resource:c,payload:A,couponCode:d,metadata:x,resourceType:n});return E.success&&E.settlement&&k(E.settlement),E}},[C,l]),w=a.useCallback(async(o,c,d)=>{if(I())return{success:!1,error:"Payment already in progress"};const x=S();if(!x.valid)return{success:!1,error:x.error};g.current=Date.now(),y({status:"loading",error:null,transactionId:null});try{t.getLogger().debug("[useX402Payment] Fetching fresh quote");const n=await C.requestQuote({resource:o,couponCode:c});t.getLogger().debug("[useX402Payment] Received quote",{amount:n.maxAmountRequired}),L(n),t.getLogger().debug("[useX402Payment] Executing payment flow");const s=await B(n,o,c,d,"regular");return s.success?y({status:"success",error:null,transactionId:s.transactionId||"payment-success"}):y({status:"error",error:s.error||"Payment failed",transactionId:null}),s}catch(n){const s=t.formatError(n,"Payment failed");return y({status:"error",error:s,transactionId:null}),{success:!1,error:s}}finally{g.current=0}},[S,C,B]),_=a.useCallback(async(o,c,d)=>{if(I())return{success:!1,error:"Payment already in progress"};const x=S();if(!x.valid)return{success:!1,error:x.error};g.current=Date.now(),y({status:"loading",error:null,transactionId:null});try{const n=i.normalizeCartItems(o),s=await C.requestCartQuote({items:n,metadata:c,couponCode:d}),m=s.cartId,u=s.quote;if(!C.validateRequirement(u))throw new Error("Invalid cart quote received from server");L(u);const b=await B(u,m,d,c,"cart");return b.success?y({status:"success",error:null,transactionId:b.transactionId||"cart-payment-success"}):y({status:"error",error:b.error||"Cart payment failed",transactionId:null}),b}catch(n){const s=t.formatError(n,"Cart payment failed");return y({status:"error",error:s,transactionId:null}),{success:!1,error:s}}finally{g.current=0}},[S,C,B]),T=a.useCallback(()=>{y({status:"idle",error:null,transactionId:null}),L(null),k(null),g.current=0},[]);return{...N,requirement:R,settlement:K,fetchQuote:q,processPayment:w,processCartPayment:_,reset:T}}function ue({resource:C,items:l,label:W,disabled:j=!1,onAttempt:N,onSuccess:y,onError:R,className:L="",testPageUrl:K,hideMessages:k=!1,metadata:P,couponCode:h}){const{connected:g,connecting:X,connect:I,disconnect:S,select:q,wallets:B,wallet:w,publicKey:_}=ce.useWallet(),{status:T,error:o,transactionId:c,processPayment:d,processCartPayment:x}=ie(),n=t.useCedrosTheme(),{solanaError:s}=t.useCedrosContext(),{isCartMode:m,effectiveResource:u}=i.usePaymentMode(C,l),{t:b,translations:M}=i.useTranslation(),A=W||b("ui.pay_with_crypto"),E=o&&typeof o!="string"?o?.code??null:null,z=s&&typeof s!="string"?s?.code??null:null,U=e=>{if(!e||!M)return"";const r=M.errors[e];return r?r.action?`${r.message} ${r.action}`:r.message:""},Y=o?typeof o=="string"?o:U(E):null,H=s?typeof s=="string"?s:U(z):null,J=a.useRef(y),V=a.useRef(R),Z=a.useRef(d),ee=a.useRef(x);J.current=y,V.current=R,Z.current=d,ee.current=x;const de=a.useMemo(()=>B.map(e=>`${e.adapter.name}-${e.readyState}`).join(","),[B]),G=a.useMemo(()=>B.filter(({readyState:e})=>e===le.WalletReadyState.Installed||e===le.WalletReadyState.Loadable),[de]);a.useEffect(()=>{if(T==="success"&&c){const e=m&&l?i.getCartItemCount(l):void 0;i.emitPaymentSuccess("crypto",c,u,e),J.current?.(c)}},[T,c,m,l,u]),a.useEffect(()=>{if(T==="error"&&o){const e=m&&l?i.getCartItemCount(l):void 0;i.emitPaymentError("crypto",o,u,e),V.current?.(o)}},[T,o,m,l,u]);const te=typeof window<"u"&&window.top!==window.self,[re,$]=a.useState(!1),[ne,Q]=a.useState(!1),[D,v]=a.useState(null),F=s;a.useEffect(()=>{let e=!1;return e||(async()=>{if(ne&&w&&!g&&!X){t.getLogger().debug("[CryptoButton] Wallet detected, attempting auto-connect:",w.adapter.name),Q(!1),i.emitWalletConnect(w.adapter.name);try{await I(),e||t.getLogger().debug("[CryptoButton] Auto-connect successful")}catch(f){if(!e){t.getLogger().error("[CryptoButton] Auto-connect failed:",f);const O=f instanceof Error?f.message:"Failed to connect wallet";i.emitWalletError(O,w.adapter.name),v(null)}}}})(),()=>{e=!0}},[w,ne,g,X,I]),a.useEffect(()=>{let e=!0;if(t.getLogger().debug("[CryptoButton] Payment useEffect triggered",{connected:g,hasPendingPayment:!!D,hasPublicKey:!!_,pendingPaymentType:D?.type}),g&&D&&_&&w&&e){i.emitWalletConnected(w.adapter.name,_.toString()),t.getLogger().debug("[CryptoButton] All conditions met! Processing pending payment:",D);const r=D;v(null),$(!1);const f=r.type==="cart"&&r.items?i.getCartItemCount(r.items):void 0;i.emitPaymentProcessing("crypto",r.resource,f),r.type==="cart"&&r.items?(t.getLogger().debug("[CryptoButton] Auto-processing cart payment"),ee.current(r.items,r.metadata,r.couponCode)):r.type==="single"&&r.resource&&(t.getLogger().debug("[CryptoButton] Auto-processing single payment"),Z.current(r.resource,r.couponCode,r.metadata))}return()=>{e=!1}},[g,D,_,w]);const oe=a.useCallback(async()=>{t.getLogger().debug("[CryptoButton] executePaymentFlow called",{connected:g,wallet:w?.adapter.name,couponCode:h,isCartMode:m,hasItems:!!l,effectiveResource:u});const e=m&&l?i.getCartItemCount(l):void 0;if(i.emitPaymentStart("crypto",u,e),N&&N("crypto"),F){t.getLogger().error("[CryptoButton] Solana dependencies missing:",F),i.emitPaymentError("crypto",F,u,e),R&&R(F);return}if(te){const r=K||window.location.href;try{if(new URL(r,window.location.origin).origin!==window.location.origin)throw t.getLogger().error("[CryptoButton] Blocked attempt to open external URL:",r),new Error("Cannot open external URLs from embedded context");window.open(r,"_blank","noopener,noreferrer")}catch(f){throw t.getLogger().error("[CryptoButton] URL validation failed:",f),f}return}if(g)i.emitPaymentProcessing("crypto",u,e),m&&l?(t.getLogger().debug("[CryptoButton] Processing cart payment with coupon:",h),await x(l,P,h)):u&&(t.getLogger().debug("[CryptoButton] Processing single payment with coupon:",h),await d(u,h,P));else{let r=!1;if(m&&l?(t.getLogger().debug("[CryptoButton] Setting pending cart payment with coupon:",h),v({type:"cart",items:l,metadata:P,couponCode:h}),r=!0):u&&(t.getLogger().debug("[CryptoButton] Setting pending single payment with coupon:",h),v({type:"single",resource:u,metadata:P,couponCode:h}),r=!0),!r){t.getLogger().error("[CryptoButton] No valid payment to process");return}try{if(w)t.getLogger().debug("[CryptoButton] Wallet already selected, connecting:",w.adapter.name),i.emitWalletConnect(w.adapter.name),await I();else{if(t.getLogger().debug("[CryptoButton] No wallet selected, showing selector. Available wallets:",G.map(f=>f.adapter.name)),G.length===0){v(null);const f="No wallets available";throw i.emitWalletError(f),new Error(f)}$(!0)}}catch(f){v(null);const O=f instanceof Error?f.message:"Failed to connect wallet";t.getLogger().error("[CryptoButton] Connection error:",O),i.emitWalletError(O,w?.adapter.name)}}},[g,w,h,m,l,u,te,K,G,I,P,x,d,F,N,R]),ae=a.useMemo(()=>m&&l?`crypto-cart-${l.map(e=>e.resource).join("-")}`:`crypto-${u||"unknown"}`,[m,l,u]),ge=a.useMemo(()=>i.createDedupedClickHandler(ae,oe,{cooldownMs:200,deduplicationWindowMs:0}),[ae,oe]),se=T==="loading",ye=j||se||X||!!F,me=se?b("ui.processing"):A,fe=a.useCallback(async()=>{try{Q(!1),g&&await S(),q(null),$(!0)}catch(e){t.getLogger().error("Failed to change wallet:",e)}},[g,S,q]),pe=a.useCallback(e=>{t.getLogger().debug("[CryptoButton] Wallet clicked:",e),$(!1),q(e),Q(!0),t.getLogger().debug("[CryptoButton] Wallet selected, useEffect will auto-connect")},[q]),we=a.useCallback(async()=>{try{if(await S(),v(null),typeof window<"u"&&window.localStorage)try{window.localStorage.removeItem("walletName")}catch(e){e instanceof Error&&e.name==="QuotaExceededError"?t.getLogger().warn("localStorage quota exceeded when removing wallet preference"):t.getLogger().error("Failed to clear wallet preference from localStorage:",e)}}catch(e){t.getLogger().error("Failed to disconnect wallet:",e)}},[S]);return p.jsxs("div",{className:n.unstyled?L:`${n.className} cedros-theme__crypto-button ${L||""}`,style:n.unstyled?{}:n.style,children:[p.jsx("button",{onClick:ge,disabled:ye,className:n.unstyled?L:"cedros-theme__button cedros-theme__crypto",type:"button",children:me}),re&&!k&&p.jsx("div",{className:"cedros-modal-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:n.tokens.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999,padding:"1rem"},onClick:()=>{$(!1),v(null)},children:p.jsxs("div",{className:"cedros-modal-content",style:{backgroundColor:n.tokens.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 ${n.tokens.modalBorder}`},onClick:e=>e.stopPropagation(),children:[p.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},children:[p.jsx("h3",{style:{margin:0,fontSize:"1.25rem",fontWeight:600,color:n.tokens.surfaceText},children:b("wallet.select_wallet")}),p.jsx("button",{onClick:()=>{$(!1),v(null)},style:i.getModalCloseButtonStyles(n.tokens.surfaceText),"aria-label":"Close modal",type:"button",children:"×"})]}),p.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:G.map(e=>p.jsxs("button",{onClick:()=>pe(e.adapter.name),style:{width:"100%",padding:"1rem",backgroundColor:n.tokens.surfaceBackground,border:`1px solid ${n.tokens.surfaceBorder}`,borderRadius:"0.5rem",cursor:"pointer",fontSize:"1rem",textAlign:"left",color:n.tokens.surfaceText,display:"flex",alignItems:"center",gap:"1rem",transition:"all 0.2s ease"},onMouseEnter:r=>{r.currentTarget.style.backgroundColor=n.tokens.modalBackground,r.currentTarget.style.borderColor=n.tokens.surfaceText,r.currentTarget.style.transform="translateY(-2px)"},onMouseLeave:r=>{r.currentTarget.style.backgroundColor=n.tokens.surfaceBackground,r.currentTarget.style.borderColor=n.tokens.surfaceBorder,r.currentTarget.style.transform="translateY(0)"},type:"button",children:[p.jsx(be.WalletIcon,{wallet:e,style:{width:"24px",height:"24px"}}),p.jsx("span",{style:{fontWeight:500},children:e.adapter.name})]},e.adapter.name))})]})}),g&&!k&&!re&&p.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"0.5rem",fontSize:"0.75rem",color:n.tokens.surfaceText,opacity:.7},children:[p.jsx("button",{onClick:fe,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:b("wallet.change")}),p.jsx("button",{onClick:we,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:b("ui.disconnect")})]}),!k&&H&&p.jsx("div",{className:n.unstyled?"":"cedros-theme__error",children:H}),!k&&Y&&p.jsx("div",{className:n.unstyled?"":"cedros-theme__error",children:Y}),!k&&c&&p.jsx("div",{className:n.unstyled?"":"cedros-theme__success",children:b("ui.payment_successful")})]})}const Ce=Object.freeze(Object.defineProperty({__proto__:null,CryptoButton:ue},Symbol.toStringTag,{value:"Module"}));exports.CryptoButton=ue;exports.CryptoButton$1=Ce;exports.useX402Payment=ie;
@@ -1,22 +1,22 @@
1
- import { jsxs as O, jsx as h } from "react/jsx-runtime";
2
- import { useState as L, useRef as R, useCallback as P, useMemo as Y, useEffect as H } from "react";
1
+ import { jsxs as A, jsx as h } from "react/jsx-runtime";
2
+ import { useState as K, useRef as R, useCallback as P, useMemo as Y, useEffect as H } from "react";
3
3
  import { useWallet as be } from "@solana/wallet-adapter-react";
4
4
  import { WalletReadyState as pe } from "@solana/wallet-adapter-base";
5
5
  import { WalletIcon as Te } from "@solana/wallet-adapter-react-ui";
6
- import { T as Ie, i as Ee, O as We, U as V, B as Re, D as fe, y as _e, A as ge, w as qe, x as we, z as Z, V as ze, W as Me } from "./styles--eKKnfdj.mjs";
7
- import { u as he, m as ee, i as n, a as De } from "./CedrosContext-BE6P5PQ0.mjs";
6
+ import { T as Ie, K as Ee, O as We, U as V, q as Re, n as fe, s as _e, o as ge, p as qe, r as we, t as Z, V as Me, W as ze } from "./styles-Ag-7ZvAB.mjs";
7
+ import { u as he, m as ee, i as n, j as De } from "./CedrosContext-DQUbL8yP.mjs";
8
8
  function $e() {
9
- const { x402Manager: g, walletManager: s } = he(), { publicKey: _, signTransaction: q } = be(), [X, d] = L({
9
+ const { x402Manager: g, walletManager: s } = he(), { publicKey: _, signTransaction: q } = be(), [L, d] = K({
10
10
  status: "idle",
11
11
  error: null,
12
12
  transactionId: null
13
- }), [I, k] = L(null), [G, x] = L(null), C = R(_);
13
+ }), [I, k] = K(null), [G, x] = K(null), C = R(_);
14
14
  C.current = _;
15
15
  const w = R(q);
16
16
  w.current = q;
17
- const u = R(0), K = 6e4, E = () => {
17
+ const u = R(0), X = 6e4, E = () => {
18
18
  const o = u.current;
19
- return o > 0 && Date.now() - o < K;
19
+ return o > 0 && Date.now() - o < X;
20
20
  }, v = P(() => {
21
21
  if (!_) {
22
22
  const o = "Wallet not connected";
@@ -27,7 +27,7 @@ function $e() {
27
27
  return d({ status: "error", error: o, transactionId: null }), { valid: !1, error: o };
28
28
  }
29
29
  return { valid: !0 };
30
- }, [_, q]), z = P(
30
+ }, [_, q]), M = P(
31
31
  async (o) => {
32
32
  try {
33
33
  d((i) => ({ ...i, status: "loading" }));
@@ -59,12 +59,12 @@ function $e() {
59
59
  couponCode: i
60
60
  });
61
61
  n().debug("[useX402Payment] Deserializing backend transaction");
62
- const A = s.deserializeTransaction(f);
62
+ const O = s.deserializeTransaction(f);
63
63
  if (C.current?.toString() !== a.toString())
64
64
  throw new Error("Wallet changed during payment flow");
65
65
  n().debug("[useX402Payment] Requesting partial signature");
66
66
  const T = await s.partiallySignTransaction({
67
- transaction: A,
67
+ transaction: O,
68
68
  signTransaction: y,
69
69
  blockhash: D
70
70
  });
@@ -88,13 +88,13 @@ function $e() {
88
88
  const D = await s.signTransaction({
89
89
  transaction: f,
90
90
  signTransaction: y
91
- }), A = s.buildPaymentPayload({
91
+ }), O = s.buildPaymentPayload({
92
92
  requirement: o,
93
93
  signedTx: D,
94
94
  payerPublicKey: a
95
95
  }), T = await g.submitPayment({
96
96
  resource: l,
97
- payload: A,
97
+ payload: O,
98
98
  couponCode: i,
99
99
  metadata: b,
100
100
  resourceType: r
@@ -143,7 +143,7 @@ function $e() {
143
143
  }
144
144
  },
145
145
  [v, g, B]
146
- ), M = P(
146
+ ), z = P(
147
147
  async (o, l, i) => {
148
148
  if (E())
149
149
  return { success: !1, error: "Payment already in progress" };
@@ -194,21 +194,21 @@ function $e() {
194
194
  }), k(null), x(null), u.current = 0;
195
195
  }, []);
196
196
  return {
197
- ...X,
197
+ ...L,
198
198
  requirement: I,
199
199
  settlement: G,
200
- fetchQuote: z,
200
+ fetchQuote: M,
201
201
  processPayment: p,
202
- processCartPayment: M,
202
+ processCartPayment: z,
203
203
  reset: W
204
204
  };
205
205
  }
206
- function Fe({
206
+ function je({
207
207
  resource: g,
208
208
  items: s,
209
209
  label: _,
210
210
  disabled: q = !1,
211
- onAttempt: X,
211
+ onAttempt: L,
212
212
  onSuccess: d,
213
213
  onError: I,
214
214
  className: k = "",
@@ -217,7 +217,7 @@ function Fe({
217
217
  metadata: C,
218
218
  couponCode: w
219
219
  }) {
220
- const { connected: u, connecting: K, connect: E, disconnect: v, select: z, wallets: B, wallet: p, publicKey: M } = be(), { status: W, error: o, transactionId: l, processPayment: i, processCartPayment: b } = $e(), r = De(), { solanaError: a } = he(), { isCartMode: y, effectiveResource: c } = Ee(g, s), { t: f, translations: D } = We(), A = _ || f("ui.pay_with_crypto"), T = o && typeof o != "string" ? o?.code ?? null : null, $ = a && typeof a != "string" ? a?.code ?? null : null, te = (e) => {
220
+ const { connected: u, connecting: X, connect: E, disconnect: v, select: M, wallets: B, wallet: p, publicKey: z } = be(), { status: W, error: o, transactionId: l, processPayment: i, processCartPayment: b } = $e(), r = De(), { solanaError: a } = he(), { isCartMode: y, effectiveResource: c } = Ee(g, s), { t: f, translations: D } = We(), O = _ || f("ui.pay_with_crypto"), T = o && typeof o != "string" ? o?.code ?? null : null, $ = a && typeof a != "string" ? a?.code ?? null : null, te = (e) => {
221
221
  if (!e || !D) return "";
222
222
  const t = D.errors[e];
223
223
  return t ? t.action ? `${t.message} ${t.action}` : t.message : "";
@@ -245,11 +245,11 @@ function Fe({
245
245
  fe("crypto", o, c, e), ae.current?.(o);
246
246
  }
247
247
  }, [W, o, y, s, c]);
248
- const ce = typeof window < "u" && window.top !== window.self, [ie, F] = L(!1), [ue, J] = L(!1), [N, S] = L(null), j = a;
248
+ const ce = typeof window < "u" && window.top !== window.self, [ie, j] = K(!1), [ue, J] = K(!1), [F, S] = K(null), N = a;
249
249
  H(() => {
250
250
  let e = !1;
251
251
  return e || (async () => {
252
- if (ue && p && !u && !K) {
252
+ if (ue && p && !u && !X) {
253
253
  n().debug("[CryptoButton] Wallet detected, attempting auto-connect:", p.adapter.name), J(!1), we(p.adapter.name);
254
254
  try {
255
255
  await E(), e || n().debug("[CryptoButton] Auto-connect successful");
@@ -264,24 +264,24 @@ function Fe({
264
264
  })(), () => {
265
265
  e = !0;
266
266
  };
267
- }, [p, ue, u, K, E]), H(() => {
267
+ }, [p, ue, u, X, E]), H(() => {
268
268
  let e = !0;
269
269
  if (n().debug("[CryptoButton] Payment useEffect triggered", {
270
270
  connected: u,
271
- hasPendingPayment: !!N,
272
- hasPublicKey: !!M,
273
- pendingPaymentType: N?.type
274
- }), u && N && M && p && e) {
275
- _e(p.adapter.name, M.toString()), n().debug("[CryptoButton] All conditions met! Processing pending payment:", N);
276
- const t = N;
277
- S(null), F(!1);
271
+ hasPendingPayment: !!F,
272
+ hasPublicKey: !!z,
273
+ pendingPaymentType: F?.type
274
+ }), u && F && z && p && e) {
275
+ _e(p.adapter.name, z.toString()), n().debug("[CryptoButton] All conditions met! Processing pending payment:", F);
276
+ const t = F;
277
+ S(null), j(!1);
278
278
  const m = t.type === "cart" && t.items ? V(t.items) : void 0;
279
279
  ge("crypto", t.resource, m), t.type === "cart" && t.items ? (n().debug("[CryptoButton] Auto-processing cart payment"), le.current(t.items, t.metadata, t.couponCode)) : t.type === "single" && t.resource && (n().debug("[CryptoButton] Auto-processing single payment"), se.current(t.resource, t.couponCode, t.metadata));
280
280
  }
281
281
  return () => {
282
282
  e = !1;
283
283
  };
284
- }, [u, N, M, p]);
284
+ }, [u, F, z, p]);
285
285
  const de = P(async () => {
286
286
  n().debug("[CryptoButton] executePaymentFlow called", {
287
287
  connected: u,
@@ -292,8 +292,8 @@ function Fe({
292
292
  effectiveResource: c
293
293
  });
294
294
  const e = y && s ? V(s) : void 0;
295
- if (qe("crypto", c, e), X && X("crypto"), j) {
296
- n().error("[CryptoButton] Solana dependencies missing:", j), fe("crypto", j, c, e), I && I(j);
295
+ if (qe("crypto", c, e), L && L("crypto"), N) {
296
+ n().error("[CryptoButton] Solana dependencies missing:", N), fe("crypto", N, c, e), I && I(N);
297
297
  return;
298
298
  }
299
299
  if (ce) {
@@ -327,7 +327,7 @@ function Fe({
327
327
  const m = "No wallets available";
328
328
  throw Z(m), new Error(m);
329
329
  }
330
- F(!0);
330
+ j(!0);
331
331
  }
332
332
  } catch (m) {
333
333
  S(null);
@@ -335,22 +335,22 @@ function Fe({
335
335
  n().error("[CryptoButton] Connection error:", U), Z(U, p?.adapter.name);
336
336
  }
337
337
  }
338
- }, [u, p, w, y, s, c, ce, G, Q, E, C, b, i, j, X, I]), ye = Y(() => y && s ? `crypto-cart-${s.map((e) => e.resource).join("-")}` : `crypto-${c || "unknown"}`, [y, s, c]), Pe = Y(
339
- () => ze(ye, de, {
338
+ }, [u, p, w, y, s, c, ce, G, Q, E, C, b, i, N, L, I]), ye = Y(() => y && s ? `crypto-cart-${s.map((e) => e.resource).join("-")}` : `crypto-${c || "unknown"}`, [y, s, c]), Pe = Y(
339
+ () => Me(ye, de, {
340
340
  cooldownMs: 200,
341
341
  deduplicationWindowMs: 0
342
342
  // MUST be 0 for crypto - each payment needs fresh transaction
343
343
  }),
344
344
  [ye, de]
345
- ), me = W === "loading", xe = q || me || K || !!j, ve = me ? f("ui.processing") : A, Se = P(async () => {
345
+ ), me = W === "loading", xe = q || me || X || !!N, ve = me ? f("ui.processing") : O, Se = P(async () => {
346
346
  try {
347
- J(!1), u && await v(), z(null), F(!0);
347
+ J(!1), u && await v(), M(null), j(!0);
348
348
  } catch (e) {
349
349
  n().error("Failed to change wallet:", e);
350
350
  }
351
- }, [u, v, z]), ke = P((e) => {
352
- n().debug("[CryptoButton] Wallet clicked:", e), F(!1), z(e), J(!0), n().debug("[CryptoButton] Wallet selected, useEffect will auto-connect");
353
- }, [z]), Be = P(async () => {
351
+ }, [u, v, M]), ke = P((e) => {
352
+ n().debug("[CryptoButton] Wallet clicked:", e), j(!1), M(e), J(!0), n().debug("[CryptoButton] Wallet selected, useEffect will auto-connect");
353
+ }, [M]), Be = P(async () => {
354
354
  try {
355
355
  if (await v(), S(null), typeof window < "u" && window.localStorage)
356
356
  try {
@@ -362,7 +362,7 @@ function Fe({
362
362
  n().error("Failed to disconnect wallet:", e);
363
363
  }
364
364
  }, [v]);
365
- return /* @__PURE__ */ O("div", { className: r.unstyled ? k : `${r.className} cedros-theme__crypto-button ${k || ""}`, style: r.unstyled ? {} : r.style, children: [
365
+ return /* @__PURE__ */ A("div", { className: r.unstyled ? k : `${r.className} cedros-theme__crypto-button ${k || ""}`, style: r.unstyled ? {} : r.style, children: [
366
366
  /* @__PURE__ */ h(
367
367
  "button",
368
368
  {
@@ -391,9 +391,9 @@ function Fe({
391
391
  padding: "1rem"
392
392
  },
393
393
  onClick: () => {
394
- F(!1), S(null);
394
+ j(!1), S(null);
395
395
  },
396
- children: /* @__PURE__ */ O(
396
+ children: /* @__PURE__ */ A(
397
397
  "div",
398
398
  {
399
399
  className: "cedros-modal-content",
@@ -408,7 +408,7 @@ function Fe({
408
408
  },
409
409
  onClick: (e) => e.stopPropagation(),
410
410
  children: [
411
- /* @__PURE__ */ O(
411
+ /* @__PURE__ */ A(
412
412
  "div",
413
413
  {
414
414
  style: {
@@ -434,9 +434,9 @@ function Fe({
434
434
  "button",
435
435
  {
436
436
  onClick: () => {
437
- F(!1), S(null);
437
+ j(!1), S(null);
438
438
  },
439
- style: Me(r.tokens.surfaceText),
439
+ style: ze(r.tokens.surfaceText),
440
440
  "aria-label": "Close modal",
441
441
  type: "button",
442
442
  children: "×"
@@ -445,7 +445,7 @@ function Fe({
445
445
  ]
446
446
  }
447
447
  ),
448
- /* @__PURE__ */ h("div", { style: { display: "flex", flexDirection: "column", gap: "0.75rem" }, children: Q.map((e) => /* @__PURE__ */ O(
448
+ /* @__PURE__ */ h("div", { style: { display: "flex", flexDirection: "column", gap: "0.75rem" }, children: Q.map((e) => /* @__PURE__ */ A(
449
449
  "button",
450
450
  {
451
451
  onClick: () => ke(e.adapter.name),
@@ -483,7 +483,7 @@ function Fe({
483
483
  )
484
484
  }
485
485
  ),
486
- u && !x && !ie && /* @__PURE__ */ O("div", { style: {
486
+ u && !x && !ie && /* @__PURE__ */ A("div", { style: {
487
487
  display: "flex",
488
488
  justifyContent: "space-between",
489
489
  marginTop: "0.5rem",
@@ -533,10 +533,10 @@ function Fe({
533
533
  }
534
534
  const Ge = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
535
535
  __proto__: null,
536
- CryptoButton: Fe
536
+ CryptoButton: je
537
537
  }, Symbol.toStringTag, { value: "Module" }));
538
538
  export {
539
- Fe as C,
539
+ je as C,
540
540
  Ge as a,
541
541
  $e as u
542
542
  };
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),c=require("react"),d=require("./index-IZ4WcMd7.js");function R({serverUrl:h,apiKey:o,pageSize:g=20,authManager:r}){const[u,N]=c.useState([]),[Q,w]=c.useState(!0),[S,f]=c.useState(!1),[p,A]=c.useState(null),[F,C]=c.useState(!1),[x,P]=c.useState(""),[v,O]=c.useState("all"),[q,b]=c.useState(null),[$,j]=c.useState(null),[n,l]=c.useState({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),_=c.useCallback(async()=>{w(!0);try{j(null);let s;const t=`/admin/faqs?limit=${g}`;if(r?.isAuthenticated())s=await r.fetchWithAuth(t);else{const i={"Content-Type":"application/json"};o&&(i["X-API-Key"]=o);const a=await fetch(`${h}${t}`,{headers:i});if(!a.ok)throw new Error(`Failed to fetch FAQs: ${a.status}`);s=await a.json()}N(s.faqs||[])}catch{N([]),j("Failed to load FAQs")}finally{w(!1)}},[h,o,g,r]);c.useEffect(()=>{_()},[_]);const E=async s=>{if(s.preventDefault(),!(!n.question.trim()||!n.answer.trim())){C(!0);try{const t=n.keywordsCsv.split(",").map(a=>a.trim().toLowerCase()).filter(Boolean),i={question:n.question.trim(),answer:n.answer.trim(),keywords:t,active:n.active,useInChat:n.useInChat,displayOnPage:n.displayOnPage};if(p){const a=`/admin/faqs/${p.id}`;if(r?.isAuthenticated())await r.fetchWithAuth(a,{method:"PUT",body:JSON.stringify(i)});else{const m={"Content-Type":"application/json"};o&&(m["X-API-Key"]=o);const I=await fetch(`${h}${a}`,{method:"PUT",headers:m,body:JSON.stringify(i)});if(!I.ok)throw new Error(`Failed to update FAQ: ${I.status}`)}}else if(r?.isAuthenticated())await r.fetchWithAuth("/admin/faqs",{method:"POST",body:JSON.stringify(i)});else{const a={"Content-Type":"application/json"};o&&(a["X-API-Key"]=o);const m=await fetch(`${h}/admin/faqs`,{method:"POST",headers:a,body:JSON.stringify(i)});if(!m.ok)throw new Error(`Failed to create FAQ: ${m.status}`)}y(),_()}catch{j(p?"Failed to update FAQ":"Failed to create FAQ")}finally{C(!1)}}},T=async s=>{try{const t=`/admin/faqs/${s}`;if(r?.isAuthenticated())await r.fetchWithAuth(t,{method:"DELETE"});else{const i={"Content-Type":"application/json"};o&&(i["X-API-Key"]=o);const a=await fetch(`${h}${t}`,{method:"DELETE",headers:i});if(!a.ok)throw new Error(`Failed to delete FAQ: ${a.status}`)}_()}catch{j("Failed to delete FAQ")}b(null)},D=async s=>{try{const t=`/admin/faqs/${s.id}`,i={...s,active:!s.active};if(r?.isAuthenticated())await r.fetchWithAuth(t,{method:"PUT",body:JSON.stringify(i)});else{const a={"Content-Type":"application/json"};o&&(a["X-API-Key"]=o);const m=await fetch(`${h}${t}`,{method:"PUT",headers:a,body:JSON.stringify(i)});if(!m.ok)throw new Error(`Failed to update FAQ: ${m.status}`)}_()}catch{j("Failed to update FAQ status")}},y=()=>{l({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),A(null),f(!1)},L=s=>{l({question:s.question,answer:s.answer,keywordsCsv:s.keywords.join(", "),active:s.active,useInChat:s.useInChat??!0,displayOnPage:s.displayOnPage??!0}),A(s),f(!0)},W=u.length,B=u.filter(s=>s.active).length,J=u.filter(s=>s.active&&s.useInChat).length,X=u.filter(s=>s.active&&s.displayOnPage).length,k=c.useMemo(()=>u.filter(s=>{if(v==="active"&&!s.active||v==="inactive"&&s.active)return!1;if(x){const t=x.toLowerCase();return s.question.toLowerCase().includes(t)||s.answer.toLowerCase().includes(t)||s.keywords.some(i=>i.includes(t))}return!0}),[u,v,x]);return e.jsxs("div",{className:"cedros-admin__faqs",children:[e.jsx(d.ErrorBanner,{message:$,onRetry:_}),e.jsx(d.StatsBar,{stats:[{label:"Total FAQs",value:W},{label:"Active",value:B,variant:"success"},{label:"In Chat",value:J},{label:"On Page",value:X}]}),e.jsxs("div",{className:"cedros-admin__section",children:[e.jsxs("div",{className:"cedros-admin__section-header",children:[e.jsxs("div",{className:"cedros-admin__section-header-left",children:[e.jsx("h3",{className:"cedros-admin__section-title",children:"Knowledge Base"}),e.jsx("p",{className:"cedros-admin__section-subtitle",children:"Manage FAQs for the AI chat assistant and public FAQ page."})]}),e.jsx("div",{className:"cedros-admin__section-header-right",children:e.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary",onClick:()=>{y(),f(!0)},children:[d.Icons.plus," Add FAQ"]})})]}),e.jsxs("div",{className:"cedros-admin__filters",style:{display:"flex",gap:"1rem",marginBottom:"1rem"},children:[e.jsx("input",{type:"text",placeholder:"Search FAQs...",value:x,onChange:s=>P(s.target.value),className:"cedros-admin__input",style:{flex:1,maxWidth:300}}),e.jsxs("select",{value:v,onChange:s=>O(s.target.value),className:"cedros-admin__select",children:[e.jsx("option",{value:"all",children:"All Status"}),e.jsx("option",{value:"active",children:"Active Only"}),e.jsx("option",{value:"inactive",children:"Inactive Only"})]})]}),S&&e.jsx("div",{className:"cedros-admin__form-container",style:{marginBottom:"1.5rem"},children:e.jsxs("form",{onSubmit:E,className:"cedros-admin__form",children:[e.jsxs("div",{className:"cedros-admin__form-header",children:[e.jsx("h4",{children:p?"Edit FAQ":"Add New FAQ"}),e.jsx("button",{type:"button",className:"cedros-admin__button--icon",onClick:y,children:d.Icons.close})]}),e.jsxs("div",{className:"cedros-admin__form-group",children:[e.jsx("label",{className:"cedros-admin__label",children:"Question *"}),e.jsx("input",{type:"text",value:n.question,onChange:s=>l(t=>({...t,question:s.target.value})),className:"cedros-admin__input",placeholder:"What is your return policy?",required:!0})]}),e.jsxs("div",{className:"cedros-admin__form-group",children:[e.jsx("label",{className:"cedros-admin__label",children:"Answer *"}),e.jsx("textarea",{value:n.answer,onChange:s=>l(t=>({...t,answer:s.target.value})),className:"cedros-admin__textarea",placeholder:"We accept returns within 30 days...",rows:4,required:!0}),e.jsx("span",{className:"cedros-admin__hint",children:"Supports markdown formatting."})]}),e.jsxs("div",{className:"cedros-admin__form-group",children:[e.jsx("label",{className:"cedros-admin__label",children:"Keywords"}),e.jsx("input",{type:"text",value:n.keywordsCsv,onChange:s=>l(t=>({...t,keywordsCsv:s.target.value})),className:"cedros-admin__input",placeholder:"returns, refund, policy"}),e.jsx("span",{className:"cedros-admin__hint",children:"Comma-separated keywords to help AI find this FAQ."})]}),e.jsxs("div",{className:"cedros-admin__form-group",children:[e.jsxs("label",{className:"cedros-admin__checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:n.active,onChange:s=>l(t=>({...t,active:s.target.checked}))}),e.jsx("span",{children:"Active"})]}),e.jsx("span",{className:"cedros-admin__hint",children:"Inactive FAQs won't appear anywhere."})]}),e.jsxs("div",{className:"cedros-admin__form-group",children:[e.jsx("label",{className:"cedros-admin__label",children:"Visibility"}),e.jsxs("div",{className:"cedros-admin__checkbox-group",children:[e.jsxs("label",{className:"cedros-admin__checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:n.useInChat,onChange:s=>l(t=>({...t,useInChat:s.target.checked}))}),e.jsx("span",{children:"Use in AI Chat"})]}),e.jsxs("label",{className:"cedros-admin__checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:n.displayOnPage,onChange:s=>l(t=>({...t,displayOnPage:s.target.checked}))}),e.jsx("span",{children:"Display on FAQ Page"})]})]}),e.jsx("span",{className:"cedros-admin__hint",children:"Choose where this FAQ should appear."})]}),e.jsxs("div",{className:"cedros-admin__form-actions",children:[e.jsx("button",{type:"button",className:"cedros-admin__button",onClick:y,children:"Cancel"}),e.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:F||!n.question.trim()||!n.answer.trim(),children:F?d.Icons.loading:p?"Update FAQ":"Create FAQ"})]})]})}),Q?e.jsxs("div",{className:"cedros-admin__loading",children:[d.Icons.loading,e.jsx("span",{children:"Loading FAQs..."})]}):k.length===0?e.jsx("div",{className:"cedros-admin__empty",children:e.jsx("p",{children:x||v!=="all"?"No FAQs match your filters.":"No FAQs yet. Add one to get started."})}):e.jsx("div",{className:"cedros-admin__faq-list",children:k.map(s=>e.jsxs("div",{className:`cedros-admin__faq-item ${s.active?"":"cedros-admin__faq-item--inactive"}`,children:[e.jsxs("div",{className:"cedros-admin__faq-content",children:[e.jsxs("div",{className:"cedros-admin__faq-question",children:[e.jsx("span",{className:`cedros-admin__status-dot ${s.active?"cedros-admin__status-dot--active":"cedros-admin__status-dot--inactive"}`}),s.question]}),e.jsx("div",{className:"cedros-admin__faq-answer",children:s.answer}),e.jsxs("div",{className:"cedros-admin__faq-meta",children:[s.keywords.length>0&&e.jsx("div",{className:"cedros-admin__faq-keywords",children:s.keywords.map(t=>e.jsx("span",{className:"cedros-admin__tag",children:t},t))}),e.jsxs("div",{className:"cedros-admin__faq-visibility",children:[s.useInChat&&e.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--chat",title:"Used in AI Chat",children:[d.Icons.chat," Chat"]}),s.displayOnPage&&e.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--page",title:"Displayed on FAQ Page",children:[d.Icons.globe," Page"]})]})]})]}),e.jsxs("div",{className:"cedros-admin__faq-actions",children:[e.jsx("button",{className:"cedros-admin__button--icon",onClick:()=>D(s),title:s.active?"Deactivate":"Activate",children:s.active?d.Icons.eyeOff:d.Icons.eye}),e.jsx("button",{className:"cedros-admin__button--icon",onClick:()=>L(s),title:"Edit",children:d.Icons.edit}),e.jsx("button",{className:"cedros-admin__button--icon cedros-admin__btn--danger",onClick:()=>b(s.id),title:"Delete",children:d.Icons.trash})]}),q===s.id&&e.jsx("div",{className:"cedros-admin__confirm-overlay",children:e.jsxs("div",{className:"cedros-admin__confirm-dialog",children:[e.jsx("p",{children:"Delete this FAQ?"}),e.jsxs("div",{className:"cedros-admin__confirm-actions",children:[e.jsx("button",{className:"cedros-admin__button",onClick:()=>b(null),children:"Cancel"}),e.jsx("button",{className:"cedros-admin__button cedros-admin__button--danger",onClick:()=>T(s.id),children:"Delete"})]})]})})]},s.id))})]})]})}exports.FAQSection=R;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),c=require("react"),d=require("./index-OaWkrl0G.js");function R({serverUrl:h,apiKey:o,pageSize:g=20,authManager:r}){const[u,N]=c.useState([]),[Q,w]=c.useState(!0),[S,f]=c.useState(!1),[p,A]=c.useState(null),[F,C]=c.useState(!1),[x,P]=c.useState(""),[v,O]=c.useState("all"),[q,b]=c.useState(null),[$,j]=c.useState(null),[n,l]=c.useState({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),_=c.useCallback(async()=>{w(!0);try{j(null);let s;const t=`/admin/faqs?limit=${g}`;if(r?.isAuthenticated())s=await r.fetchWithAuth(t);else{const i={"Content-Type":"application/json"};o&&(i["X-API-Key"]=o);const a=await fetch(`${h}${t}`,{headers:i});if(!a.ok)throw new Error(`Failed to fetch FAQs: ${a.status}`);s=await a.json()}N(s.faqs||[])}catch{N([]),j("Failed to load FAQs")}finally{w(!1)}},[h,o,g,r]);c.useEffect(()=>{_()},[_]);const E=async s=>{if(s.preventDefault(),!(!n.question.trim()||!n.answer.trim())){C(!0);try{const t=n.keywordsCsv.split(",").map(a=>a.trim().toLowerCase()).filter(Boolean),i={question:n.question.trim(),answer:n.answer.trim(),keywords:t,active:n.active,useInChat:n.useInChat,displayOnPage:n.displayOnPage};if(p){const a=`/admin/faqs/${p.id}`;if(r?.isAuthenticated())await r.fetchWithAuth(a,{method:"PUT",body:JSON.stringify(i)});else{const m={"Content-Type":"application/json"};o&&(m["X-API-Key"]=o);const I=await fetch(`${h}${a}`,{method:"PUT",headers:m,body:JSON.stringify(i)});if(!I.ok)throw new Error(`Failed to update FAQ: ${I.status}`)}}else if(r?.isAuthenticated())await r.fetchWithAuth("/admin/faqs",{method:"POST",body:JSON.stringify(i)});else{const a={"Content-Type":"application/json"};o&&(a["X-API-Key"]=o);const m=await fetch(`${h}/admin/faqs`,{method:"POST",headers:a,body:JSON.stringify(i)});if(!m.ok)throw new Error(`Failed to create FAQ: ${m.status}`)}y(),_()}catch{j(p?"Failed to update FAQ":"Failed to create FAQ")}finally{C(!1)}}},T=async s=>{try{const t=`/admin/faqs/${s}`;if(r?.isAuthenticated())await r.fetchWithAuth(t,{method:"DELETE"});else{const i={"Content-Type":"application/json"};o&&(i["X-API-Key"]=o);const a=await fetch(`${h}${t}`,{method:"DELETE",headers:i});if(!a.ok)throw new Error(`Failed to delete FAQ: ${a.status}`)}_()}catch{j("Failed to delete FAQ")}b(null)},D=async s=>{try{const t=`/admin/faqs/${s.id}`,i={...s,active:!s.active};if(r?.isAuthenticated())await r.fetchWithAuth(t,{method:"PUT",body:JSON.stringify(i)});else{const a={"Content-Type":"application/json"};o&&(a["X-API-Key"]=o);const m=await fetch(`${h}${t}`,{method:"PUT",headers:a,body:JSON.stringify(i)});if(!m.ok)throw new Error(`Failed to update FAQ: ${m.status}`)}_()}catch{j("Failed to update FAQ status")}},y=()=>{l({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),A(null),f(!1)},L=s=>{l({question:s.question,answer:s.answer,keywordsCsv:s.keywords.join(", "),active:s.active,useInChat:s.useInChat??!0,displayOnPage:s.displayOnPage??!0}),A(s),f(!0)},W=u.length,B=u.filter(s=>s.active).length,J=u.filter(s=>s.active&&s.useInChat).length,X=u.filter(s=>s.active&&s.displayOnPage).length,k=c.useMemo(()=>u.filter(s=>{if(v==="active"&&!s.active||v==="inactive"&&s.active)return!1;if(x){const t=x.toLowerCase();return s.question.toLowerCase().includes(t)||s.answer.toLowerCase().includes(t)||s.keywords.some(i=>i.includes(t))}return!0}),[u,v,x]);return e.jsxs("div",{className:"cedros-admin__faqs",children:[e.jsx(d.ErrorBanner,{message:$,onRetry:_}),e.jsx(d.StatsBar,{stats:[{label:"Total FAQs",value:W},{label:"Active",value:B,variant:"success"},{label:"In Chat",value:J},{label:"On Page",value:X}]}),e.jsxs("div",{className:"cedros-admin__section",children:[e.jsxs("div",{className:"cedros-admin__section-header",children:[e.jsxs("div",{className:"cedros-admin__section-header-left",children:[e.jsx("h3",{className:"cedros-admin__section-title",children:"Knowledge Base"}),e.jsx("p",{className:"cedros-admin__section-subtitle",children:"Manage FAQs for the AI chat assistant and public FAQ page."})]}),e.jsx("div",{className:"cedros-admin__section-header-right",children:e.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary",onClick:()=>{y(),f(!0)},children:[d.Icons.plus," Add FAQ"]})})]}),e.jsxs("div",{className:"cedros-admin__filters",style:{display:"flex",gap:"1rem",marginBottom:"1rem"},children:[e.jsx("input",{type:"text",placeholder:"Search FAQs...",value:x,onChange:s=>P(s.target.value),className:"cedros-admin__input",style:{flex:1,maxWidth:300}}),e.jsxs("select",{value:v,onChange:s=>O(s.target.value),className:"cedros-admin__select",children:[e.jsx("option",{value:"all",children:"All Status"}),e.jsx("option",{value:"active",children:"Active Only"}),e.jsx("option",{value:"inactive",children:"Inactive Only"})]})]}),S&&e.jsx("div",{className:"cedros-admin__form-container",style:{marginBottom:"1.5rem"},children:e.jsxs("form",{onSubmit:E,className:"cedros-admin__form",children:[e.jsxs("div",{className:"cedros-admin__form-header",children:[e.jsx("h4",{children:p?"Edit FAQ":"Add New FAQ"}),e.jsx("button",{type:"button",className:"cedros-admin__button--icon",onClick:y,children:d.Icons.close})]}),e.jsxs("div",{className:"cedros-admin__form-group",children:[e.jsx("label",{className:"cedros-admin__label",children:"Question *"}),e.jsx("input",{type:"text",value:n.question,onChange:s=>l(t=>({...t,question:s.target.value})),className:"cedros-admin__input",placeholder:"What is your return policy?",required:!0})]}),e.jsxs("div",{className:"cedros-admin__form-group",children:[e.jsx("label",{className:"cedros-admin__label",children:"Answer *"}),e.jsx("textarea",{value:n.answer,onChange:s=>l(t=>({...t,answer:s.target.value})),className:"cedros-admin__textarea",placeholder:"We accept returns within 30 days...",rows:4,required:!0}),e.jsx("span",{className:"cedros-admin__hint",children:"Supports markdown formatting."})]}),e.jsxs("div",{className:"cedros-admin__form-group",children:[e.jsx("label",{className:"cedros-admin__label",children:"Keywords"}),e.jsx("input",{type:"text",value:n.keywordsCsv,onChange:s=>l(t=>({...t,keywordsCsv:s.target.value})),className:"cedros-admin__input",placeholder:"returns, refund, policy"}),e.jsx("span",{className:"cedros-admin__hint",children:"Comma-separated keywords to help AI find this FAQ."})]}),e.jsxs("div",{className:"cedros-admin__form-group",children:[e.jsxs("label",{className:"cedros-admin__checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:n.active,onChange:s=>l(t=>({...t,active:s.target.checked}))}),e.jsx("span",{children:"Active"})]}),e.jsx("span",{className:"cedros-admin__hint",children:"Inactive FAQs won't appear anywhere."})]}),e.jsxs("div",{className:"cedros-admin__form-group",children:[e.jsx("label",{className:"cedros-admin__label",children:"Visibility"}),e.jsxs("div",{className:"cedros-admin__checkbox-group",children:[e.jsxs("label",{className:"cedros-admin__checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:n.useInChat,onChange:s=>l(t=>({...t,useInChat:s.target.checked}))}),e.jsx("span",{children:"Use in AI Chat"})]}),e.jsxs("label",{className:"cedros-admin__checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:n.displayOnPage,onChange:s=>l(t=>({...t,displayOnPage:s.target.checked}))}),e.jsx("span",{children:"Display on FAQ Page"})]})]}),e.jsx("span",{className:"cedros-admin__hint",children:"Choose where this FAQ should appear."})]}),e.jsxs("div",{className:"cedros-admin__form-actions",children:[e.jsx("button",{type:"button",className:"cedros-admin__button",onClick:y,children:"Cancel"}),e.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:F||!n.question.trim()||!n.answer.trim(),children:F?d.Icons.loading:p?"Update FAQ":"Create FAQ"})]})]})}),Q?e.jsxs("div",{className:"cedros-admin__loading",children:[d.Icons.loading,e.jsx("span",{children:"Loading FAQs..."})]}):k.length===0?e.jsx("div",{className:"cedros-admin__empty",children:e.jsx("p",{children:x||v!=="all"?"No FAQs match your filters.":"No FAQs yet. Add one to get started."})}):e.jsx("div",{className:"cedros-admin__faq-list",children:k.map(s=>e.jsxs("div",{className:`cedros-admin__faq-item ${s.active?"":"cedros-admin__faq-item--inactive"}`,children:[e.jsxs("div",{className:"cedros-admin__faq-content",children:[e.jsxs("div",{className:"cedros-admin__faq-question",children:[e.jsx("span",{className:`cedros-admin__status-dot ${s.active?"cedros-admin__status-dot--active":"cedros-admin__status-dot--inactive"}`}),s.question]}),e.jsx("div",{className:"cedros-admin__faq-answer",children:s.answer}),e.jsxs("div",{className:"cedros-admin__faq-meta",children:[s.keywords.length>0&&e.jsx("div",{className:"cedros-admin__faq-keywords",children:s.keywords.map(t=>e.jsx("span",{className:"cedros-admin__tag",children:t},t))}),e.jsxs("div",{className:"cedros-admin__faq-visibility",children:[s.useInChat&&e.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--chat",title:"Used in AI Chat",children:[d.Icons.chat," Chat"]}),s.displayOnPage&&e.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--page",title:"Displayed on FAQ Page",children:[d.Icons.globe," Page"]})]})]})]}),e.jsxs("div",{className:"cedros-admin__faq-actions",children:[e.jsx("button",{className:"cedros-admin__button--icon",onClick:()=>D(s),title:s.active?"Deactivate":"Activate",children:s.active?d.Icons.eyeOff:d.Icons.eye}),e.jsx("button",{className:"cedros-admin__button--icon",onClick:()=>L(s),title:"Edit",children:d.Icons.edit}),e.jsx("button",{className:"cedros-admin__button--icon cedros-admin__btn--danger",onClick:()=>b(s.id),title:"Delete",children:d.Icons.trash})]}),q===s.id&&e.jsx("div",{className:"cedros-admin__confirm-overlay",children:e.jsxs("div",{className:"cedros-admin__confirm-dialog",children:[e.jsx("p",{children:"Delete this FAQ?"}),e.jsxs("div",{className:"cedros-admin__confirm-actions",children:[e.jsx("button",{className:"cedros-admin__button",onClick:()=>b(null),children:"Cancel"}),e.jsx("button",{className:"cedros-admin__button cedros-admin__button--danger",onClick:()=>T(s.id),children:"Delete"})]})]})})]},s.id))})]})]})}exports.FAQSection=R;
@@ -1,6 +1,6 @@
1
1
  import { jsxs as a, jsx as t } from "react/jsx-runtime";
2
2
  import { useState as r, useCallback as R, useEffect as V, useMemo as G } from "react";
3
- import { E as H, f as Y, I as l } from "./index-CufXF9Yd.mjs";
3
+ import { E as H, g as Y, I as l } from "./index-BHF82XBB.mjs";
4
4
  function M({ serverUrl: u, apiKey: d, pageSize: A = 20, authManager: o }) {
5
5
  const [_, F] = r([]), [E, C] = r(!0), [S, N] = r(!1), [v, k] = r(null), [Q, I] = r(!1), [y, $] = r(""), [f, x] = r("all"), [q, w] = r(null), [T, b] = r(null), [n, m] = r({
6
6
  question: "",
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),l=require("react"),y=require("./index-IZ4WcMd7.js"),S=require("./Toggle-CsPSF8Dr.js"),q=require("./useAutosave-B2p6iwh8.js"),z=require("./AutosaveIndicator-C-CH-obR.js"),p={mailgun:{label:"Mailgun",host:"smtp.mailgun.org",username:"",credentialLabel:"SMTP Password",showUsername:!0,usernameEqualsPassword:!1},sendgrid:{label:"SendGrid",host:"smtp.sendgrid.net",username:"apikey",credentialLabel:"API Key",showUsername:!1,usernameEqualsPassword:!1},postmark:{label:"Postmark",host:"smtp.postmarkapp.com",username:"",credentialLabel:"Server API Token",showUsername:!1,usernameEqualsPassword:!0},ses:{label:"AWS SES",host:"email-smtp.us-east-1.amazonaws.com",username:"",credentialLabel:"SMTP Password",showUsername:!0,usernameEqualsPassword:!1},resend:{label:"Resend",host:"smtp.resend.com",username:"resend",credentialLabel:"API Key",showUsername:!1,usernameEqualsPassword:!1},custom:{label:"Custom SMTP",host:"",username:"",credentialLabel:"SMTP Password",showUsername:!0,usernameEqualsPassword:!1}};function R(c){if(!c)return"custom";for(const[d,n]of Object.entries(p))if(n.host&&c===n.host)return d;return"custom"}const v={email_enabled:!1,email_provider:"custom",smtp_host:"",smtp_port:587,smtp_username:"",smtp_password:"",from_email:"",from_name:"",webhook_enabled:!1,webhook_url:"",webhook_secret:"",webhook_timeout:30};function W({serverUrl:c,apiKey:d,authManager:n}){const[m,b]=l.useState("messages"),[a,h]=l.useState(v),[N,k]=l.useState(!0),[C,E]=l.useState(!0),[P,f]=l.useState(null),[_,j]=l.useState(new Set),g=l.useCallback(async()=>{try{f(null);let s;const t="/admin/config/messaging";if(n?.isAuthenticated())s=await n.fetchWithAuth(t);else{const o={"Content-Type":"application/json"};d&&(o["X-API-Key"]=d);const u=await fetch(`${c}${t}`,{headers:o});if(!u.ok)throw new Error(`Failed to fetch: ${u.status}`);s=await u.json()}const i={...v,...s.config};i.email_provider||(i.email_provider=R(i.smtp_host)),h(i)}catch{h(v),f("Could not load saved settings. Showing defaults.")}finally{k(!1),setTimeout(()=>E(!1),100)}},[c,d,n]);l.useEffect(()=>{g()},[g]);const T=l.useCallback(async s=>{const t="/admin/config/messaging",i={...s};_.has("smtp_password")||delete i.smtp_password,_.has("webhook_secret")||delete i.webhook_secret;const o=JSON.stringify({config:i});try{if(n?.isAuthenticated())await n.fetchWithAuth(t,{method:"PUT",body:o});else{const u={"Content-Type":"application/json"};d&&(u["X-API-Key"]=d);const w=await fetch(`${c}${t}`,{method:"PUT",headers:u,body:o});if(!w.ok)throw new Error(`Failed to save: ${w.status}`)}}catch{throw f("Failed to save messaging settings"),new Error("Save failed")}},[c,d,n,_]),{status:A,error:I}=q.useAutosave({data:a,onSave:T,debounceMs:1500,enabled:!C}),r=(s,t)=>{(s==="smtp_password"||s==="webhook_secret")&&j(i=>new Set(i).add(s)),h(i=>({...i,[s]:t}))},L=s=>{const t=p[s];h(i=>({...i,email_provider:s,smtp_host:t.host||i.smtp_host,smtp_port:587,smtp_username:t.username||(t.showUsername?i.smtp_username:"")}))},M=s=>{const t=a.email_provider||"custom",i=p[t];j(o=>new Set(o).add("smtp_password")),i.usernameEqualsPassword?h(o=>({...o,smtp_password:s,smtp_username:s})):h(o=>({...o,smtp_password:s}))},x=p[a.email_provider||"custom"]??p.custom;return N?e.jsxs("div",{className:"cedros-admin__messaging-settings",children:[e.jsxs("div",{className:"cedros-admin__page-header",children:[e.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),e.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),e.jsxs("div",{className:"cedros-admin__loading",style:{marginTop:"1rem"},children:[y.Icons.loading," Loading message settings..."]})]}):e.jsxs("div",{className:"cedros-admin__messaging-settings",children:[e.jsxs("div",{className:"cedros-admin__page-header",children:[e.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),e.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),e.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[e.jsx("button",{type:"button",className:`cedros-admin__tab ${m==="messages"?"cedros-admin__tab--active":""}`,onClick:()=>b("messages"),children:"Messages"}),e.jsx("button",{type:"button",className:`cedros-admin__tab ${m==="email"?"cedros-admin__tab--active":""}`,onClick:()=>b("email"),children:"Email"}),e.jsx("button",{type:"button",className:`cedros-admin__tab ${m==="webhooks"?"cedros-admin__tab--active":""}`,onClick:()=>b("webhooks"),children:"Webhooks"}),e.jsx("div",{style:{flex:1}}),e.jsx(z.AutosaveIndicator,{status:A,error:I})]}),e.jsx(y.ErrorBanner,{message:P,onRetry:g}),e.jsxs("div",{className:"cedros-admin__tab-content",style:{marginTop:"1rem"},children:[m==="messages"&&e.jsxs("div",{className:"cedros-admin__section",children:[e.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Enable or disable notification types. Configure the delivery settings in the Email or Webhooks tab."}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:"0.5rem"},children:[e.jsx(S.Toggle,{checked:a.email_enabled,onChange:s=>r("email_enabled",s)}),e.jsxs("div",{style:{flex:1},children:[e.jsx("div",{style:{fontWeight:500},children:"Email Confirmation"}),e.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8125rem",opacity:.6},children:"Send order confirmation emails to customers after successful purchase."}),e.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.75rem",opacity:.5},children:"Requires Email configuration"})]})]}),e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:"0.5rem"},children:[e.jsx(S.Toggle,{checked:a.webhook_enabled,onChange:s=>r("webhook_enabled",s)}),e.jsxs("div",{style:{flex:1},children:[e.jsx("div",{style:{fontWeight:500},children:"Admin Purchase Notification"}),e.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8125rem",opacity:.6},children:"Send webhook notifications to your server when a purchase is completed."}),e.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.75rem",opacity:.5},children:"Requires Webhook configuration"})]})]})]})]}),m==="email"&&e.jsxs("div",{className:"cedros-admin__section",children:[e.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Select your email service provider for automatic configuration."}),!a.email_enabled&&e.jsx("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #fef3c7)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-warning, #f59e0b)",fontSize:"0.875rem"},children:"Email notifications are disabled. Enable them in the Messages tab."}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",opacity:a.email_enabled?1:.5},children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Email Provider"}),e.jsx("select",{className:"cedros-admin__input",value:a.email_provider||"custom",onChange:s=>L(s.target.value),disabled:!a.email_enabled,children:Object.entries(p).map(([s,{label:t}])=>e.jsx("option",{value:s,children:t},s))})]}),a.email_provider==="custom"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Host"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:a.smtp_host,onChange:s=>r("smtp_host",s.target.value),placeholder:"smtp.example.com",disabled:!a.email_enabled})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Port"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:a.smtp_port,onChange:s=>r("smtp_port",parseInt(s.target.value)||587),placeholder:"587",disabled:!a.email_enabled,style:{maxWidth:120}}),e.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.75rem",opacity:.6},children:"Common: 587 (TLS), 465 (SSL), 25 (unencrypted)."})]})]}),x.showUsername&&e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Username"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:a.smtp_username,onChange:s=>r("smtp_username",s.target.value),placeholder:a.email_provider==="mailgun"?"postmaster@your-domain.com":"username",disabled:!a.email_enabled})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:x.credentialLabel}),e.jsx("input",{type:"password",className:"cedros-admin__input",value:_.has("smtp_password")?a.smtp_password:"",onChange:s=>M(s.target.value),placeholder:a.smtp_password?"••••••••":`Enter ${x.credentialLabel.toLowerCase()}`,disabled:!a.email_enabled})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"From Email"}),e.jsx("input",{type:"email",className:"cedros-admin__input",value:a.from_email,onChange:s=>r("from_email",s.target.value),placeholder:"noreply@example.com",disabled:!a.email_enabled}),e.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.75rem",opacity:.6},children:"Default sender email address."})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"From Name"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:a.from_name,onChange:s=>r("from_name",s.target.value),placeholder:"Your Store",disabled:!a.email_enabled}),e.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.75rem",opacity:.6},children:"Default sender display name."})]})]})]}),m==="webhooks"&&e.jsxs("div",{className:"cedros-admin__section",children:[e.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Configure webhook endpoint for receiving purchase notifications."}),!a.webhook_enabled&&e.jsx("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #fef3c7)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-warning, #f59e0b)",fontSize:"0.875rem"},children:"Webhook notifications are disabled. Enable them in the Messages tab."}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",opacity:a.webhook_enabled?1:.5},children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Webhook URL"}),e.jsx("input",{type:"url",className:"cedros-admin__input",value:a.webhook_url,onChange:s=>r("webhook_url",s.target.value),placeholder:"https://api.yoursite.com/webhooks/orders",disabled:!a.webhook_enabled})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Webhook Secret"}),e.jsx("input",{type:"password",className:"cedros-admin__input",value:_.has("webhook_secret")?a.webhook_secret:"",onChange:s=>r("webhook_secret",s.target.value),placeholder:a.webhook_secret?"••••••••":"Enter secret for HMAC-SHA256",disabled:!a.webhook_enabled}),e.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.75rem",opacity:.6},children:"Used for HMAC-SHA256 signature verification"})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Timeout (seconds)"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:a.webhook_timeout,onChange:s=>r("webhook_timeout",parseInt(s.target.value)||30),placeholder:"30",disabled:!a.webhook_enabled,style:{maxWidth:120}})]})]})]})]})]})}exports.MessagingSection=W;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),l=require("react"),y=require("./index-OaWkrl0G.js"),S=require("./Toggle-CsPSF8Dr.js"),q=require("./useAutosave-B2p6iwh8.js"),z=require("./AutosaveIndicator-CY_YHM1D.js"),p={mailgun:{label:"Mailgun",host:"smtp.mailgun.org",username:"",credentialLabel:"SMTP Password",showUsername:!0,usernameEqualsPassword:!1},sendgrid:{label:"SendGrid",host:"smtp.sendgrid.net",username:"apikey",credentialLabel:"API Key",showUsername:!1,usernameEqualsPassword:!1},postmark:{label:"Postmark",host:"smtp.postmarkapp.com",username:"",credentialLabel:"Server API Token",showUsername:!1,usernameEqualsPassword:!0},ses:{label:"AWS SES",host:"email-smtp.us-east-1.amazonaws.com",username:"",credentialLabel:"SMTP Password",showUsername:!0,usernameEqualsPassword:!1},resend:{label:"Resend",host:"smtp.resend.com",username:"resend",credentialLabel:"API Key",showUsername:!1,usernameEqualsPassword:!1},custom:{label:"Custom SMTP",host:"",username:"",credentialLabel:"SMTP Password",showUsername:!0,usernameEqualsPassword:!1}};function R(c){if(!c)return"custom";for(const[d,n]of Object.entries(p))if(n.host&&c===n.host)return d;return"custom"}const v={email_enabled:!1,email_provider:"custom",smtp_host:"",smtp_port:587,smtp_username:"",smtp_password:"",from_email:"",from_name:"",webhook_enabled:!1,webhook_url:"",webhook_secret:"",webhook_timeout:30};function W({serverUrl:c,apiKey:d,authManager:n}){const[m,b]=l.useState("messages"),[a,h]=l.useState(v),[N,k]=l.useState(!0),[C,E]=l.useState(!0),[P,f]=l.useState(null),[_,j]=l.useState(new Set),g=l.useCallback(async()=>{try{f(null);let s;const t="/admin/config/messaging";if(n?.isAuthenticated())s=await n.fetchWithAuth(t);else{const o={"Content-Type":"application/json"};d&&(o["X-API-Key"]=d);const u=await fetch(`${c}${t}`,{headers:o});if(!u.ok)throw new Error(`Failed to fetch: ${u.status}`);s=await u.json()}const i={...v,...s.config};i.email_provider||(i.email_provider=R(i.smtp_host)),h(i)}catch{h(v),f("Could not load saved settings. Showing defaults.")}finally{k(!1),setTimeout(()=>E(!1),100)}},[c,d,n]);l.useEffect(()=>{g()},[g]);const T=l.useCallback(async s=>{const t="/admin/config/messaging",i={...s};_.has("smtp_password")||delete i.smtp_password,_.has("webhook_secret")||delete i.webhook_secret;const o=JSON.stringify({config:i});try{if(n?.isAuthenticated())await n.fetchWithAuth(t,{method:"PUT",body:o});else{const u={"Content-Type":"application/json"};d&&(u["X-API-Key"]=d);const w=await fetch(`${c}${t}`,{method:"PUT",headers:u,body:o});if(!w.ok)throw new Error(`Failed to save: ${w.status}`)}}catch{throw f("Failed to save messaging settings"),new Error("Save failed")}},[c,d,n,_]),{status:A,error:I}=q.useAutosave({data:a,onSave:T,debounceMs:1500,enabled:!C}),r=(s,t)=>{(s==="smtp_password"||s==="webhook_secret")&&j(i=>new Set(i).add(s)),h(i=>({...i,[s]:t}))},L=s=>{const t=p[s];h(i=>({...i,email_provider:s,smtp_host:t.host||i.smtp_host,smtp_port:587,smtp_username:t.username||(t.showUsername?i.smtp_username:"")}))},M=s=>{const t=a.email_provider||"custom",i=p[t];j(o=>new Set(o).add("smtp_password")),i.usernameEqualsPassword?h(o=>({...o,smtp_password:s,smtp_username:s})):h(o=>({...o,smtp_password:s}))},x=p[a.email_provider||"custom"]??p.custom;return N?e.jsxs("div",{className:"cedros-admin__messaging-settings",children:[e.jsxs("div",{className:"cedros-admin__page-header",children:[e.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),e.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),e.jsxs("div",{className:"cedros-admin__loading",style:{marginTop:"1rem"},children:[y.Icons.loading," Loading message settings..."]})]}):e.jsxs("div",{className:"cedros-admin__messaging-settings",children:[e.jsxs("div",{className:"cedros-admin__page-header",children:[e.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),e.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),e.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[e.jsx("button",{type:"button",className:`cedros-admin__tab ${m==="messages"?"cedros-admin__tab--active":""}`,onClick:()=>b("messages"),children:"Messages"}),e.jsx("button",{type:"button",className:`cedros-admin__tab ${m==="email"?"cedros-admin__tab--active":""}`,onClick:()=>b("email"),children:"Email"}),e.jsx("button",{type:"button",className:`cedros-admin__tab ${m==="webhooks"?"cedros-admin__tab--active":""}`,onClick:()=>b("webhooks"),children:"Webhooks"}),e.jsx("div",{style:{flex:1}}),e.jsx(z.AutosaveIndicator,{status:A,error:I})]}),e.jsx(y.ErrorBanner,{message:P,onRetry:g}),e.jsxs("div",{className:"cedros-admin__tab-content",style:{marginTop:"1rem"},children:[m==="messages"&&e.jsxs("div",{className:"cedros-admin__section",children:[e.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Enable or disable notification types. Configure the delivery settings in the Email or Webhooks tab."}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:"0.5rem"},children:[e.jsx(S.Toggle,{checked:a.email_enabled,onChange:s=>r("email_enabled",s)}),e.jsxs("div",{style:{flex:1},children:[e.jsx("div",{style:{fontWeight:500},children:"Email Confirmation"}),e.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8125rem",opacity:.6},children:"Send order confirmation emails to customers after successful purchase."}),e.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.75rem",opacity:.5},children:"Requires Email configuration"})]})]}),e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:"0.5rem"},children:[e.jsx(S.Toggle,{checked:a.webhook_enabled,onChange:s=>r("webhook_enabled",s)}),e.jsxs("div",{style:{flex:1},children:[e.jsx("div",{style:{fontWeight:500},children:"Admin Purchase Notification"}),e.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8125rem",opacity:.6},children:"Send webhook notifications to your server when a purchase is completed."}),e.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.75rem",opacity:.5},children:"Requires Webhook configuration"})]})]})]})]}),m==="email"&&e.jsxs("div",{className:"cedros-admin__section",children:[e.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Select your email service provider for automatic configuration."}),!a.email_enabled&&e.jsx("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #fef3c7)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-warning, #f59e0b)",fontSize:"0.875rem"},children:"Email notifications are disabled. Enable them in the Messages tab."}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",opacity:a.email_enabled?1:.5},children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Email Provider"}),e.jsx("select",{className:"cedros-admin__input",value:a.email_provider||"custom",onChange:s=>L(s.target.value),disabled:!a.email_enabled,children:Object.entries(p).map(([s,{label:t}])=>e.jsx("option",{value:s,children:t},s))})]}),a.email_provider==="custom"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Host"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:a.smtp_host,onChange:s=>r("smtp_host",s.target.value),placeholder:"smtp.example.com",disabled:!a.email_enabled})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Port"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:a.smtp_port,onChange:s=>r("smtp_port",parseInt(s.target.value)||587),placeholder:"587",disabled:!a.email_enabled,style:{maxWidth:120}}),e.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.75rem",opacity:.6},children:"Common: 587 (TLS), 465 (SSL), 25 (unencrypted)."})]})]}),x.showUsername&&e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Username"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:a.smtp_username,onChange:s=>r("smtp_username",s.target.value),placeholder:a.email_provider==="mailgun"?"postmaster@your-domain.com":"username",disabled:!a.email_enabled})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:x.credentialLabel}),e.jsx("input",{type:"password",className:"cedros-admin__input",value:_.has("smtp_password")?a.smtp_password:"",onChange:s=>M(s.target.value),placeholder:a.smtp_password?"••••••••":`Enter ${x.credentialLabel.toLowerCase()}`,disabled:!a.email_enabled})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"From Email"}),e.jsx("input",{type:"email",className:"cedros-admin__input",value:a.from_email,onChange:s=>r("from_email",s.target.value),placeholder:"noreply@example.com",disabled:!a.email_enabled}),e.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.75rem",opacity:.6},children:"Default sender email address."})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"From Name"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:a.from_name,onChange:s=>r("from_name",s.target.value),placeholder:"Your Store",disabled:!a.email_enabled}),e.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.75rem",opacity:.6},children:"Default sender display name."})]})]})]}),m==="webhooks"&&e.jsxs("div",{className:"cedros-admin__section",children:[e.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Configure webhook endpoint for receiving purchase notifications."}),!a.webhook_enabled&&e.jsx("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #fef3c7)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-warning, #f59e0b)",fontSize:"0.875rem"},children:"Webhook notifications are disabled. Enable them in the Messages tab."}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",opacity:a.webhook_enabled?1:.5},children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Webhook URL"}),e.jsx("input",{type:"url",className:"cedros-admin__input",value:a.webhook_url,onChange:s=>r("webhook_url",s.target.value),placeholder:"https://api.yoursite.com/webhooks/orders",disabled:!a.webhook_enabled})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Webhook Secret"}),e.jsx("input",{type:"password",className:"cedros-admin__input",value:_.has("webhook_secret")?a.webhook_secret:"",onChange:s=>r("webhook_secret",s.target.value),placeholder:a.webhook_secret?"••••••••":"Enter secret for HMAC-SHA256",disabled:!a.webhook_enabled}),e.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.75rem",opacity:.6},children:"Used for HMAC-SHA256 signature verification"})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Timeout (seconds)"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:a.webhook_timeout,onChange:s=>r("webhook_timeout",parseInt(s.target.value)||30),placeholder:"30",disabled:!a.webhook_enabled,style:{maxWidth:120}})]})]})]})]})]})}exports.MessagingSection=W;
@@ -1,9 +1,9 @@
1
1
  import { jsxs as i, jsx as e, Fragment as R } from "react/jsx-runtime";
2
2
  import { useState as _, useCallback as k, useEffect as U } from "react";
3
- import { I as $, E as q } from "./index-CufXF9Yd.mjs";
3
+ import { I as $, E as q } from "./index-BHF82XBB.mjs";
4
4
  import { T as C } from "./Toggle-DAxIdpY4.mjs";
5
5
  import { u as F } from "./useAutosave-YwMqRzqy.mjs";
6
- import { A as j } from "./AutosaveIndicator-CWbb-VXf.mjs";
6
+ import { A as j } from "./AutosaveIndicator-BJsg_kFZ.mjs";
7
7
  const u = {
8
8
  mailgun: { label: "Mailgun", host: "smtp.mailgun.org", username: "", credentialLabel: "SMTP Password", showUsername: !0, usernameEqualsPassword: !1 },
9
9
  sendgrid: { label: "SendGrid", host: "smtp.sendgrid.net", username: "apikey", credentialLabel: "API Key", showUsername: !1, usernameEqualsPassword: !1 },
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),a=require("react"),u=require("./index-OaWkrl0G.js");function A({serverUrl:n,apiKey:d,pageSize:o=20,authManager:r}){const[l,s]=a.useState([]),[c,p]=a.useState(0),[w,v]=a.useState(!0),[b,S]=a.useState(null),[h,N]=a.useState(null),[L,_]=a.useState(null),[R,y]=a.useState([]),[$,C]=a.useState(!1),[j,F]=a.useState(""),x=a.useCallback(async(t,i)=>{if(r?.isAuthenticated())return r.fetchWithAuth(t,i);const f={"Content-Type":"application/json"};d&&(f["X-API-Key"]=d);const m=await fetch(`${n}${t}`,{...i,headers:{...f,...i?.headers}});if(!m.ok){const I=await m.text().catch(()=>`HTTP ${m.status}`);throw new Error(I)}return m.json()},[n,d,r]),g=a.useCallback(async()=>{v(!0);try{S(null);const t=new URLSearchParams({limit:String(o)});j&&t.set("status",j);const i=await x(`/admin/orders?${t}`);s(i.orders),p(i.total)}catch{S("Failed to load orders")}finally{v(!1)}},[x,o,j]);a.useEffect(()=>{g()},[g]);const O=a.useCallback(async t=>{C(!0);try{const[i,f]=await Promise.all([x(`/admin/orders/${encodeURIComponent(t)}`),x("/admin/gift-card-redemptions?limit=50").catch(()=>[])]);_(i),y(f.filter(m=>m.orderId===t))}catch{_(null),y([])}finally{C(!1)}},[x]),T=t=>{h===t?(N(null),_(null),y([])):(N(t),O(t))},D=(t,i)=>i==="USD"||i==="usd"?`$${(t/100).toFixed(2)}`:`${t} ${i}`;return e.jsxs("div",{className:"cedros-admin__section",children:[e.jsxs("div",{className:"cedros-admin__section-header",children:[e.jsx("h2",{className:"cedros-admin__section-title",children:"Orders"}),e.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[e.jsxs("select",{className:"cedros-admin__input",style:{width:"auto",minWidth:"120px"},value:j,onChange:t=>F(t.target.value),children:[e.jsx("option",{value:"",children:"All statuses"}),e.jsx("option",{value:"paid",children:"Paid"}),e.jsx("option",{value:"processing",children:"Processing"}),e.jsx("option",{value:"fulfilled",children:"Fulfilled"}),e.jsx("option",{value:"shipped",children:"Shipped"}),e.jsx("option",{value:"delivered",children:"Delivered"}),e.jsx("option",{value:"cancelled",children:"Cancelled"}),e.jsx("option",{value:"refunded",children:"Refunded"})]}),e.jsxs("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary",onClick:g,children:[u.Icons.refresh," Refresh"]})]})]}),b?e.jsx(u.ErrorBanner,{message:b,onRetry:g}):null,w?e.jsx("div",{className:"cedros-admin__loading-text",children:"Loading orders..."}):l.length===0?e.jsx("div",{className:"cedros-admin__empty",children:"No orders found."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin__table-info",children:[c," order",c===1?"":"s"," total"]}),e.jsxs("table",{className:"cedros-admin__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Order"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Amount"}),e.jsx("th",{children:"Source"}),e.jsx("th",{children:"Customer"}),e.jsx("th",{children:"Date"})]})}),e.jsx("tbody",{children:l.map(t=>e.jsx(E,{order:t,expanded:h===t.id,detail:h===t.id?L:null,redemptions:h===t.id?R:[],detailLoading:h===t.id&&$,onToggle:()=>T(t.id),formatAmount:D},t.id))})]})]})]})}function E({order:n,expanded:d,detail:o,redemptions:r,detailLoading:l,onToggle:s,formatAmount:c}){const p=n.metadata?.recipient_email||r.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("tr",{onClick:s,style:{cursor:"pointer"},className:d?"cedros-admin__table-row--active":"",children:[e.jsxs("td",{children:[e.jsxs("span",{className:"cedros-admin__mono",children:[n.id.slice(0,12),"..."]}),p?e.jsx("span",{className:"cedros-admin__badge cedros-admin__badge--info",style:{marginLeft:"0.5rem"},children:"Gift Card"}):null]}),e.jsx("td",{children:e.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${k(n.status)}`,children:n.status})}),e.jsx("td",{children:c(n.amount,n.amountAsset)}),e.jsx("td",{children:n.source}),e.jsx("td",{children:n.customerEmail||n.customerName||"—"}),e.jsx("td",{children:u.formatDateTime(n.createdAt)})]}),d?e.jsx("tr",{children:e.jsx("td",{colSpan:6,style:{padding:0},children:e.jsx(P,{detail:o,redemptions:r,loading:l,formatAmount:c,metadata:n.metadata})})}):null]})}function P({detail:n,redemptions:d,loading:o,formatAmount:r,metadata:l}){return o?e.jsx("div",{style:{padding:"1rem"},className:"cedros-admin__loading-text",children:"Loading details..."}):e.jsxs("div",{style:{padding:"1rem",background:"var(--cedros-admin-bg-muted, #f9fafb)"},children:[Object.keys(l).length>0?e.jsxs("div",{style:{marginBottom:"1rem"},children:[e.jsx("div",{className:"cedros-admin__label",children:"Order Metadata"}),e.jsx("div",{style:{display:"grid",gridTemplateColumns:"auto 1fr",gap:"0.25rem 1rem",fontSize:"0.8125rem"},children:Object.entries(l).map(([s,c])=>e.jsxs("div",{style:{display:"contents"},children:[e.jsx("span",{style:{fontWeight:500,color:"var(--cedros-admin-text-muted)"},children:s}),e.jsx("span",{children:c})]},s))})]}):null,d.length>0?e.jsxs("div",{style:{marginBottom:"1rem"},children:[e.jsx("div",{className:"cedros-admin__label",children:"Gift Card Fulfillment"}),d.map(s=>e.jsxs("div",{style:{fontSize:"0.8125rem",padding:"0.5rem",border:"1px solid var(--cedros-admin-border)",borderRadius:"0.5rem",marginBottom:"0.5rem"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsxs("span",{children:["Face value: ",r(s.faceValueCents,s.currency)]}),e.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${s.creditsIssued>0?"success":"warning"}`,children:s.creditsIssued>0?"Credits issued":"Pending"})]}),e.jsxs("div",{style:{marginTop:"0.25rem",color:"var(--cedros-admin-text-muted)"},children:["Recipient: ",s.recipientUserId||"—",s.tokenMinted?e.jsx("span",{className:"cedros-admin__badge cedros-admin__badge--info",style:{marginLeft:"0.5rem"},children:"Token minted"}):null]})]},s.id))]}):null,n?.fulfillments&&n.fulfillments.length>0?e.jsxs("div",{style:{marginBottom:"1rem"},children:[e.jsx("div",{className:"cedros-admin__label",children:"Fulfillments"}),n.fulfillments.map(s=>e.jsxs("div",{style:{fontSize:"0.8125rem",marginBottom:"0.25rem"},children:[e.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${k(s.status)}`,children:s.status}),s.carrier?e.jsx("span",{style:{marginLeft:"0.5rem"},children:s.carrier}):null,s.trackingNumber?u.safeHref(s.trackingUrl)?e.jsx("a",{href:u.safeHref(s.trackingUrl),target:"_blank",rel:"noreferrer",style:{marginLeft:"0.5rem"},children:s.trackingNumber}):e.jsx("span",{style:{marginLeft:"0.5rem"},children:s.trackingNumber}):null]},s.id))]}):null,n?.history&&n.history.length>0?e.jsxs("div",{children:[e.jsx("div",{className:"cedros-admin__label",children:"Status History"}),n.history.map(s=>e.jsxs("div",{style:{fontSize:"0.8125rem",marginBottom:"0.25rem"},children:[e.jsx("span",{style:{color:"var(--cedros-admin-text-muted)"},children:u.formatDateTime(s.createdAt)})," ",s.fromStatus," → ",s.toStatus,s.note?e.jsx("span",{style:{marginLeft:"0.5rem",fontStyle:"italic"},children:s.note}):null]},s.id))]}):null]})}function k(n){switch(n){case"paid":case"fulfilled":case"delivered":case"success":return"success";case"processing":case"shipped":case"pending":return"warning";case"cancelled":case"refunded":case"failed":return"error";default:return"default"}}exports.OrdersSection=A;