@cedros/pay-react 1.1.30 → 1.1.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -30
- package/dist/{AISettingsSection-BMh3hAb5.mjs → AISettingsSection-ChBtZVz7.mjs} +4 -4
- package/dist/{AISettingsSection-C0zqPbd6.js → AISettingsSection-DSROL7Lg.js} +2 -2
- package/dist/{AutosaveIndicator-3ctAnz8Y.mjs → AutosaveIndicator-BTa2YPNH.mjs} +1 -1
- package/dist/AutosaveIndicator-BgDnlrCW.js +1 -0
- package/dist/CedrosContext-3Dz7_9Ct.js +3 -0
- package/dist/{CedrosContext-5Gjveoba.mjs → CedrosContext-DQc_k5PG.mjs} +430 -314
- package/dist/ChatLogsSection-B5AdoZls.js +1 -0
- package/dist/{ChatLogsSection-BtJixYAp.mjs → ChatLogsSection-D8FX7Dmn.mjs} +2 -2
- package/dist/{ComplianceSection-BMnb1p4w.mjs → ComplianceSection-A1hgI_X2.mjs} +3 -3
- package/dist/ComplianceSection-UWfkNrmW.js +1 -0
- package/dist/CryptoButton-BQceZhbn.js +1 -0
- package/dist/{CryptoButton-Cl2kZbOP.mjs → CryptoButton-BuO_RZLj.mjs} +4 -5
- package/dist/{CustomersSection-dmwoBhcf.mjs → CustomersSection-BuSVgS16.mjs} +2 -2
- package/dist/CustomersSection-Rh552kcC.js +1 -0
- package/dist/DisputesSection-BtMdxOuD.js +1 -0
- package/dist/{DisputesSection-CHyLne76.mjs → DisputesSection-DqWrBCyC.mjs} +2 -2
- package/dist/Dropdown-CWYy2Rtt.js +1 -0
- package/dist/{Dropdown-BRSZlhik.mjs → Dropdown-DHCHYuTB.mjs} +1 -1
- package/dist/{ErrorBanner-lZJhCmDX.mjs → ErrorBanner-7naZtdtD.mjs} +1 -1
- package/dist/ErrorBanner-BOS1XAPu.js +1 -0
- package/dist/FAQSection-DczKj0C3.js +1 -0
- package/dist/{FAQSection-Di2xE9Sm.mjs → FAQSection-x0ya8PvI.mjs} +3 -3
- package/dist/{ImagesSection-D63PEjR6.mjs → ImagesSection-CMvHgbtL.mjs} +2 -2
- package/dist/ImagesSection-tRpBN-ls.js +1 -0
- package/dist/{InventorySection-Dp5Yu4TA.mjs → InventorySection-5PEOXciZ.mjs} +2 -2
- package/dist/InventorySection-clEVFr_r.js +1 -0
- package/dist/MessagingSection-BpwTsNW1.js +1 -0
- package/dist/{MessagingSection-BLCnCpEv.mjs → MessagingSection-Bt84iW-5.mjs} +3 -3
- package/dist/OrdersSection-Bsou3cwl.js +1 -0
- package/dist/{OrdersSection-Bd56F3cj.mjs → OrdersSection-kJzPO6CP.mjs} +2 -2
- package/dist/{PaymentSettingsSection-B5J56VAk.js → PaymentSettingsSection-CUgUJ7tm.js} +1 -1
- package/dist/{PaymentSettingsSection-52iw47Su.mjs → PaymentSettingsSection-s_XMFPik.mjs} +3 -3
- package/dist/{ReturnsSection-DUVeKrCd.mjs → ReturnsSection-BcwsQbrU.mjs} +2 -2
- package/dist/ReturnsSection-BwHv1HkV.js +1 -0
- package/dist/{SettingsSection-DKkHykaC.js → SettingsSection-B_feZEzU.js} +1 -1
- package/dist/{SettingsSection-vK9WIwXE.mjs → SettingsSection-OI1G3b40.mjs} +1 -1
- package/dist/{ShippingSection-CZRrXrlh.mjs → ShippingSection-B2GtSEvn.mjs} +2 -2
- package/dist/ShippingSection-DyTGH_Fh.js +1 -0
- package/dist/{SingleCategorySettings-C8xJ47_T.mjs → SingleCategorySettings-Cd76sY00.mjs} +4 -4
- package/dist/SingleCategorySettings-Ci6hJ0Xu.js +3 -0
- package/dist/{StatsBar-D4cOKG2e.mjs → StatsBar-B_lf0ph0.mjs} +1 -1
- package/dist/StatsBar-CVqsD8j2.js +1 -0
- package/dist/StorefrontSection-BxaWrsPc.js +1 -0
- package/dist/{StorefrontSection-uXSVbEAa.mjs → StorefrontSection-DW0q9GsC.mjs} +4 -4
- package/dist/{SubscriptionsSection-Ci_AZrWA.mjs → SubscriptionsSection-CNHPCync.mjs} +3 -3
- package/dist/SubscriptionsSection-QMoSKKot.js +1 -0
- package/dist/TaxSection-BKhh7kOv.js +1 -0
- package/dist/{TaxSection-BTukS_cU.mjs → TaxSection-BwLpiery.mjs} +2 -2
- package/dist/Token22Section-B_URxab9.js +1 -0
- package/dist/{Token22Section-DRsPJuTq.mjs → Token22Section-DyNDKGdU.mjs} +227 -212
- package/dist/{WalletManager-D-eoqUDy.mjs → WalletManager-CGR69MiR.mjs} +1 -1
- package/dist/{WalletManager-DXChB9LA.js → WalletManager-ZJbGQHrn.js} +1 -1
- package/dist/WebhooksSection-BIs2Qh-o.js +1 -0
- package/dist/{WebhooksSection-A8Y4ZGcj.mjs → WebhooksSection-bDVQE9Qp.mjs} +2 -2
- package/dist/admin.js +1 -1
- package/dist/admin.mjs +1 -1
- package/dist/crypto-only.js +1 -1
- package/dist/crypto-only.mjs +102 -105
- package/dist/{index-9QF_UfSN.mjs → index-CU6M10Rs.mjs} +13 -14
- package/dist/{index-Cq9ya93W.js → index-DVxx_62C.js} +10 -10
- package/dist/index.js +1 -1
- package/dist/index.mjs +31 -34
- package/dist/pay-react.css +1 -1
- package/dist/plugin-CuoGEYWr.mjs +339 -0
- package/dist/plugin-DNhaPAbC.js +1 -0
- package/dist/sections-BYdyCKFF.js +1 -0
- package/dist/{sections-more-Ixw6mM6R.mjs → sections-vLd_ind5.mjs} +263 -270
- package/dist/src/admin/plugin.d.ts.map +1 -1
- package/dist/src/admin/sectionIds.d.ts.map +1 -1
- package/dist/src/admin.d.ts +0 -7
- package/dist/src/admin.d.ts.map +1 -1
- package/dist/src/components/admin/LiquidityPoolTab.d.ts.map +1 -1
- package/dist/src/components/admin/PoolManagementView.d.ts.map +1 -1
- package/dist/src/components/admin/index.d.ts +0 -1
- package/dist/src/components/admin/index.d.ts.map +1 -1
- package/dist/src/index.d.ts +0 -1
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/managers/MeteoraPoolManager.d.ts.map +1 -1
- package/dist/src/utils/optionalPeerImport.d.ts +6 -0
- package/dist/src/utils/optionalPeerImport.d.ts.map +1 -0
- package/dist/stripe-only.js +1 -1
- package/dist/stripe-only.mjs +18 -19
- package/dist/styles-BwaDljnz.js +1 -0
- package/dist/{styles-DGagylUj.mjs → styles-fihm6qVA.mjs} +51 -52
- package/dist/testing/index.js +1 -1
- package/dist/testing/index.mjs +1 -1
- package/package.json +6 -8
- package/dist/AutosaveIndicator-DXRPr4P7.js +0 -1
- package/dist/CedrosContext-CCakH2SZ.js +0 -3
- package/dist/CedrosPayAdminDashboard-DaJ9JoGn.mjs +0 -250
- package/dist/CedrosPayAdminDashboard-Uvyh9p7A.js +0 -1
- package/dist/ChatLogsSection-FC3O536G.js +0 -1
- package/dist/ComplianceSection-BioTKm7k.js +0 -1
- package/dist/CryptoButton-DxFCYDlJ.js +0 -1
- package/dist/CustomersSection-z6ARxuex.js +0 -1
- package/dist/DisputesSection-BjHHQAi7.js +0 -1
- package/dist/Dropdown-j8o0OO5L.js +0 -1
- package/dist/ErrorBanner-CAgPnj62.js +0 -1
- package/dist/FAQSection-b34DMzgV.js +0 -1
- package/dist/ImagesSection-DGBA7iKY.js +0 -1
- package/dist/InventorySection-bVCECzX5.js +0 -1
- package/dist/LazyCedrosPayAdminDashboard-BqJDNrDI.mjs +0 -9
- package/dist/LazyCedrosPayAdminDashboard-CpfTtOBc.js +0 -1
- package/dist/MessagingSection-DU0dYNMy.js +0 -1
- package/dist/OrdersSection-FOFEAgs1.js +0 -1
- package/dist/ReturnsSection-BjpIVFfN.js +0 -1
- package/dist/ShippingSection-B5lk7zpS.js +0 -1
- package/dist/SingleCategorySettings-g7D-9lG1.js +0 -3
- package/dist/StatsBar-CWXw2ZT3.js +0 -1
- package/dist/StorefrontSection-BWnMB9k-.js +0 -1
- package/dist/SubscriptionsSection-DQfXkuDv.js +0 -1
- package/dist/TaxSection-cuPQISxZ.js +0 -1
- package/dist/ThemeContext-CFXyYx7A.js +0 -1
- package/dist/ThemeContext-l0bqcOGW.mjs +0 -126
- package/dist/Token22Section-CCfkDm8W.js +0 -1
- package/dist/WebhooksSection-CnEmaGH1.js +0 -1
- package/dist/icons-C3yDMnKE.mjs +0 -235
- package/dist/icons-Cjgd9YVo.js +0 -1
- package/dist/pay-react_false-CPX8Vyp9.mjs +0 -5
- package/dist/pay-react_false-DaeIe3_l.js +0 -1
- package/dist/sectionIds-D46-_-h-.js +0 -1
- package/dist/sectionIds-YktNxmRt.mjs +0 -124
- package/dist/sections-511_XBh4.js +0 -1
- package/dist/sections-CRaMa8ZB.mjs +0 -9
- package/dist/sections-more-Cgw2qJlA.js +0 -1
- package/dist/src/components/admin/CedrosPayAdminDashboard.d.ts +0 -40
- package/dist/src/components/admin/CedrosPayAdminDashboard.d.ts.map +0 -1
- package/dist/src/components/admin/LazyCedrosPayAdminDashboard.d.ts +0 -4
- package/dist/src/components/admin/LazyCedrosPayAdminDashboard.d.ts.map +0 -1
- package/dist/src/standalone-admin.d.ts +0 -8
- package/dist/src/standalone-admin.d.ts.map +0 -1
- package/dist/standalone-admin.d.ts +0 -2
- package/dist/standalone-admin.js +0 -1
- package/dist/standalone-admin.mjs +0 -4
- package/dist/styles--fxb3lCl.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const r=require("react/jsx-runtime"),k=require("react"),S=require("./index-WcOlBYZJ.js"),p=require("./fetchWithTimeout-CG0EKbhf.js"),t={adminProfile:"admin-profile",adminSectionAccess:"admin-section-access",cedrosLogin:"cedros-login",cedrosPay:"cedros-pay",org:"org",dashboardPermissions:"dashboard-permissions"};function x(e={}){return{...e}}function T(e){const o=x(e.services);return!(t.adminProfile in o)&&e.cedrosLogin?.user&&(o[t.adminProfile]={user:e.cedrosLogin.user}),!(t.adminSectionAccess in o)&&e.dashboardPermissions&&(o[t.adminSectionAccess]=e.dashboardPermissions),!(t.cedrosLogin in o)&&e.cedrosLogin&&(o[t.cedrosLogin]=e.cedrosLogin),!(t.cedrosPay in o)&&e.cedrosPay&&(o[t.cedrosPay]=e.cedrosPay),!(t.org in o)&&e.org&&(o[t.org]=e.org),!(t.dashboardPermissions in o)&&e.dashboardPermissions&&(o[t.dashboardPermissions]=e.dashboardPermissions),o}function m(e,o){return P(T(e),o)}function P(e,o){return e[o]}class y{serverUrl;walletSigner=null;jwtToken=null;isAdminUser=!1;constructor(o){this.serverUrl=o}getAuthMethod(){return this.walletSigner?.publicKey&&this.walletSigner.signMessage?"wallet":this.jwtToken&&this.isAdminUser?"cedros-login":"none"}isAuthenticated(){return this.getAuthMethod()!=="none"}setWalletSigner(o){this.walletSigner=o,p.getLogger().debug("[AdminAuthManager] Wallet signer updated:",!!o?.publicKey)}setCedrosLoginAuth(o,i){this.jwtToken=o,this.isAdminUser=i??!1,p.getLogger().debug("[AdminAuthManager] Cedros-login auth updated:",{hasToken:!!o,isAdmin:this.isAdminUser})}async createAuthHeaders(o){const i=this.getAuthMethod();if(i==="wallet")return this.createWalletAuthHeaders(o);if(i==="cedros-login")return this.createJwtAuthHeaders();throw new Error("No admin authentication configured. Connect a wallet or sign in as admin.")}async createWalletAuthHeaders(o){if(!this.walletSigner?.publicKey||!this.walletSigner.signMessage)throw new Error("Wallet not connected or does not support message signing");const i=await this.fetchNonce(o),c=new TextEncoder().encode(i.nonce),a=await this.walletSigner.signMessage(c),d=S.bs58.encode(this.walletSigner.publicKey.toBytes()),h=p.gBase64.fromUint8Array(a);return{"X-Signer":d,"X-Message":i.nonce,"X-Signature":h}}createJwtAuthHeaders(){if(!this.jwtToken)throw new Error("No JWT token available");return{Authorization:`Bearer ${this.jwtToken}`}}async fetchNonce(o){const i=`${this.serverUrl}/paywall/v1/nonce`,c=typeof o=="string"?{purpose:o}:{path:o.path,method:o.method.toUpperCase()};p.getLogger().debug("[AdminAuthManager] Fetching nonce:",c);const a=await p.fetchWithTimeout(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!a.ok){const d=await a.text();throw new Error(`Failed to fetch nonce: ${a.status} ${d}`)}return await a.json()}async fetchWithAuth(o,i={}){if(this.getAuthMethod()==="none")throw new Error("No admin authentication configured");const a=(i.method||"GET").toUpperCase(),d=await this.createAuthHeaders({path:o,method:a}),h={...a!=="GET"&&a!=="HEAD"?{"Content-Type":"application/json"}:{},...i.headers||{},...d},u=await p.fetchWithTimeout(`${this.serverUrl}${o}`,{...i,headers:h});if(!u.ok){let g=`Admin API error ${u.status}`;try{const l=await u.json();l&&typeof l.error=="string"?g=l.error:l&&typeof l.message=="string"&&(g=l.message)}catch{}throw new Error(g)}return await u.json()}}function E(){return r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M20 7.5v9l-4 2.25M4 7.5v9l4 2.25"}),r.jsx("path",{d:"m20 7.5-8-4.5-8 4.5"}),r.jsx("path",{d:"m12 12 8-4.5M12 12v9.5M12 12 4 7.5"})]})}function L(){return r.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"})})}function b(){return r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z"}),r.jsx("path",{d:"M13 5v2M13 17v2M13 11v2"})]})}function q(){return r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),r.jsx("path",{d:"M3 3v5h5"}),r.jsx("path",{d:"M12 7v5l4 2"})]})}function j(){return r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),r.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function M(){return r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}),r.jsx("path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"})]})}const s={products:()=>r.jsx(E,{}),transactions:()=>r.jsx(L,{}),coupons:()=>r.jsx(b,{}),refunds:()=>r.jsx(q,{}),settings:()=>r.jsx(j,{}),wallet:()=>r.jsx(M,{})},C={settings:r.jsx(j,{}),chevronRight:r.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"m9 18 6-6-6-6"})}),loading:r.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"cedros-admin__spinner",children:r.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),refresh:r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}),r.jsx("path",{d:"M21 3v5h-5"}),r.jsx("path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}),r.jsx("path",{d:"M8 16H3v5"})]}),check:r.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"M20 6 9 17l-5-5"})}),trash:r.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"})}),plus:r.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"M12 5v14M5 12h14"})}),chevronDown:r.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"m6 9 6 6 6-6"})}),chevronUp:r.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"m18 15-6-6-6 6"})}),arrowUp:r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"m5 12 7-7 7 7"}),r.jsx("path",{d:"M12 19V5"})]}),arrowDown:r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"m5 12 7 7 7-7"}),r.jsx("path",{d:"M12 5v14"})]}),delete:r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"}),r.jsx("path",{d:"M10 11v6M14 11v6"})]}),close:r.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"M18 6 6 18M6 6l12 12"})}),edit:r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),r.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),chat:r.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"m3 21 1.9-5.7a8.5 8.5 0 1 1 3.8 3.8z"})}),globe:r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("circle",{cx:"12",cy:"12",r:"10"}),r.jsx("path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}),r.jsx("path",{d:"M2 12h20"})]}),eye:r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),r.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),eyeOff:r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24"}),r.jsx("path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"}),r.jsx("path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"}),r.jsx("line",{x1:"2",x2:"22",y1:"2",y2:"22"})]})},f=[{id:"transactions",qualifiedId:"cedros-pay:transactions",label:"Transactions",group:"Store",order:0,endpoints:["GET /admin/transactions"]},{id:"orders",qualifiedId:"cedros-pay:orders",label:"Orders",group:"Store",order:1,endpoints:["GET /admin/orders","GET /admin/orders/{id}"]},{id:"products",qualifiedId:"cedros-pay:products",label:"Products",group:"Store",order:2,endpoints:["GET /admin/products","POST /admin/products","PUT /admin/products/{id}","DELETE /admin/products/{id}"]},{id:"subscriptions",qualifiedId:"cedros-pay:subscriptions",label:"Subscriptions",group:"Store",order:3,endpoints:["GET /admin/subscriptions","POST /admin/subscriptions","PUT /admin/subscriptions/{id}"]},{id:"coupons",qualifiedId:"cedros-pay:coupons",label:"Coupons",group:"Store",order:4,endpoints:["GET /admin/coupons","POST /admin/coupons","PUT /admin/coupons/{id}","DELETE /admin/coupons/{id}"]},{id:"refunds",qualifiedId:"cedros-pay:refunds",label:"Refunds",group:"Store",order:5,endpoints:["GET /admin/refunds","POST /admin/refunds/{id}/approve","POST /admin/refunds/{id}/deny"]},{id:"compliance",qualifiedId:"cedros-pay:compliance",label:"Compliance",group:"Store",order:6,endpoints:["GET /admin/compliance/stats","POST /admin/compliance/check"]},{id:"chat-logs",qualifiedId:"cedros-pay:chat-logs",label:"Chat Logs",group:"Store",order:7,endpoints:["GET /admin/chats","GET /admin/chats/{sessionId}"]},{id:"customers",qualifiedId:"cedros-pay:customers",label:"Customers",group:"Store",order:8,endpoints:["GET /admin/customers","POST /admin/customers","PUT /admin/customers/{id}"]},{id:"disputes",qualifiedId:"cedros-pay:disputes",label:"Disputes",group:"Store",order:9,endpoints:["GET /admin/disputes","GET /admin/disputes/{id}","PUT /admin/disputes/{id}/status"]},{id:"returns",qualifiedId:"cedros-pay:returns",label:"Returns",group:"Store",order:10,endpoints:["GET /admin/returns","GET /admin/returns/{id}","PUT /admin/returns/{id}/status"]},{id:"images",qualifiedId:"cedros-pay:images",label:"Images",group:"Store",order:11,endpoints:["GET /admin/images","POST /admin/images","DELETE /admin/images/{id}"]},{id:"inventory",qualifiedId:"cedros-pay:inventory",label:"Inventory",group:"Store",order:12,endpoints:["GET /admin/products","GET /admin/products/{id}/inventory/adjustments"]},{id:"storefront",qualifiedId:"cedros-pay:storefront",label:"Storefront",group:"Configuration",order:20,endpoints:["GET /admin/config/shop","PUT /admin/config/shop"]},{id:"ai-settings",qualifiedId:"cedros-pay:ai-settings",label:"Store AI",group:"Configuration",order:21,endpoints:["GET /admin/config/ai","PUT /admin/config/ai/api-key","PUT /admin/config/ai/assignment","PUT /admin/config/ai/prompt"]},{id:"faqs",qualifiedId:"cedros-pay:faqs",label:"Knowledge Base",group:"Configuration",order:22,endpoints:["GET /admin/faqs","POST /admin/faqs","PUT /admin/faqs/{id}","DELETE /admin/faqs/{id}"]},{id:"payment-settings",qualifiedId:"cedros-pay:payment-settings",label:"Payment Options",group:"Configuration",order:23,endpoints:["GET /admin/config/stripe","PUT /admin/config/stripe","GET /admin/config/x402","PUT /admin/config/x402","GET /admin/config/cedros_login","PUT /admin/config/cedros_login"]},{id:"token22",qualifiedId:"cedros-pay:token22",label:"Gift Cards & Token-22",group:"Configuration",order:24,endpoints:["GET /admin/token22/status","POST /admin/token22/initialize","POST /admin/token22/harvest-fees","GET /admin/gift-card-redemptions"]},{id:"messaging",qualifiedId:"cedros-pay:messaging",label:"Store Messages",group:"Configuration",order:25,endpoints:["GET /admin/config/messaging","PUT /admin/config/messaging"]},{id:"webhooks",qualifiedId:"cedros-pay:webhooks",label:"Webhooks",group:"Configuration",order:26,endpoints:["GET /admin/webhooks","POST /admin/webhooks/{id}/retry","DELETE /admin/webhooks/{id}","GET /admin/webhooks/dlq"]},{id:"shipping",qualifiedId:"cedros-pay:shipping",label:"Shipping",group:"Configuration",order:27,endpoints:["GET /admin/shipping/profiles","POST /admin/shipping/profiles","GET /admin/shipping/profiles/{id}/rates"]},{id:"tax",qualifiedId:"cedros-pay:tax",label:"Tax Rates",group:"Configuration",order:28,endpoints:["GET /admin/tax/rates","POST /admin/tax/rates","PUT /admin/tax/rates/{id}","DELETE /admin/tax/rates/{id}"]},{id:"settings",qualifiedId:"cedros-pay:settings",label:"Store Server",group:"Configuration",order:29,endpoints:["GET /admin/config/server","PUT /admin/config/server"]}],A=f.map(e=>e.qualifiedId),w=[{id:"Store",label:"Store",order:1,defaultCollapsed:!1},{id:"Configuration",label:"Configuration",order:2,defaultCollapsed:!0}],n=e=>k.lazy(async()=>{const c=(await e()).default;return{default:({pluginContext:d})=>{const h=d.getAccessToken(),u=d.hasPermission("cedros-pay:admin")||d.hasPermission("admin"),g=k.useMemo(()=>{const v=new y(d.serverUrl);return v.setCedrosLoginAuth(h??null,u),v},[u,d.serverUrl,h]),l={serverUrl:d.serverUrl,authManager:g};return r.jsx(c,{...l})}}}),I={id:"cedros-pay",name:"Cedros Pay",version:"1.0.0",sections:f.map(e=>({id:e.id,label:e.label,icon:{transactions:s.transactions,orders:s.transactions,products:s.products,subscriptions:s.products,coupons:s.coupons,refunds:s.refunds,compliance:s.settings,"chat-logs":s.settings,customers:s.settings,disputes:s.settings,returns:s.refunds,images:s.products,inventory:s.products,storefront:s.products,"ai-settings":s.settings,faqs:s.settings,"payment-settings":s.wallet,token22:s.wallet,messaging:s.settings,webhooks:s.settings,shipping:s.products,tax:s.transactions,settings:s.settings}[e.id],group:e.group,order:e.order})),groups:w.map(e=>({id:e.id,label:e.label,order:e.order,defaultCollapsed:e.defaultCollapsed})),components:{products:n(()=>Promise.resolve().then(()=>require("./sections-BYdyCKFF.js")).then(e=>({default:e.ProductsSection}))),subscriptions:n(()=>Promise.resolve().then(()=>require("./SubscriptionsSection-QMoSKKot.js")).then(e=>({default:e.SubscriptionsSection}))),transactions:n(()=>Promise.resolve().then(()=>require("./sections-BYdyCKFF.js")).then(e=>({default:e.TransactionsSection}))),orders:n(()=>Promise.resolve().then(()=>require("./OrdersSection-Bsou3cwl.js")).then(e=>({default:e.OrdersSection}))),coupons:n(()=>Promise.resolve().then(()=>require("./sections-BYdyCKFF.js")).then(e=>({default:e.CouponsSection}))),refunds:n(()=>Promise.resolve().then(()=>require("./sections-BYdyCKFF.js")).then(e=>({default:e.RefundsSection}))),compliance:n(()=>Promise.resolve().then(()=>require("./ComplianceSection-UWfkNrmW.js")).then(e=>({default:e.ComplianceSection}))),"chat-logs":n(()=>Promise.resolve().then(()=>require("./ChatLogsSection-B5AdoZls.js")).then(e=>({default:e.ChatLogsSection}))),customers:n(()=>Promise.resolve().then(()=>require("./CustomersSection-Rh552kcC.js")).then(e=>({default:e.CustomersSection}))),disputes:n(()=>Promise.resolve().then(()=>require("./DisputesSection-BtMdxOuD.js")).then(e=>({default:e.DisputesSection}))),returns:n(()=>Promise.resolve().then(()=>require("./ReturnsSection-BwHv1HkV.js")).then(e=>({default:e.ReturnsSection}))),images:n(()=>Promise.resolve().then(()=>require("./ImagesSection-tRpBN-ls.js")).then(e=>({default:e.ImagesSection}))),inventory:n(()=>Promise.resolve().then(()=>require("./InventorySection-clEVFr_r.js")).then(e=>({default:e.InventorySection}))),storefront:n(()=>Promise.resolve().then(()=>require("./StorefrontSection-BxaWrsPc.js")).then(e=>({default:e.StorefrontSection}))),"ai-settings":n(()=>Promise.resolve().then(()=>require("./AISettingsSection-DSROL7Lg.js")).then(e=>({default:e.AISettingsSection}))),faqs:n(()=>Promise.resolve().then(()=>require("./FAQSection-DczKj0C3.js")).then(e=>({default:e.FAQSection}))),"payment-settings":n(()=>Promise.resolve().then(()=>require("./PaymentSettingsSection-CUgUJ7tm.js")).then(e=>({default:e.PaymentSettingsSection}))),token22:n(()=>Promise.resolve().then(()=>require("./Token22Section-B_URxab9.js")).then(e=>({default:e.Token22Section}))),messaging:n(()=>Promise.resolve().then(()=>require("./MessagingSection-BpwTsNW1.js")).then(e=>({default:e.MessagingSection}))),webhooks:n(()=>Promise.resolve().then(()=>require("./WebhooksSection-BIs2Qh-o.js")).then(e=>({default:e.WebhooksSection}))),shipping:n(()=>Promise.resolve().then(()=>require("./ShippingSection-DyTGH_Fh.js")).then(e=>({default:e.ShippingSection}))),tax:n(()=>Promise.resolve().then(()=>require("./TaxSection-BKhh7kOv.js")).then(e=>({default:e.TaxSection}))),settings:n(()=>Promise.resolve().then(()=>require("./SettingsSection-B_feZEzU.js")).then(e=>({default:e.SettingsSection})))},createPluginContext(e){const o=m(e,t.cedrosPay),i=m(e,t.cedrosLogin),c=m(e,t.org);return{serverUrl:o?.serverUrl||i?.serverUrl||"",userId:i?.user?.id,getAccessToken:()=>i?.getAccessToken?.()||o?.jwtToken||null,hasPermission:d=>this.checkPermission(d,e),orgId:c?.orgId,pluginData:{walletAddress:o?.walletAddress}}},checkPermission(e,o){const i=m(o,t.org);return i?.permissions?i.permissions.includes(e):!1},cssNamespace:"cedros-dashboard"};exports.CEDROS_PAY_GROUPS=w;exports.CEDROS_PAY_SECTIONS=f;exports.CEDROS_PAY_SECTION_IDS=A;exports.Icons=C;exports.cedrosPayPlugin=I;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),r=require("react"),$=require("./plugin-DNhaPAbC.js"),ne=require("./ErrorBanner-BOS1XAPu.js"),ce=require("./StatsBar-CVqsD8j2.js"),G=require("./Dropdown-CWYy2Rtt.js"),de=require("./dateHelpers-BKW_lGND.js"),te=require("./fetchWithTimeout-CG0EKbhf.js");function _e({serverUrl:y,productId:o,apiKey:b,authManager:u}){const[p,A]=r.useState(null),[N,T]=r.useState(!1),[g,V]=r.useState(!1),[k,v]=r.useState(null),S=r.useCallback(async()=>{if(o){T(!0),v(null);try{let c;if(u?.isAuthenticated())c=await u.fetchWithAuth(`/admin/products/${o}/variations`);else{const a={"Content-Type":"application/json"};b&&(a["X-API-Key"]=b);const l=await fetch(`${y}/admin/products/${o}/variations`,{headers:a});if(!l.ok)throw new Error(`Failed to fetch variations: ${l.status}`);c=await l.json()}c.variationConfig||(c.variationConfig={variationTypes:[]}),c.variants||(c.variants=[]),A(c)}catch(c){const a=c instanceof Error?c.message:"Failed to fetch variations";v(a),A({productId:o,variationConfig:{variationTypes:[]},variants:[]})}finally{T(!1)}}},[y,o,b,u]),R=r.useCallback(async c=>{if(!o)return null;V(!0),v(null);try{let a;if(u?.isAuthenticated())a=await u.fetchWithAuth(`/admin/products/${o}/variations`,{method:"PUT",body:JSON.stringify(c)});else{const l={"Content-Type":"application/json"};b&&(l["X-API-Key"]=b);const C=await fetch(`${y}/admin/products/${o}/variations`,{method:"PUT",headers:l,body:JSON.stringify(c)});if(!C.ok)throw new Error(`Failed to save variations: ${C.status}`);a=await C.json()}return A({productId:o,variationConfig:a.variationConfig,variants:a.variants}),{variantsCreated:a.variantsCreated}}catch(a){const l=a instanceof Error?a.message:"Failed to save variations";return v(l),null}finally{V(!1)}},[y,o,b,u]),f=r.useCallback(async c=>{if(!o||c.length===0)return!1;V(!0),v(null);try{if(u?.isAuthenticated())await u.fetchWithAuth(`/admin/products/${o}/variants/inventory`,{method:"PUT",body:JSON.stringify({updates:c})});else{const a={"Content-Type":"application/json"};b&&(a["X-API-Key"]=b);const l=await fetch(`${y}/admin/products/${o}/variants/inventory`,{method:"PUT",headers:a,body:JSON.stringify({updates:c})});if(!l.ok)throw new Error(`Failed to update inventory: ${l.status}`)}if(p){const a=new Map(c.map(l=>[l.variantId,l]));A({...p,variants:p.variants.map(l=>{const C=a.get(l.id);return C?{...l,inventoryQuantity:C.inventoryQuantity,inventoryStatus:C.inventoryStatus??l.inventoryStatus}:l})})}return!0}catch(a){const l=a instanceof Error?a.message:"Failed to update inventory";return v(l),!1}finally{V(!1)}},[y,o,b,u,p]);return{data:p,isLoading:N,error:k,fetch:S,save:R,bulkUpdateInventory:f,isSaving:g}}function pe(){return`var_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function ye({value:y,onChange:o,maxTypes:b=5,maxValuesPerType:u=20,disabled:p=!1}){const[A,N]=r.useState(null),[T,g]=r.useState(""),[V,k]=r.useState({}),v=y.variationTypes,S=r.useCallback(()=>{if(!T.trim()||v.length>=b)return;const _={id:pe(),name:T.trim(),displayOrder:v.length,values:[]};o({variationTypes:[...v,_]}),g(""),N(_.id)},[T,v,b,o]),R=r.useCallback(_=>{o({variationTypes:v.filter(D=>D.id!==_).map((D,j)=>({...D,displayOrder:j}))}),A===_&&N(null)},[v,o,A]),f=r.useCallback((_,D)=>{o({variationTypes:v.map(j=>j.id===_?{...j,name:D}:j)})},[v,o]),c=r.useCallback((_,D)=>{const j=v.findIndex(I=>I.id===_);if(j===-1||D==="up"&&j===0||D==="down"&&j===v.length-1)return;const s=[...v],h=D==="up"?j-1:j+1;[s[j],s[h]]=[s[h],s[j]],o({variationTypes:s.map((I,d)=>({...I,displayOrder:d}))})},[v,o]),a=r.useCallback(_=>{const D=(V[_]||"").trim();if(!D)return;const j=v.find(h=>h.id===_);if(!j||j.values.length>=u)return;const s={id:pe(),label:D};o({variationTypes:v.map(h=>h.id===_?{...h,values:[...h.values,s]}:h)}),k(h=>({...h,[_]:""}))},[v,V,u,o]),l=r.useCallback((_,D)=>{o({variationTypes:v.map(j=>j.id===_?{...j,values:j.values.filter(s=>s.id!==D)}:j)})},[v,o]),C=r.useCallback((_,D,j)=>{o({variationTypes:v.map(s=>s.id===_?{...s,values:s.values.map(h=>h.id===D?{...h,label:j}:h)}:s)})},[v,o]);return e.jsxs("div",{className:"cedros-admin__variation-editor",children:[e.jsxs("div",{className:"cedros-admin__variation-editor-header",children:[e.jsx("h4",{className:"cedros-admin__field-label",style:{marginBottom:0},children:"Variation Types"}),e.jsxs("span",{style:{fontSize:12,opacity:.7},children:[v.length,"/",b," types"]})]}),v.length===0?e.jsx("div",{className:"cedros-admin__variation-empty",children:'No variation types defined. Add types like "Size" or "Color" to create product variants.'}):e.jsx("div",{className:"cedros-admin__variation-type-list",children:v.map((_,D)=>e.jsxs("div",{className:"cedros-admin__variation-type-item",children:[e.jsxs("div",{className:"cedros-admin__variation-type-header",children:[e.jsxs("div",{className:"cedros-admin__variation-type-controls",children:[e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>c(_.id,"up"),disabled:p||D===0,title:"Move up",children:$.Icons.arrowUp}),e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>c(_.id,"down"),disabled:p||D===v.length-1,title:"Move down",children:$.Icons.arrowDown})]}),e.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__variation-type-name",value:_.name,onChange:j=>f(_.id,j.target.value),disabled:p,placeholder:"Type name"}),e.jsxs("span",{className:"cedros-admin__variation-value-count",children:[_.values.length," values"]}),e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>N(A===_.id?null:_.id),children:A===_.id?"Collapse":"Edit values"}),e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>R(_.id),disabled:p,title:"Remove type",children:$.Icons.delete})]}),A===_.id&&e.jsxs("div",{className:"cedros-admin__variation-values",children:[e.jsxs("div",{className:"cedros-admin__variation-values-header",children:[e.jsxs("span",{style:{fontSize:12,fontWeight:600},children:['Values for "',_.name,'"']}),e.jsxs("span",{style:{fontSize:11,opacity:.7},children:[_.values.length,"/",u]})]}),_.values.length===0?e.jsx("div",{className:"cedros-admin__variation-empty",style:{padding:"8px 0"},children:'No values yet. Add values like "Small", "Medium", "Large".'}):e.jsx("div",{className:"cedros-admin__variation-value-list",children:_.values.map(j=>e.jsxs("div",{className:"cedros-admin__variation-value-item",children:[e.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:j.label,onChange:s=>C(_.id,j.id,s.target.value),disabled:p}),e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon cedros-admin__button--danger",onClick:()=>l(_.id,j.id),disabled:p,title:"Remove value",children:$.Icons.close})]},j.id))}),_.values.length<u&&e.jsxs("div",{className:"cedros-admin__variation-add-value",children:[e.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:V[_.id]||"",onChange:j=>k(s=>({...s,[_.id]:j.target.value})),placeholder:"Add value...",disabled:p,onKeyDown:j=>{j.key==="Enter"&&(j.preventDefault(),a(_.id))}}),e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary cedros-admin__button--sm",onClick:()=>a(_.id),disabled:p||!V[_.id]?.trim(),children:"Add"})]})]})]},_.id))}),v.length<b&&e.jsxs("div",{className:"cedros-admin__variation-add-type",children:[e.jsx("input",{type:"text",className:"cedros-admin__input",value:T,onChange:_=>g(_.target.value),placeholder:"New variation type (e.g., Size, Color)",disabled:p,onKeyDown:_=>{_.key==="Enter"&&(_.preventDefault(),S())}}),e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary",onClick:S,disabled:p||!T.trim(),children:"Add Type"})]})]})}function ge(){return`variant_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function xe(y){if(y.length===0)return[];const o=[...y].sort((u,p)=>u.displayOrder-p.displayOrder),b=(u,p)=>{if(u>=o.length){const T=p.valueIds.sort().join("|"),g=Object.values(p.options).join(" / ");return[{key:T,title:g,optionValueIds:[...p.valueIds],options:{...p.options}}]}const A=o[u],N=[];for(const T of A.values)N.push(...b(u+1,{valueIds:[...p.valueIds,T.id],options:{...p.options,[A.name]:T.label}}));return N};return b(0,{valueIds:[],options:{}})}function be(y){return y.optionValueIds?.length?[...y.optionValueIds].sort().join("|"):Object.entries(y.options).sort(([o],[b])=>o.localeCompare(b)).map(([o,b])=>`${o}:${b}`).join("|")}function ve({variationConfig:y,variants:o,onChange:b,defaultPrice:u=0,currencySymbol:p="$",maxVariants:A=100,disabled:N=!1}){const T=r.useMemo(()=>xe(y.variationTypes),[y.variationTypes]),g=r.useMemo(()=>{const c=new Map;for(const a of o)c.set(be(a),a);return c},[o]),{existingRows:V,possibleRows:k}=r.useMemo(()=>{const c=[],a=[];for(const l of T){const C=g.get(l.key);C?c.push({combo:l,variant:C}):a.push(l)}return{existingRows:c,possibleRows:a}},[T,g]),v=r.useCallback((c,a)=>{b(o.map(l=>l.id===c?{...l,...a}:l))},[o,b]),S=r.useCallback(c=>{b(o.filter(a=>a.id!==c))},[o,b]),R=r.useCallback(c=>{if(o.length>=A)return;const a={id:ge(),title:c.title,options:c.options,optionValueIds:c.optionValueIds,price:u,inventoryQuantity:0,inventoryStatus:"in_stock",autoGenerated:!1};b([...o,a])},[o,b,A,u]),f=r.useCallback(()=>{const c=A-o.length,l=k.slice(0,c).map(C=>({id:ge(),title:C.title,options:C.options,optionValueIds:C.optionValueIds,price:u,inventoryQuantity:0,inventoryStatus:"in_stock",autoGenerated:!0}));b([...o,...l])},[o,b,k,A,u]);return y.variationTypes.length===0?e.jsx("div",{className:"cedros-admin__variant-grid-empty",children:"Add variation types above to create product variants."}):T.length===0?e.jsx("div",{className:"cedros-admin__variant-grid-empty",children:"Add values to your variation types to create product variants."}):e.jsxs("div",{className:"cedros-admin__variant-grid",children:[e.jsxs("div",{className:"cedros-admin__variant-grid-header",children:[e.jsx("h4",{className:"cedros-admin__field-label",style:{marginBottom:0},children:"Variants"}),e.jsxs("span",{style:{fontSize:12,opacity:.7},children:[o.length,"/",A," variants (",T.length," ","possible)"]})]}),k.length>0&&o.length<A&&e.jsxs("div",{className:"cedros-admin__variant-grid-actions",children:[e.jsxs("button",{type:"button",className:"cedros-admin__button cedros-admin__button--secondary",onClick:f,disabled:N,children:["Generate All (",Math.min(k.length,A-o.length),")"]}),e.jsx("span",{style:{fontSize:11,opacity:.7},children:"Creates variants with default price and 0 inventory"})]}),e.jsx("div",{className:"cedros-admin__table-container",children:e.jsxs("table",{className:"cedros-admin__table cedros-admin__variant-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Variant"}),e.jsx("th",{style:{width:100},children:"Price"}),e.jsx("th",{style:{width:80},children:"Qty"}),e.jsx("th",{style:{width:100},children:"SKU"}),e.jsx("th",{style:{width:100},children:"Status"}),e.jsx("th",{style:{width:80},children:"Actions"})]})}),e.jsxs("tbody",{children:[V.map(({combo:c,variant:a})=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[e.jsx("span",{style:{fontWeight:600},children:c.title}),e.jsx("span",{style:{fontSize:11,opacity:.6},children:Object.entries(c.options).map(([l,C])=>`${l}: ${C}`).join(", ")})]})}),e.jsx("td",{children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[e.jsx("span",{children:p}),e.jsx("input",{type:"number",className:"cedros-admin__input cedros-admin__input--sm",value:a.price??"",onChange:l=>v(a.id,{price:l.target.value===""?void 0:parseFloat(l.target.value)||0}),disabled:N,min:"0",step:"0.01",style:{width:70}})]})}),e.jsx("td",{children:e.jsx("input",{type:"number",className:"cedros-admin__input cedros-admin__input--sm",value:a.inventoryQuantity??"",onChange:l=>v(a.id,{inventoryQuantity:l.target.value===""?void 0:parseInt(l.target.value)||0}),disabled:N,min:"0",style:{width:60}})}),e.jsx("td",{children:e.jsx("input",{type:"text",className:"cedros-admin__input cedros-admin__input--sm",value:a.sku??"",onChange:l=>v(a.id,{sku:l.target.value||void 0}),disabled:N,placeholder:"SKU",style:{width:80}})}),e.jsx("td",{children:e.jsx(G.FilterDropdown,{value:a.inventoryStatus??"in_stock",onChange:l=>v(a.id,{inventoryStatus:l}),options:[{value:"in_stock",label:"In stock"},{value:"low",label:"Low"},{value:"out_of_stock",label:"Out of stock"},{value:"backorder",label:"Backorder"}],disabled:N})}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon cedros-admin__button--danger",onClick:()=>S(a.id),disabled:N,title:"Remove variant",children:$.Icons.trash})})]},a.id)),k.length>0&&o.length<A&&e.jsxs(e.Fragment,{children:[e.jsx("tr",{className:"cedros-admin__variant-separator",children:e.jsx("td",{colSpan:6,children:e.jsxs("span",{style:{fontSize:11,opacity:.6},children:["Uncreated combinations (",k.length,")"]})})}),k.slice(0,10).map(c=>e.jsxs("tr",{className:"cedros-admin__variant-possible",children:[e.jsx("td",{children:e.jsx("span",{style:{opacity:.6},children:c.title})}),e.jsx("td",{colSpan:4,style:{opacity:.5},children:"Not created"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--icon",onClick:()=>R(c),disabled:N,title:"Create variant",children:$.Icons.plus})})]},c.key)),k.length>10&&e.jsx("tr",{className:"cedros-admin__variant-more",children:e.jsxs("td",{colSpan:6,style:{textAlign:"center",opacity:.6},children:["+",k.length-10," more combinations"]})})]})]})]})})]})}function je({serverUrl:y,productId:o,productTitle:b,defaultPrice:u=0,currencySymbol:p="$",apiKey:A,authManager:N,onClose:T}){const{data:g,isLoading:V,error:k,fetch:v,save:S,isSaving:R}=_e({serverUrl:y,productId:o,apiKey:A,authManager:N}),[f,c]=r.useState({variationTypes:[]}),[a,l]=r.useState([]),[C,_]=r.useState(!1),[D,j]=r.useState(!1);r.useEffect(()=>{v()},[v]),r.useEffect(()=>{g&&(c(g.variationConfig),l(g.variants),_(!1))},[g]);const s=r.useCallback(d=>{c(d),_(!0),j(!1)},[]),h=r.useCallback(d=>{l(d),_(!0),j(!1)},[]),I=r.useCallback(async()=>{const d=new Set((g?.variants??[]).map(F=>F.id)),m=a.filter(F=>!d.has(F.id)),L=a.filter(F=>d.has(F.id)),E=(g?.variants??[]).filter(F=>!a.some(H=>H.id===F.id)).map(F=>F.id);await S({variationConfig:f,createVariants:m.map(F=>({optionValueIds:F.optionValueIds??[],inventoryQuantity:F.inventoryQuantity,sku:F.sku,price:F.price})),updateVariants:L.map(F=>({id:F.id,inventoryQuantity:F.inventoryQuantity,sku:F.sku,price:F.price,inventoryStatus:F.inventoryStatus})),deleteVariantIds:E.length>0?E:void 0})&&(_(!1),j(!0),setTimeout(()=>j(!1),3e3))},[f,a,g?.variants,S]);return V?e.jsxs("div",{className:"cedros-admin__variations-editor",children:[e.jsxs("div",{className:"cedros-admin__variations-editor-header",children:[e.jsx("h3",{className:"cedros-admin__section-title",children:b?`Variations: ${b}`:"Product Variations"}),T&&e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:T,children:$.Icons.close})]}),e.jsxs("div",{className:"cedros-admin__loading",children:[$.Icons.loading," Loading variations..."]})]}):e.jsxs("div",{className:"cedros-admin__variations-editor",children:[e.jsxs("div",{className:"cedros-admin__variations-editor-header",children:[e.jsx("h3",{className:"cedros-admin__section-title",children:b?`Variations: ${b}`:"Product Variations"}),e.jsxs("div",{className:"cedros-admin__variations-editor-actions",children:[D&&e.jsxs("span",{className:"cedros-admin__success-text",children:[$.Icons.check," Saved"]}),C&&e.jsx("span",{className:"cedros-admin__unsaved-text",children:"Unsaved changes"}),e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--primary",onClick:I,disabled:R||!C,children:R?"Saving...":"Save Changes"}),T&&e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:T,children:$.Icons.close})]})]}),k&&e.jsx("div",{className:"cedros-admin__error-banner",children:k}),e.jsxs("div",{className:"cedros-admin__variations-editor-content",children:[e.jsx("div",{className:"cedros-admin__variations-editor-section",children:e.jsx(ye,{value:f,onChange:s,disabled:R})}),f.variationTypes.length>0&&e.jsx("div",{className:"cedros-admin__variations-editor-section",children:e.jsx(ve,{variationConfig:f,variants:a,onChange:h,defaultPrice:u,currencySymbol:p,disabled:R})})]})]})}const fe={requireSanctionsClear:!0,requireKyc:!1,requireAccreditedInvestor:!1,tokenGates:[]};function Ce({value:y,onChange:o}){const[b,u]=r.useState(y!==null),[p,A]=r.useState(""),[N,T]=r.useState("fungible_token"),[g,V]=r.useState(1),k=y??fe,v=()=>{y?(o(null),u(!1)):(o({...fe}),u(!0))},S=c=>{o({...k,...c})},R=()=>{if(!p.trim())return;const c={address:p.trim(),gateType:N,minAmount:g},a=[...k.tokenGates??[],c];S({tokenGates:a}),A(""),V(1)},f=c=>{const a=(k.tokenGates??[]).filter((l,C)=>C!==c);S({tokenGates:a.length>0?a:[]})};return e.jsxs("div",{style:{border:"1px solid var(--cedros-admin-border, #e0e0e0)",borderRadius:"4px",padding:"0.75rem",marginTop:"0.5rem"},children:[e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.9rem",fontWeight:600,cursor:"pointer"},children:[e.jsx("input",{type:"checkbox",checked:y!==null,onChange:v}),"Enable compliance gates"]}),y!==null&&b&&e.jsxs("div",{style:{marginTop:"0.75rem",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.85rem"},children:[e.jsx("input",{type:"checkbox",checked:k.requireSanctionsClear,onChange:c=>S({requireSanctionsClear:c.target.checked})}),"Require sanctions clearance"]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.85rem"},children:[e.jsx("input",{type:"checkbox",checked:k.requireKyc,onChange:c=>S({requireKyc:c.target.checked})}),"Require KYC verification"]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.85rem"},children:[e.jsx("input",{type:"checkbox",checked:k.requireAccreditedInvestor,onChange:c=>S({requireAccreditedInvestor:c.target.checked})}),"Require accredited investor status"]}),e.jsxs("div",{style:{marginTop:"0.5rem"},children:[e.jsx("span",{style:{fontSize:"0.85rem",fontWeight:600},children:"Token Gates"}),(k.tokenGates??[]).length>0&&e.jsx("div",{style:{marginTop:"0.25rem"},children:(k.tokenGates??[]).map((c,a)=>e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.8rem",padding:"0.25rem 0"},children:[e.jsxs("code",{style:{fontSize:"0.75rem"},children:[c.address.slice(0,8),"..."]}),e.jsx("span",{className:"cedros-admin__badge cedros-admin__badge--muted",children:c.gateType==="fungible_token"?"Fungible":"NFT"}),e.jsxs("span",{children:["min: ",c.minAmount]}),e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--sm",onClick:()=>f(a),style:{padding:"0 0.25rem"},children:"×"})]},a))}),e.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"flex-end",marginTop:"0.25rem",flexWrap:"wrap"},children:[e.jsx("input",{type:"text",className:"cedros-admin__input",placeholder:"Mint or collection address",value:p,onChange:c=>A(c.target.value),style:{flex:1,minWidth:"200px",fontSize:"0.8rem"}}),e.jsxs("select",{className:"cedros-admin__input",value:N,onChange:c=>T(c.target.value),style:{width:"auto",fontSize:"0.8rem"},children:[e.jsx("option",{value:"fungible_token",children:"Fungible"}),e.jsx("option",{value:"nft_collection",children:"NFT"})]}),e.jsx("input",{type:"number",className:"cedros-admin__input",min:1,value:g,onChange:c=>V(Number(c.target.value)),style:{width:"80px",fontSize:"0.8rem"}}),e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--sm",onClick:R,disabled:!p.trim(),children:"Add Gate"})]})]})]})]})}function Ne({serverUrl:y,productId:o,productTitle:b,apiKey:u,authManager:p,onClose:A}){const[N,T]=r.useState(null),[g,V]=r.useState(!0),[k,v]=r.useState(null),S=r.useCallback(async()=>{V(!0),v(null);try{const R=`/paywall/v1/products/${encodeURIComponent(o)}/nft-metadata`;let f;if(p?.isAuthenticated())f=await p.fetchWithAuth(R);else{const c={"Content-Type":"application/json"};u&&(c["X-API-Key"]=u);const a=await fetch(`${y}${R}`,{headers:c});if(!a.ok)throw new Error(`Request failed: ${a.status}`);f=await a.json()}T(f)}catch{v("Failed to load NFT metadata. Ensure this product exists and the server is running.")}finally{V(!1)}},[y,o,u,p]);return r.useEffect(()=>{S()},[S]),e.jsxs("div",{children:[e.jsxs("div",{className:"cedros-admin__section-header",style:{marginBottom:"1rem"},children:[e.jsxs("h3",{className:"cedros-admin__section-title",style:{fontSize:"1rem"},children:["NFT Metadata — ",b]}),e.jsxs("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:A,children:[$.Icons.close," Close"]})]}),e.jsx(ne.ErrorBanner,{message:k,onRetry:S}),g?e.jsxs("div",{className:"cedros-admin__loading",children:[$.Icons.loading," Loading metadata..."]}):N?e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[e.jsxs("div",{style:{display:"flex",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e0e0e0)",borderRadius:"8px"},children:[N.image&&e.jsx("img",{src:N.image,alt:N.name,style:{width:120,height:120,borderRadius:8,objectFit:"cover",flexShrink:0}}),e.jsxs("div",{style:{flex:1},children:[e.jsx("h4",{style:{margin:"0 0 0.25rem",fontSize:"1rem",fontWeight:600},children:N.name}),e.jsx("p",{style:{margin:"0 0 0.5rem",fontSize:"0.85rem",color:"var(--cedros-admin-text-muted, #888)"},children:N.description}),N.external_url&&e.jsxs("p",{style:{margin:"0 0 0.5rem",fontSize:"0.8rem"},children:[e.jsx("strong",{children:"URL:"})," ",e.jsx("code",{children:N.external_url})]}),N.attributes.length>0&&e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.5rem"},children:N.attributes.map(R=>e.jsxs("div",{style:{padding:"0.25rem 0.5rem",border:"1px solid var(--cedros-admin-border, #e0e0e0)",borderRadius:"4px",fontSize:"0.8rem"},children:[e.jsxs("span",{style:{color:"var(--cedros-admin-text-muted, #888)"},children:[R.trait_type,":"]})," ",e.jsx("strong",{children:R.value})]},R.trait_type))})]})]}),e.jsxs("div",{children:[e.jsx("h4",{style:{margin:"0 0 0.5rem",fontSize:"0.85rem",fontWeight:600},children:"Raw JSON (stored on-chain URI)"}),e.jsx("pre",{style:{background:"var(--cedros-admin-bg-muted, #f5f5f5)",border:"1px solid var(--cedros-admin-border, #e0e0e0)",borderRadius:"4px",padding:"0.75rem",fontSize:"0.8rem",overflow:"auto",maxHeight:"300px"},children:JSON.stringify(N,null,2)})]})]}):null]})}function ke({serverUrl:y,apiKey:o,pageSize:b=20,authManager:u}){const[p,A]=r.useState([]),[N,T]=r.useState(!0),[g,V]=r.useState(!1),[k,v]=r.useState(!1),[S,R]=r.useState(null),[f,c]=r.useState(null),[a,l]=r.useState(null),[C,_]=r.useState(null),[D,j]=r.useState(null),[s,h]=r.useState({id:"",title:"",slug:"",imageUrl:"",description:"",productType:"one_time",priceUsd:"",fiatCurrency:"usd",cryptoToken:"USDC",inventoryStatus:"in_stock",compareAtUsd:"",tagsCsv:"",categoryIdsCsv:"",checkoutEmail:"required",checkoutName:"optional",checkoutPhone:"none",checkoutShippingAddress:!1,checkoutBillingAddress:!1,fulfillmentType:"shipping",storePolicyFulfillment:"physical_goods",storeManagedKind:"none",appleProductId:"",googleProductId:"",googlePackageName:"",googleBasePlanId:"",googleOfferId:"",fulfillmentNotes:"",shippingCountriesCsv:"",inventoryQuantity:"",giftCardConfig:null,tokenizedAssetConfig:null,complianceRequirements:null}),I=t=>{const n=t.tagsCsv.split(",").map(J=>J.trim()).filter(Boolean),P=t.categoryIdsCsv.split(",").map(J=>J.trim()).filter(Boolean),W={email:t.checkoutEmail,name:t.checkoutName,phone:t.checkoutPhone,shippingAddress:t.checkoutShippingAddress,billingAddress:t.checkoutBillingAddress},z=t.fulfillmentType==="shipping"?"physical":"digital",B={title:t.title,slug:t.slug||t.id,shipping_profile:z,inventory_status:t.inventoryStatus,checkout_requirements:JSON.stringify(W),fulfillment_type:t.fulfillmentType,store_policy_fulfillment_type:t.storePolicyFulfillment};t.imageUrl&&(B.image_url=t.imageUrl);const X=t.compareAtUsd?Math.round(Number(t.compareAtUsd)*100):0;X&&(B.compare_at_amount_cents=String(X)),n.length&&(B.tags=JSON.stringify(n)),P.length&&(B.category_ids=JSON.stringify(P)),t.fulfillmentNotes&&(B.fulfillment_notes=t.fulfillmentNotes);const U=t.shippingCountriesCsv.split(",").map(J=>J.trim().toUpperCase()).filter(Boolean);return U.length&&(B.shippingCountries=U.join(","),B.shipping_countries=U.join(",")),B},[d,m]=r.useState([]),L=t=>t.title||t.metadata?.title||t.description||t.id,E=t=>t.imageUrl||t.images?.[0]?.url||t.metadata?.image_url,q=t=>{const n=t.metadata?.store_policy_fulfillment_type;if(n==="digital_in_app"||n==="physical_goods"||n==="real_world_service"||n==="reader_content"||n==="other")return n;switch(t.fulfillment?.type){case"shipping":return"physical_goods";case"service":return"real_world_service";case"digital_download":return"digital_in_app";default:return}},F=t=>{switch(t){case"digital_in_app":return"Digital in-app";case"physical_goods":return"Physical goods";case"real_world_service":return"Real-world service";case"reader_content":return"Reader content";case"other":return"Other";default:return"Not set"}},H=t=>{switch(t){case"consumable":return"Consumable";case"non_consumable":return"Non-consumable";case"auto_renewable_subscription":return"Auto-renewing subscription";default:return"External billing only"}},le=t=>{if(t.storeManagedKind==="none")return;const n=t.appleProductId.trim(),P=t.googleProductId.trim(),W=t.googlePackageName.trim(),z=t.googleBasePlanId.trim(),B=t.googleOfferId.trim();if(!(!n&&!P))return{kind:t.storeManagedKind,apple:n?{productId:n}:void 0,google:P?{productId:P,packageName:W||void 0,basePlanId:z||void 0,offerId:B||void 0}:void 0}},ae=t=>{const n=[],P=q(t);return P&&n.push(F(P)),t.storeBilling?.kind&&n.push(H(t.storeBilling.kind)),t.storeBilling?.apple?.productId&&n.push(`Apple ${t.storeBilling.apple.productId}`),t.storeBilling?.google?.productId&&n.push(`Google ${t.storeBilling.google.productId}`),n.join(" • ")},Z=r.useCallback(async()=>{try{j(null);let t;if(u?.isAuthenticated())t=await u.fetchWithAuth(`/admin/products?limit=${b}`);else{const n={"Content-Type":"application/json"};o&&(n["X-API-Key"]=o);const P=await fetch(`${y}/admin/products?limit=${b}`,{headers:n});if(!P.ok)throw new Error(`Failed to fetch products: ${P.status}`);t=await P.json()}A(t.products||[])}catch{A([]),j("Failed to load products")}finally{T(!1)}},[y,o,b,u]);r.useEffect(()=>{Z(),(async()=>{try{let t;if(u?.isAuthenticated())t=await u.fetchWithAuth("/admin/collections");else{const n={"Content-Type":"application/json"};o&&(n["X-API-Key"]=o);const P=await fetch(`${y}/admin/collections`,{headers:n});if(!P.ok)return;t=await P.json()}m((t.collections||[]).filter(n=>n.tokenizationConfig).map(n=>({id:n.id,name:n.name})))}catch{}})()},[Z,y,o,u]);const ue=async t=>{if(t.preventDefault(),!(!s.id||!s.description)){if(R(null),s.fulfillmentType==="shipping"&&s.checkoutShippingAddress&&!s.shippingCountriesCsv.split(",").map(P=>P.trim()).filter(Boolean).length){R("Shipping countries are required when collecting shipping address. Example: US,CA");return}if(s.storeManagedKind!=="none"&&!s.appleProductId.trim()&&!s.googleProductId.trim()){R("Add at least one Apple or Google store product ID for store-managed products.");return}if(s.googleBasePlanId.trim()&&!s.googleProductId.trim()){R("Google base plan ID requires a Google product ID.");return}if(s.storeManagedKind==="auto_renewable_subscription"&&s.googleProductId.trim()&&!s.googleBasePlanId.trim()){R("Google Play subscriptions require a base plan ID.");return}v(!0);try{const{productType:n}=s,P=s.inventoryQuantity===""?void 0:Number.isFinite(Number(s.inventoryQuantity))?Number(s.inventoryQuantity):void 0,W=Number(s.priceUsd)||0,z=Math.round(W*100),B=Math.round(W*1e6),X=s.tagsCsv.split(",").map(x=>x.trim()).filter(Boolean),U=s.categoryIdsCsv.split(",").map(x=>x.trim()).filter(Boolean),J={email:s.checkoutEmail,name:s.checkoutName,phone:s.checkoutPhone,shippingAddress:s.checkoutShippingAddress,billingAddress:s.checkoutBillingAddress},oe=le(s),re=s.compareAtUsd===""?void 0:Math.round(Number(s.compareAtUsd)*100),i={id:s.id,title:s.title||void 0,slug:s.slug||void 0,description:s.description,tags:X,categoryIds:U,images:s.imageUrl?[{url:s.imageUrl,alt:s.title||s.id}]:[],shippingProfile:s.fulfillmentType==="shipping"?"physical":"digital",checkoutRequirements:J,fulfillment:{type:s.fulfillmentType,notes:s.fulfillmentNotes||void 0},fiatAmountCents:z,fiatCurrency:s.fiatCurrency,compareAtFiatAmountCents:re,compareAtFiatCurrency:re?s.fiatCurrency:void 0,cryptoAtomicAmount:B,cryptoToken:s.cryptoToken,inventoryStatus:s.fulfillmentType==="shipping"?s.inventoryStatus:void 0,...P!==void 0?{inventoryQuantity:P}:{},...oe?{storeBilling:oe}:{},metadata:{...n?{product_type:n}:{},...I(s)}};if(n==="gift_card"&&s.giftCardConfig&&(i.giftCardConfig=s.giftCardConfig),n==="tokenized_asset"&&s.tokenizedAssetConfig&&(i.tokenizedAssetConfig=s.tokenizedAssetConfig),s.complianceRequirements&&(i.complianceRequirements=s.complianceRequirements),u?.isAuthenticated())await u.fetchWithAuth("/admin/products",{method:"POST",body:JSON.stringify(i)});else{const x={"Content-Type":"application/json"};o&&(x["X-API-Key"]=o);const w=await fetch(`${y}/admin/products`,{method:"POST",headers:x,body:JSON.stringify(i)});if(!w.ok)throw new Error(`Failed to create product: ${w.status}`)}h({id:"",title:"",slug:"",imageUrl:"",description:"",productType:"one_time",priceUsd:"",fiatCurrency:"usd",cryptoToken:"USDC",inventoryStatus:"in_stock",compareAtUsd:"",tagsCsv:"",categoryIdsCsv:"",checkoutEmail:"required",checkoutName:"optional",checkoutPhone:"none",checkoutShippingAddress:!1,checkoutBillingAddress:!1,fulfillmentType:"shipping",storePolicyFulfillment:"physical_goods",storeManagedKind:"none",appleProductId:"",googleProductId:"",googlePackageName:"",googleBasePlanId:"",googleOfferId:"",fulfillmentNotes:"",shippingCountriesCsv:"",inventoryQuantity:"",giftCardConfig:null,tokenizedAssetConfig:null,complianceRequirements:null}),V(!1),Z()}catch(n){R(n instanceof Error?n.message:"Failed to create product")}finally{v(!1)}}},me=t=>`$${(t/100).toFixed(2)}`,se=t=>{switch(t){case"subscription":return"Subscription";case"pay_per_access":return"Pay per access";case"one_time":return"One-time purchase";case"gift_card":return"Gift card";default:return"One-time purchase"}},ie=s.storePolicyFulfillment==="digital_in_app"||s.storePolicyFulfillment==="reader_content"||s.storePolicyFulfillment==="other"||s.productType==="subscription"||s.storeManagedKind!=="none",ee=r.useMemo(()=>{const t=p.filter(P=>P.active).length,n=p.reduce((P,W)=>{const z=W.variations?.length??0;return P+(z>0?z:1)},0);return{activeCount:t,totalSkus:n}},[p]),K=t=>{_(n=>!n||n.key!==t?{key:t,direction:"asc"}:{key:t,direction:n.direction==="asc"?"desc":"asc"})},Y=t=>!C||C.key!==t?e.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:$.Icons.chevronUp}):e.jsx("span",{className:"cedros-admin__sort-icon",children:C.direction==="asc"?$.Icons.chevronUp:$.Icons.chevronDown}),he=r.useMemo(()=>{if(!C)return p;const t=C.direction==="asc"?1:-1,n=P=>{switch(C.key){case"product":return L(P);case"type":return se(P.metadata?.product_type);case"price":return P.fiatAmountCents??0;case"status":return P.active?1:0;case"id":default:return P.id}};return[...p].sort((P,W)=>{const z=n(P),B=n(W);return typeof z=="number"&&typeof B=="number"?(z-B)*t:String(z).localeCompare(String(B),void 0,{sensitivity:"base"})*t})},[p,C]);return e.jsxs("div",{className:"cedros-admin__page",children:[e.jsx(ne.ErrorBanner,{message:D,onRetry:Z}),e.jsx(ce.StatsBar,{stats:[{label:"Total Products",value:p.length},{label:"Active",value:ee.activeCount,variant:ee.activeCount>0?"success":"muted"},{label:"Total SKUs",value:ee.totalSkus}],isLoading:N}),e.jsxs("div",{className:"cedros-admin__section-header",children:[e.jsx("h3",{className:"cedros-admin__section-title",children:"Paywall Products"}),e.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:()=>{R(null),V(!g)},children:[g?$.Icons.close:$.Icons.plus,g?"Cancel":"Add Product"]})]}),g&&e.jsxs("form",{onSubmit:ue,className:"cedros-admin__add-form",children:[S&&e.jsx("div",{style:{marginBottom:"0.75rem",color:"#B42318",fontWeight:600},children:S}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Product ID"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.id,onChange:t=>h(n=>({...n,id:t.target.value})),placeholder:"e.g., premium-article",required:!0})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Product name"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.title,onChange:t=>h(n=>({...n,title:t.target.value})),placeholder:"e.g., Cedros Hoodie"})]})]}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Slug"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.slug,onChange:t=>h(n=>({...n,slug:t.target.value})),placeholder:"e.g., cedros-hoodie (defaults to ID)"})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Primary image URL"}),e.jsx("input",{type:"url",className:"cedros-admin__input",value:s.imageUrl,onChange:t=>h(n=>({...n,imageUrl:t.target.value})),placeholder:"https://..."})]})]}),e.jsx("div",{className:"cedros-admin__form-row",children:e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Short description"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.description,onChange:t=>h(n=>({...n,description:t.target.value})),placeholder:"e.g., Midweight fleece with relaxed fit",required:!0})]})}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsx(G.FormDropdown,{value:s.productType,onChange:t=>h(n=>({...n,productType:t,storeManagedKind:t==="subscription"?"auto_renewable_subscription":n.storeManagedKind==="auto_renewable_subscription"?"non_consumable":n.storeManagedKind,giftCardConfig:t==="gift_card"?n.giftCardConfig??{faceValueCents:0,currency:"usd",secondaryMarket:!1,expiresInDays:null}:null,tokenizedAssetConfig:t==="tokenized_asset"?n.tokenizedAssetConfig??{assetClassCollectionId:"",backingValueCents:0,backingCurrency:"usd",assetIdentifier:"",tokensPerUnit:1,custodyProofUrl:null}:null})),options:[{value:"one_time",label:"One-time purchase"},{value:"pay_per_access",label:"Pay per access"},{value:"subscription",label:"Subscription"},{value:"gift_card",label:"Gift card"},{value:"tokenized_asset",label:"Tokenized asset"}],label:"Product Type"}),e.jsx(G.FormDropdown,{value:s.fulfillmentType,onChange:t=>{const n=t;h(P=>({...P,fulfillmentType:n,storePolicyFulfillment:n==="shipping"?"physical_goods":n==="service"?"real_world_service":"digital_in_app",storeManagedKind:n==="shipping"||n==="service"?"none":P.productType==="subscription"?"auto_renewable_subscription":P.storeManagedKind==="none"?"non_consumable":P.storeManagedKind,checkoutShippingAddress:n==="shipping"?P.checkoutShippingAddress:!1}))},options:[{value:"shipping",label:"Physical (shipped)"},{value:"digital_download",label:"Digital download"},{value:"service",label:"Service"}],label:"Fulfillment"})]}),e.jsxs("div",{style:{padding:"0.9rem 1rem",borderRadius:"0.75rem",border:"1px solid var(--cedros-admin-border, #e5e7eb)",background:"var(--cedros-admin-surface, #ffffff)",marginBottom:"1rem"},children:[e.jsx("div",{style:{fontWeight:700,marginBottom:"0.35rem"},children:"Store policy and app billing"}),e.jsx("div",{style:{fontSize:"0.9rem",lineHeight:1.6,opacity:.8},children:"This controls how Cedros routes payments across the web, Apple App Store, and Google Play. For digital app functionality, choose the explicit store policy classification here instead of relying on generic product type labels."})]}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsx(G.FormDropdown,{value:s.storePolicyFulfillment,onChange:t=>h(n=>({...n,storePolicyFulfillment:t,storeManagedKind:t==="physical_goods"||t==="real_world_service"?"none":n.storeManagedKind})),options:[{value:"digital_in_app",label:"Digital in-app"},{value:"physical_goods",label:"Physical goods"},{value:"real_world_service",label:"Real-world service"},{value:"reader_content",label:"Reader content"},{value:"other",label:"Other / review manually"}],label:"Store policy classification"}),e.jsx(G.FormDropdown,{value:s.storeManagedKind,onChange:t=>h(n=>({...n,storeManagedKind:t})),options:[{value:"none",label:"External billing only"},{value:"consumable",label:"Consumable"},{value:"non_consumable",label:"Non-consumable"},{value:"auto_renewable_subscription",label:"Auto-renewing subscription"}],label:"Store-managed product kind"})]}),ie&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Apple product ID"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.appleProductId,onChange:t=>h(n=>({...n,appleProductId:t.target.value})),placeholder:"e.g., com.cedros.pro.monthly"}),e.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Create the matching product in App Store Connect and paste the product ID here."})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Google product ID"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.googleProductId,onChange:t=>h(n=>({...n,googleProductId:t.target.value})),placeholder:"e.g., pro_monthly"}),e.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Create the matching one-time product or subscription in Google Play Console."})]})]}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Google package name"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.googlePackageName,onChange:t=>h(n=>({...n,googlePackageName:t.target.value})),placeholder:"e.g., com.cedros.app"})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Google base plan ID"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.googleBasePlanId,onChange:t=>h(n=>({...n,googleBasePlanId:t.target.value})),placeholder:"Required for Google subscriptions"})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Google offer ID"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.googleOfferId,onChange:t=>h(n=>({...n,googleOfferId:t.target.value})),placeholder:"Optional"})]})]})]}),s.productType==="gift_card"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Gift card face value (USD cents)"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:s.giftCardConfig?.faceValueCents??"",onChange:t=>h(n=>({...n,giftCardConfig:{faceValueCents:parseInt(t.target.value)||0,currency:n.giftCardConfig?.currency??"usd",secondaryMarket:n.giftCardConfig?.secondaryMarket??!1,expiresInDays:n.giftCardConfig?.expiresInDays??null}})),placeholder:"e.g., 5000 for $50.00",min:"1",required:!0}),e.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Face value in cents (e.g. 5000 = $50.00). Must be greater than 0."})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Gift card currency"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.giftCardConfig?.currency??"",onChange:t=>h(n=>({...n,giftCardConfig:{faceValueCents:n.giftCardConfig?.faceValueCents??0,currency:t.target.value.toLowerCase().slice(0,3),secondaryMarket:n.giftCardConfig?.secondaryMarket??!1,expiresInDays:n.giftCardConfig?.expiresInDays??null}})),placeholder:"usd",maxLength:3,required:!0}),e.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"ISO 4217 3-letter currency code (e.g. usd, eur, gbp)."})]})]}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Expiration (days)"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:s.giftCardConfig?.expiresInDays??"",onChange:t=>h(n=>({...n,giftCardConfig:{faceValueCents:n.giftCardConfig?.faceValueCents??0,currency:n.giftCardConfig?.currency??"usd",secondaryMarket:n.giftCardConfig?.secondaryMarket??!1,expiresInDays:t.target.value===""?null:parseInt(t.target.value)||0}})),placeholder:"Leave blank for no expiry",min:"0"}),e.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Number of days until gift card expires. Leave blank for no expiry."})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Secondary market (Token-22)"}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginTop:8},children:[e.jsx("input",{type:"checkbox",checked:s.giftCardConfig?.secondaryMarket??!1,onChange:t=>h(n=>({...n,giftCardConfig:{faceValueCents:n.giftCardConfig?.faceValueCents??0,currency:n.giftCardConfig?.currency??"usd",secondaryMarket:t.target.checked,expiresInDays:n.giftCardConfig?.expiresInDays??null}}))}),"Enable Token-22 secondary market trading"]}),e.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Mints store credit tokens to recipient's embedded wallet for peer-to-peer trading with transfer fees."})]})]})]}),s.productType==="tokenized_asset"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Asset class collection"}),d.length>0?e.jsxs("select",{className:"cedros-admin__input",value:s.tokenizedAssetConfig?.assetClassCollectionId??"",onChange:t=>h(n=>({...n,tokenizedAssetConfig:{...n.tokenizedAssetConfig,assetClassCollectionId:t.target.value}})),required:!0,children:[e.jsx("option",{value:"",children:"Select asset class..."}),d.map(t=>e.jsx("option",{value:t.id,children:t.name},t.id))]}):e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.tokenizedAssetConfig?.assetClassCollectionId??"",onChange:t=>h(n=>({...n,tokenizedAssetConfig:{...n.tokenizedAssetConfig,assetClassCollectionId:t.target.value}})),placeholder:"Collection ID of the asset class",required:!0})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Backing value (cents)"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:s.tokenizedAssetConfig?.backingValueCents??0,onChange:t=>h(n=>({...n,tokenizedAssetConfig:{...n.tokenizedAssetConfig,backingValueCents:Number(t.target.value)}})),min:0})]})]}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Backing currency"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.tokenizedAssetConfig?.backingCurrency??"usd",onChange:t=>h(n=>({...n,tokenizedAssetConfig:{...n.tokenizedAssetConfig,backingCurrency:t.target.value}})),placeholder:"usd",maxLength:3})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Asset identifier"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.tokenizedAssetConfig?.assetIdentifier??"",onChange:t=>h(n=>({...n,tokenizedAssetConfig:{...n.tokenizedAssetConfig,assetIdentifier:t.target.value}})),placeholder:"e.g., ISIN, lot number"})]})]}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Tokens per unit"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:s.tokenizedAssetConfig?.tokensPerUnit??1,onChange:t=>h(n=>({...n,tokenizedAssetConfig:{...n.tokenizedAssetConfig,tokensPerUnit:Number(t.target.value)}})),min:1})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Custody proof URL"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.tokenizedAssetConfig?.custodyProofUrl??"",onChange:t=>h(n=>({...n,tokenizedAssetConfig:{...n.tokenizedAssetConfig,custodyProofUrl:t.target.value||null}})),placeholder:"https://..."})]})]})]}),s.fulfillmentType==="shipping"&&e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsx(G.FormDropdown,{value:s.inventoryStatus,onChange:t=>h(n=>({...n,inventoryStatus:t})),options:[{value:"in_stock",label:"In stock"},{value:"low",label:"Low"},{value:"out_of_stock",label:"Out of stock"},{value:"backorder",label:"Backorder"}],label:"Inventory status"}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Inventory quantity (tracked)"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:s.inventoryQuantity,onChange:t=>h(n=>({...n,inventoryQuantity:t.target.value===""?"":parseInt(t.target.value)||0})),placeholder:"Leave blank for untracked",min:"0"})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Compare-at price (USD)"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:s.compareAtUsd===""?"":s.compareAtUsd,onChange:t=>h(n=>({...n,compareAtUsd:t.target.value===""?"":parseFloat(t.target.value)||0})),placeholder:"e.g., 78.00",min:"0",step:"0.01"})]})]}),e.jsx("div",{className:"cedros-admin__form-row",children:e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Price (USD)"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:s.priceUsd===""?"":s.priceUsd,onChange:t=>h(n=>({...n,priceUsd:t.target.value===""?"":parseFloat(t.target.value)||0})),placeholder:"e.g., 5.00",min:"0",step:"0.01",required:!0})]})}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Tags (comma-separated)"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.tagsCsv,onChange:t=>h(n=>({...n,tagsCsv:t.target.value})),placeholder:"e.g., core, new, gift"})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Category IDs (comma-separated)"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.categoryIdsCsv,onChange:t=>h(n=>({...n,categoryIdsCsv:t.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"})]})]}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsx(G.FormDropdown,{value:s.checkoutEmail,onChange:t=>h(n=>({...n,checkoutEmail:t})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Email"}),e.jsx(G.FormDropdown,{value:s.checkoutName,onChange:t=>h(n=>({...n,checkoutName:t})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Name"}),e.jsx(G.FormDropdown,{value:s.checkoutPhone,onChange:t=>h(n=>({...n,checkoutPhone:t})),options:[{value:"none",label:"None"},{value:"optional",label:"Optional"},{value:"required",label:"Required"}],label:"Checkout: Phone"})]}),e.jsxs("div",{className:"cedros-admin__form-row",children:[s.fulfillmentType==="shipping"&&e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Checkout: Shipping address"}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[e.jsx("input",{type:"checkbox",checked:s.checkoutShippingAddress,onChange:t=>h(n=>({...n,checkoutShippingAddress:t.target.checked}))}),"Collect shipping address"]})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Checkout: Billing address"}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[e.jsx("input",{type:"checkbox",checked:s.checkoutBillingAddress,onChange:t=>h(n=>({...n,checkoutBillingAddress:t.target.checked}))}),"Collect billing address"]})]})]}),e.jsx("div",{className:"cedros-admin__form-row",children:e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Fulfillment notes"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.fulfillmentNotes,onChange:t=>h(n=>({...n,fulfillmentNotes:t.target.value})),placeholder:s.fulfillmentType==="shipping"?"e.g., Ships within 3-5 business days":"e.g., Downloadable from your account after purchase"})]})}),s.fulfillmentType==="shipping"&&s.checkoutShippingAddress&&e.jsx("div",{className:"cedros-admin__form-row",children:e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Shipping countries"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.shippingCountriesCsv,onChange:t=>h(n=>({...n,shippingCountriesCsv:t.target.value})),placeholder:"e.g., US,CA"}),e.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"ISO 2-letter country codes, comma-separated. Required for shipping address collection."})]})}),e.jsx(Ce,{value:s.complianceRequirements,onChange:t=>h(n=>({...n,complianceRequirements:t}))}),e.jsx("div",{className:"cedros-admin__form-actions",children:e.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:k,children:k?"Creating...":"Create Product"})})]}),N?e.jsxs("div",{className:"cedros-admin__loading",children:[$.Icons.loading," Loading products..."]}):e.jsx("div",{className:"cedros-admin__table-container",children:e.jsxs("table",{className:"cedros-admin__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{"aria-sort":C?.key==="id"?C?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>K("id"),children:["ID",Y("id")]})}),e.jsx("th",{"aria-sort":C?.key==="product"?C?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>K("product"),children:["Product",Y("product")]})}),e.jsx("th",{"aria-sort":C?.key==="type"?C?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>K("type"),children:["Type",Y("type")]})}),e.jsx("th",{"aria-sort":C?.key==="price"?C?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>K("price"),children:["Price",Y("price")]})}),e.jsx("th",{"aria-sort":C?.key==="status"?C?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>K("status"),children:["Status",Y("status")]})}),e.jsx("th",{children:"Actions"})]})}),e.jsx("tbody",{children:he.map(t=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("code",{children:t.id})}),e.jsx("td",{children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[E(t)?e.jsx("img",{src:E(t),alt:"",style:{width:28,height:28,borderRadius:6,objectFit:"cover"}}):e.jsx("div",{style:{width:28,height:28,borderRadius:6,background:"rgba(0,0,0,0.06)"}}),e.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[e.jsx("span",{style:{fontWeight:600},children:L(t)}),e.jsx("span",{style:{opacity:.8},children:t.description}),ae(t)?e.jsx("span",{style:{opacity:.7,fontSize:"0.8rem"},children:ae(t)}):null]})]})}),e.jsx("td",{children:se(t.metadata?.product_type)}),e.jsx("td",{children:me(t.fiatAmountCents)}),e.jsx("td",{children:e.jsx("span",{className:`cedros-admin__badge ${t.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:t.active?"Active":"Inactive"})}),e.jsx("td",{children:e.jsxs("div",{style:{display:"flex",gap:"0.25rem"},children:[e.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>c(t),children:"Variations"}),t.metadata?.product_type==="tokenized_asset"&&e.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>l(t),children:"NFT"})]})})]},t.id))})]})}),f&&e.jsx("div",{className:"cedros-admin__modal-overlay",onClick:()=>c(null),children:e.jsx("div",{className:"cedros-admin__modal cedros-admin__modal--lg",onClick:t=>t.stopPropagation(),children:e.jsx(je,{serverUrl:y,productId:f.id,productTitle:L(f),defaultPrice:f.fiatAmountCents/100,apiKey:o,authManager:u,onClose:()=>c(null)})})}),a&&e.jsx("div",{className:"cedros-admin__modal-overlay",onClick:()=>l(null),children:e.jsx("div",{className:"cedros-admin__modal cedros-admin__modal--lg",onClick:t=>t.stopPropagation(),children:e.jsx(Ne,{serverUrl:y,productId:a.id,productTitle:L(a),apiKey:o,authManager:u,onClose:()=>l(null)})})})]})}function Se({serverUrl:y,apiKey:o,pageSize:b=20,authManager:u}){const[p,A]=r.useState([]),[N,T]=r.useState(null),[g,V]=r.useState(!0),[k,v]=r.useState(!0),[S,R]=r.useState(null),[f,c]=r.useState(""),[a,l]=r.useState(null),C=r.useCallback(async()=>{v(!0);try{R(null);let I;if(u?.isAuthenticated())I=await u.fetchWithAuth("/admin/stats");else{const d={"Content-Type":"application/json"};o&&(d["X-API-Key"]=o);const m=await fetch(`${y}/admin/stats`,{headers:d});if(!m.ok)throw new Error(`Failed to fetch stats: ${m.status}`);I=await m.json()}T(I)}catch{T(null),R("Failed to load payment stats")}finally{v(!1)}},[y,o,u]);r.useEffect(()=>{C()},[C]);const _=r.useCallback(async()=>{try{R(null);let I;const d=new URLSearchParams({limit:b.toString()});f&&d.set("method",f);const m=`/admin/transactions?${d}`;if(u?.isAuthenticated())I=await u.fetchWithAuth(m);else{const L={"Content-Type":"application/json"};o&&(L["X-API-Key"]=o);const E=await fetch(`${y}${m}`,{headers:L});if(!E.ok)throw new Error(`Failed to fetch transactions: ${E.status}`);I=await E.json()}A(I.transactions||[])}catch{A([]),R("Failed to load transactions")}finally{V(!1)}},[y,o,b,f,u]);r.useEffect(()=>{_()},[_]);const D=(I,d="USD")=>new Intl.NumberFormat("en-US",{style:"currency",currency:d}).format(I),j=I=>{l(d=>!d||d.key!==I?{key:I,direction:"asc"}:{key:I,direction:d.direction==="asc"?"desc":"asc"})},s=I=>!a||a.key!==I?e.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:$.Icons.chevronUp}):e.jsx("span",{className:"cedros-admin__sort-icon",children:a.direction==="asc"?$.Icons.chevronUp:$.Icons.chevronDown}),h=r.useMemo(()=>{if(!a)return p;const I=a.direction==="asc"?1:-1,d=m=>{switch(a.key){case"resource":return m.resourceId;case"method":return m.method;case"amount":return m.amount;case"status":return m.status;case"date":return new Date(m.paidAt).getTime();case"id":default:return m.id}};return[...p].sort((m,L)=>{const E=d(m),q=d(L);return typeof E=="number"&&typeof q=="number"?(E-q)*I:String(E).localeCompare(String(q),void 0,{sensitivity:"base"})*I})},[p,a]);return e.jsxs("div",{className:"cedros-admin__page",children:[e.jsx(ne.ErrorBanner,{message:S,onRetry:()=>{C(),_()}}),e.jsx(ce.StatsBar,{stats:[{label:"Revenue",value:D(N?.totalRevenue??0)},{label:"Orders",value:N?.totalTransactions??0},{label:"Card",value:D(N?.revenueByMethod.stripe??0),description:`${N?.transactionsByMethod.stripe??0} orders`},{label:"Crypto",value:D(N?.revenueByMethod.x402??0),description:`${N?.transactionsByMethod.x402??0} orders`},{label:"Credits",value:D(N?.revenueByMethod.credits??0),description:`${N?.transactionsByMethod.credits??0} orders`}],isLoading:k,onRefresh:C}),e.jsxs("div",{className:"cedros-admin__section-header",children:[e.jsx("h3",{className:"cedros-admin__section-title",children:"Transaction History"}),e.jsx(G.FilterDropdown,{value:f,onChange:c,options:[{value:"",label:"All"},{value:"stripe",label:"Card"},{value:"x402",label:"Crypto"},{value:"credits",label:"Credits"}]})]}),g?e.jsxs("div",{className:"cedros-admin__loading",children:[$.Icons.loading," Loading transactions..."]}):e.jsx("div",{className:"cedros-admin__table-container",children:e.jsxs("table",{className:"cedros-admin__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{"aria-sort":a?.key==="id"?a?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("id"),children:["ID",s("id")]})}),e.jsx("th",{"aria-sort":a?.key==="resource"?a?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("resource"),children:["Resource",s("resource")]})}),e.jsx("th",{"aria-sort":a?.key==="method"?a?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("method"),children:["Method",s("method")]})}),e.jsx("th",{"aria-sort":a?.key==="amount"?a?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("amount"),children:["Amount",s("amount")]})}),e.jsx("th",{"aria-sort":a?.key==="status"?a?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("status"),children:["Status",s("status")]})}),e.jsx("th",{"aria-sort":a?.key==="date"?a?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>j("date"),children:["Date",s("date")]})})]})}),e.jsx("tbody",{children:h.map(I=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("code",{children:I.id})}),e.jsx("td",{children:I.resourceId}),e.jsx("td",{children:e.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${I.method}`,children:I.method})}),e.jsxs("td",{children:["$",I.amount.toFixed(2)," ",I.currency.toUpperCase()]}),e.jsx("td",{children:e.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${I.status}`,children:I.status})}),e.jsx("td",{children:de.formatDateTime(I.paidAt)})]},I.id))})]})})]})}function we({serverUrl:y,apiKey:o,pageSize:b=20,authManager:u}){const[p,A]=r.useState([]),[N,T]=r.useState(!0),[g,V]=r.useState(!1),[k,v]=r.useState(!1),[S,R]=r.useState(null),[f,c]=r.useState(null),[a,l]=r.useState({code:"",discountType:"percentage",discountValue:0,usageLimit:void 0,expiresAt:"",scope:"all_products",productIdsCsv:"",categoryIdsCsv:"",paymentMethod:"any",autoApply:!1,appliesAt:"both",startsAt:"",minimumAmountUsd:"",usageLimitPerCustomer:void 0,firstPurchaseOnly:!1}),C=r.useCallback(async()=>{try{c(null);let d;const m=`/admin/coupons?limit=${b}`;if(u?.isAuthenticated())d=await u.fetchWithAuth(m);else{const L={"Content-Type":"application/json"};o&&(L["X-API-Key"]=o);const E=await fetch(`${y}${m}`,{headers:L});if(!E.ok)throw new Error(`Failed to fetch coupons: ${E.status}`);d=await E.json()}A(d.coupons||[])}catch(d){te.getLogger().error("[CouponsSection] Failed to fetch coupons:",d,{serverUrl:y.slice(0,20)+"...",hasApiKey:!!o}),A([]),c("Failed to load coupons")}finally{T(!1)}},[y,o,b,u]);r.useEffect(()=>{C()},[C]);const _=async d=>{if(d.preventDefault(),!(!a.code||a.discountValue<=0)){v(!0);try{const m=a.minimumAmountUsd?Math.round(Number(a.minimumAmountUsd)*100):void 0,L=a.productIdsCsv.split(",").map(F=>F.trim()).filter(Boolean),E=a.categoryIdsCsv.split(",").map(F=>F.trim()).filter(Boolean),q={code:a.code,discountType:a.discountType,discountValue:a.discountValue,usageLimit:a.usageLimit,active:!0,usageCount:0,scope:a.scope,...L.length?{productIds:L}:{},...E.length?{categoryIds:E}:{},...a.paymentMethod!=="any"?{paymentMethod:a.paymentMethod}:{},...a.autoApply?{autoApply:!0}:{},...a.appliesAt!=="both"?{appliesAt:a.appliesAt}:{},...a.startsAt?{startsAt:a.startsAt}:{},...a.expiresAt?{expiresAt:a.expiresAt}:{},...m?{minimumAmountCents:m}:{},...a.usageLimitPerCustomer?{usageLimitPerCustomer:a.usageLimitPerCustomer}:{},...a.firstPurchaseOnly?{firstPurchaseOnly:!0}:{}};if(u?.isAuthenticated())await u.fetchWithAuth("/admin/coupons",{method:"POST",body:JSON.stringify(q)});else{const F={"Content-Type":"application/json"};o&&(F["X-API-Key"]=o);const H=await fetch(`${y}/admin/coupons`,{method:"POST",headers:F,body:JSON.stringify(q)});if(!H.ok)throw new Error(`Failed to create coupon: ${H.status}`)}l({code:"",discountType:"percentage",discountValue:0,usageLimit:void 0,expiresAt:"",scope:"all_products",productIdsCsv:"",categoryIdsCsv:"",paymentMethod:"any",autoApply:!1,appliesAt:"both",startsAt:"",minimumAmountUsd:"",usageLimitPerCustomer:void 0,firstPurchaseOnly:!1}),V(!1),C()}catch(m){te.getLogger().error("[CouponsSection] Failed to add coupon:",m,{serverUrl:y.slice(0,20)+"...",hasApiKey:!!o}),c("Failed to create coupon")}finally{v(!1)}}},D=p.filter(d=>d.active).length,j=p.reduce((d,m)=>d+(m.usageCount??0),0),s=d=>{R(m=>!m||m.key!==d?{key:d,direction:"asc"}:{key:d,direction:m.direction==="asc"?"desc":"asc"})},h=d=>!S||S.key!==d?e.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:$.Icons.chevronUp}):e.jsx("span",{className:"cedros-admin__sort-icon",children:S.direction==="asc"?$.Icons.chevronUp:$.Icons.chevronDown}),I=r.useMemo(()=>{if(!S)return p;const d=S.direction==="asc"?1:-1,m=L=>{switch(S.key){case"discount":return L.discountValue??0;case"usage":return L.usageCount??0;case"status":return L.active?1:0;case"code":default:return L.code}};return[...p].sort((L,E)=>{const q=m(L),F=m(E);return typeof q=="number"&&typeof F=="number"?(q-F)*d:String(q).localeCompare(String(F),void 0,{sensitivity:"base"})*d})},[p,S]);return e.jsxs("div",{className:"cedros-admin__page",children:[e.jsx(ne.ErrorBanner,{message:f,onRetry:C}),e.jsx(ce.StatsBar,{stats:[{label:"Total Coupons",value:p.length},{label:"Active",value:D,variant:D>0?"success":"muted"},{label:"Redemptions",value:j}],isLoading:N}),e.jsxs("div",{className:"cedros-admin__section-header",children:[e.jsx("h3",{className:"cedros-admin__section-title",children:"Discount Coupons"}),e.jsxs("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--action",onClick:()=>V(!g),children:[g?$.Icons.close:$.Icons.plus,g?"Cancel":"Add Coupon"]})]}),g&&e.jsxs("form",{onSubmit:_,className:"cedros-admin__add-form",children:[e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Coupon Code"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:a.code,onChange:d=>l(m=>({...m,code:d.target.value.toUpperCase()})),placeholder:"e.g., SAVE20",required:!0})]}),e.jsx(G.FormDropdown,{value:a.discountType,onChange:d=>l(m=>({...m,discountType:d})),options:[{value:"percentage",label:"Percentage (%)"},{value:"fixed",label:"Fixed Amount ($)"}],label:"Discount Type"})]}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsxs("label",{className:"cedros-admin__field-label",children:["Discount Value ",a.discountType==="percentage"?"(%)":"($)"]}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:a.discountValue||"",onChange:d=>l(m=>({...m,discountValue:parseFloat(d.target.value)||0})),placeholder:a.discountType==="percentage"?"e.g., 20":"e.g., 10.00",min:"0",step:a.discountType==="percentage"?"1":"0.01",required:!0})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Usage Limit (optional)"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:a.usageLimit||"",onChange:d=>l(m=>({...m,usageLimit:d.target.value?parseInt(d.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Expiration Date (optional)"}),e.jsx("input",{type:"date",className:"cedros-admin__input",value:a.expiresAt,onChange:d=>l(m=>({...m,expiresAt:d.target.value}))})]})]}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsx(G.FormDropdown,{value:a.scope,onChange:d=>l(m=>({...m,scope:d})),options:[{value:"all_products",label:"All Products"},{value:"specific_products",label:"Specific Products"},{value:"specific_categories",label:"Specific Categories"}],label:"Scope"}),e.jsx(G.FormDropdown,{value:a.paymentMethod,onChange:d=>l(m=>({...m,paymentMethod:d})),options:[{value:"any",label:"Any Payment Method"},{value:"stripe",label:"Stripe (Card) Only"},{value:"x402",label:"Crypto (x402) Only"},{value:"credits",label:"Credits Only"}],label:"Payment Method"}),e.jsx(G.FormDropdown,{value:a.appliesAt,onChange:d=>l(m=>({...m,appliesAt:d})),options:[{value:"both",label:"Cart & Checkout"},{value:"cart",label:"Cart Only"},{value:"checkout",label:"Checkout Only"}],label:"Applies At"})]}),a.scope==="specific_products"&&e.jsx("div",{className:"cedros-admin__form-row",children:e.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Product IDs"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:a.productIdsCsv,onChange:d=>l(m=>({...m,productIdsCsv:d.target.value})),placeholder:"e.g., prod_123, prod_456"}),e.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated product IDs this coupon applies to."})]})}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Start Date (optional)"}),e.jsx("input",{type:"date",className:"cedros-admin__input",value:a.startsAt,onChange:d=>l(m=>({...m,startsAt:d.target.value}))})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Auto Apply"}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[e.jsx("input",{type:"checkbox",checked:a.autoApply,onChange:d=>l(m=>({...m,autoApply:d.target.checked}))}),"Automatically apply when conditions met"]})]})]}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Minimum Purchase (USD)"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:a.minimumAmountUsd===""?"":a.minimumAmountUsd,onChange:d=>l(m=>({...m,minimumAmountUsd:d.target.value===""?"":parseFloat(d.target.value)||0})),placeholder:"e.g., 50.00",min:"0",step:"0.01"})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Per-Customer Limit"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:a.usageLimitPerCustomer||"",onChange:d=>l(m=>({...m,usageLimitPerCustomer:d.target.value?parseInt(d.target.value):void 0})),placeholder:"Leave empty for unlimited",min:"1"})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"First Purchase Only"}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[e.jsx("input",{type:"checkbox",checked:a.firstPurchaseOnly,onChange:d=>l(m=>({...m,firstPurchaseOnly:d.target.checked}))}),"New customers only"]})]})]}),a.scope==="specific_categories"&&e.jsx("div",{className:"cedros-admin__form-row",children:e.jsxs("div",{className:"cedros-admin__field",style:{flex:1},children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Category IDs"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:a.categoryIdsCsv,onChange:d=>l(m=>({...m,categoryIdsCsv:d.target.value})),placeholder:"e.g., cat_apparel, cat_accessories"}),e.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Comma-separated category IDs this coupon applies to."})]})}),e.jsx("div",{className:"cedros-admin__form-actions",children:e.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:k,children:k?"Creating...":"Create Coupon"})})]}),N?e.jsxs("div",{className:"cedros-admin__loading",children:[$.Icons.loading," Loading coupons..."]}):e.jsx("div",{className:"cedros-admin__table-container",children:e.jsxs("table",{className:"cedros-admin__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{"aria-sort":S?.key==="code"?S?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>s("code"),children:["Code",h("code")]})}),e.jsx("th",{"aria-sort":S?.key==="discount"?S?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>s("discount"),children:["Discount",h("discount")]})}),e.jsx("th",{"aria-sort":S?.key==="usage"?S?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>s("usage"),children:["Usage",h("usage")]})}),e.jsx("th",{"aria-sort":S?.key==="status"?S?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>s("status"),children:["Status",h("status")]})}),e.jsx("th",{children:"Actions"})]})}),e.jsx("tbody",{children:I.map(d=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("code",{children:d.code})}),e.jsx("td",{children:d.discountType==="percentage"?`${d.discountValue}%`:`$${d.discountValue.toFixed(2)}`}),e.jsxs("td",{children:[d.usageCount,d.usageLimit?` / ${d.usageLimit}`:""]}),e.jsx("td",{children:e.jsx("span",{className:`cedros-admin__badge ${d.active?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:d.active?"Active":"Inactive"})}),e.jsx("td",{children:e.jsx("button",{className:"cedros-admin__button cedros-admin__button--ghost",children:"Edit"})})]},d.code))})]})})]})}function Ae({serverUrl:y,apiKey:o,pageSize:b=20,authManager:u}){const[p,A]=r.useState([]),[N,T]=r.useState(!0),[g,V]=r.useState(null),[k,v]=r.useState([]),[S,R]=r.useState(!0),[f,c]=r.useState(null),[a,l]=r.useState([]),[C,_]=r.useState(!0),[D,j]=r.useState(null),[s,h]=r.useState(null),[I,d]=r.useState(null),m=r.useCallback(async()=>{try{let i;const x=`/admin/refunds?limit=${b}`;if(u?.isAuthenticated())i=await u.fetchWithAuth(x);else{const w={"Content-Type":"application/json"};o&&(w["X-API-Key"]=o);const O=await fetch(`${y}${x}`,{headers:w});if(!O.ok)throw new Error(`Failed to fetch x402 refunds: ${O.status}`);i=await O.json()}A(i.refunds||[])}catch(i){te.getLogger().error("[RefundsSection] Failed to fetch x402 refunds:",i,{serverUrl:y.slice(0,20)+"...",hasApiKey:!!o}),A([]),d("Failed to load x402 refunds")}finally{T(!1)}},[y,o,b,u]);r.useEffect(()=>{m()},[m]);const L=r.useCallback(async()=>{try{let i;const x=`/admin/credits/refund-requests?status=pending&limit=${b}&offset=0`;if(u?.isAuthenticated())i=await u.fetchWithAuth(x);else{const O={"Content-Type":"application/json"};o&&(O["X-API-Key"]=o);const M=await fetch(`${y}${x}`,{headers:O});if(!M.ok)throw new Error(`Failed to fetch credits refund requests: ${M.status}`);i=await M.json()}const w=Array.isArray(i)?i:"refundRequests"in i?i.refundRequests:i.requests||[];v(w)}catch(i){te.getLogger().error("[RefundsSection] Failed to fetch credits refunds:",i,{serverUrl:y.slice(0,20)+"...",hasApiKey:!!o}),v([]),d("Failed to load credits refunds")}finally{R(!1)}},[y,o,b,u]);r.useEffect(()=>{L()},[L]);const E=r.useCallback(async()=>{try{let i;const x=`/admin/stripe/refunds?limit=${b}`;if(u?.isAuthenticated())i=await u.fetchWithAuth(x);else{const w={"Content-Type":"application/json"};o&&(w["X-API-Key"]=o);const O=await fetch(`${y}${x}`,{headers:w});if(!O.ok)throw new Error(`Failed to fetch Stripe refunds: ${O.status}`);i=await O.json()}l(i.refunds||[])}catch(i){te.getLogger().error("[RefundsSection] Failed to fetch Stripe refunds:",i,{serverUrl:y.slice(0,20)+"...",hasApiKey:!!o}),l([]),d("Failed to load Stripe refunds")}finally{_(!1)}},[y,o,b,u]);r.useEffect(()=>{E()},[E]);const q=async i=>{j(i);try{const x=`/admin/stripe/refunds/${i}/process`;if(u?.isAuthenticated())await u.fetchWithAuth(x,{method:"POST"});else{const w={"Content-Type":"application/json"};o&&(w["X-API-Key"]=o);const O=await fetch(`${y}${x}`,{method:"POST",headers:w});if(!O.ok)throw new Error(`Failed to process refund: ${O.status}`)}await E()}catch(x){te.getLogger().error("[RefundsSection] Failed to process Stripe refund:",x,{serverUrl:y.slice(0,20)+"...",hasApiKey:!!o,refundId:i}),d("Failed to process Stripe refund")}finally{j(null)}},F=(i,x)=>new Intl.NumberFormat("en-US",{style:"currency",currency:x}).format(i/100),H=i=>i?i.replace(/_/g," ").replace(/\b\w/g,x=>x.toUpperCase()):"—",le=i=>{switch(i){case"processed":return"success";case"pending":return"pending";case"rejected":default:return"muted"}},ae=(i,x)=>x?x.toLowerCase()==="usd"?`${new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(i/1e6)} (USD credits)`:`${i.toLocaleString()} ${x.toUpperCase()} (atomic)`:`${i.toLocaleString()} (atomic)`,Z=i=>{switch(i){case"succeeded":return"success";case"failed":return"failed";case"pending":case"requires_action":return"pending";case"canceled":default:return"muted"}},ue=i=>i.stripeRefundId??"—",me=i=>i.chargeId??"—",se=a.filter(i=>i.status==="pending"||i.status==="requires_action").length,ie=k.filter(i=>i.status==="pending").length,ee=p.filter(i=>i.status==="pending").length,K=se+ie+ee,Y=a.filter(i=>i.status==="succeeded").reduce((i,x)=>i+x.amount,0),he=k.filter(i=>i.status==="processed").reduce((i,x)=>i+x.amountLamports,0),t=p.filter(i=>i.status==="completed").reduce((i,x)=>i+x.amount,0),n=Y/100+he/1e6+t,P=i=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(i),W=C||S||N,z=i=>{h(x=>!x||x.key!==i?{key:i,direction:"asc"}:{key:i,direction:x.direction==="asc"?"desc":"asc"})},B=i=>{c(x=>!x||x.key!==i?{key:i,direction:"asc"}:{key:i,direction:x.direction==="asc"?"desc":"asc"})},X=i=>{V(x=>!x||x.key!==i?{key:i,direction:"asc"}:{key:i,direction:x.direction==="asc"?"desc":"asc"})},U=(i,x)=>!i||!x?e.jsx("span",{className:"cedros-admin__sort-icon cedros-admin__sort-icon--idle",children:$.Icons.chevronUp}):e.jsx("span",{className:"cedros-admin__sort-icon",children:x==="asc"?$.Icons.chevronUp:$.Icons.chevronDown}),J=r.useMemo(()=>{if(!s)return a;const i=s.direction==="asc"?1:-1,x=w=>{switch(s.key){case"stripe":return w.stripeRefundId??"";case"charge":return w.chargeId??"";case"amount":return w.amount??0;case"reason":return w.reason??"";case"status":return w.status??"";case"date":return new Date(w.createdAt).getTime();case"id":default:return w.id}};return[...a].sort((w,O)=>{const M=x(w),Q=x(O);return typeof M=="number"&&typeof Q=="number"?(M-Q)*i:String(M).localeCompare(String(Q),void 0,{sensitivity:"base"})*i})},[a,s]),oe=r.useMemo(()=>{if(!f)return k;const i=f.direction==="asc"?1:-1,x=w=>{switch(f.key){case"original":return w.originalTransactionId??"";case"user":return w.userId??"";case"amount":return w.amountLamports??0;case"reason":return w.reason??"";case"status":return w.status??"";case"date":return new Date(w.createdAt).getTime();case"id":default:return w.id}};return[...k].sort((w,O)=>{const M=x(w),Q=x(O);return typeof M=="number"&&typeof Q=="number"?(M-Q)*i:String(M).localeCompare(String(Q),void 0,{sensitivity:"base"})*i})},[k,f]),re=r.useMemo(()=>{if(!g)return p;const i=g.direction==="asc"?1:-1,x=w=>{switch(g.key){case"transaction":return w.transactionId??"";case"amount":return w.amount??0;case"reason":return w.reason??"";case"status":return w.status??"";case"date":return new Date(w.createdAt).getTime();case"id":default:return w.id}};return[...p].sort((w,O)=>{const M=x(w),Q=x(O);return typeof M=="number"&&typeof Q=="number"?(M-Q)*i:String(M).localeCompare(String(Q),void 0,{sensitivity:"base"})*i})},[p,g]);return e.jsxs("div",{className:"cedros-admin__page",children:[e.jsx(ne.ErrorBanner,{message:I,onRetry:()=>{m(),L(),E()}}),e.jsx(ce.StatsBar,{stats:[{label:"Pending",value:K,variant:K>0?"warning":"muted"},{label:"Card Pending",value:se,description:"Stripe"},{label:"Credits Pending",value:ie},{label:"Crypto Pending",value:ee,description:"x402"},{label:"Total Refunded",value:P(n),variant:"success"}],isLoading:W}),e.jsx("div",{className:"cedros-admin__section-header",children:e.jsx("h3",{className:"cedros-admin__section-title",children:"Stripe Refund Requests"})}),C?e.jsxs("div",{className:"cedros-admin__loading",children:[$.Icons.loading," Loading Stripe refunds..."]}):a.length===0?e.jsx("div",{className:"cedros-admin__empty",children:"No Stripe refund requests found."}):e.jsx("div",{className:"cedros-admin__table-container",children:e.jsxs("table",{className:"cedros-admin__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{"aria-sort":s?.key==="id"?s?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>z("id"),children:["Request ID",U(s?.key==="id",s?.direction)]})}),e.jsx("th",{"aria-sort":s?.key==="stripe"?s?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>z("stripe"),children:["Stripe Refund ID",U(s?.key==="stripe",s?.direction)]})}),e.jsx("th",{"aria-sort":s?.key==="charge"?s?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>z("charge"),children:["Charge",U(s?.key==="charge",s?.direction)]})}),e.jsx("th",{"aria-sort":s?.key==="amount"?s?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>z("amount"),children:["Amount",U(s?.key==="amount",s?.direction)]})}),e.jsx("th",{"aria-sort":s?.key==="reason"?s?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>z("reason"),children:["Reason",U(s?.key==="reason",s?.direction)]})}),e.jsx("th",{"aria-sort":s?.key==="status"?s?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>z("status"),children:["Status",U(s?.key==="status",s?.direction)]})}),e.jsx("th",{"aria-sort":s?.key==="date"?s?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>z("date"),children:["Date",U(s?.key==="date",s?.direction)]})}),e.jsx("th",{children:"Actions"})]})}),e.jsx("tbody",{children:J.map(i=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("code",{children:i.id})}),e.jsx("td",{children:e.jsx("code",{children:ue(i)})}),e.jsx("td",{children:e.jsx("code",{children:me(i)})}),e.jsx("td",{children:F(i.amount,i.currency)}),e.jsx("td",{children:H(i.reason)}),e.jsx("td",{children:e.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${Z(i.status)}`,children:i.status})}),e.jsx("td",{children:de.formatDateTime(i.createdAt)}),e.jsx("td",{children:(i.status==="pending"||i.status==="requires_action")&&e.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",onClick:()=>q(i.id),disabled:D===i.id,children:D===i.id?"Processing...":"Process"})})]},i.id))})]})}),e.jsx("div",{className:"cedros-admin__section-header",style:{marginTop:"2rem"},children:e.jsx("h3",{className:"cedros-admin__section-title",children:"Credits Refund Requests"})}),e.jsx("p",{className:"cedros-admin__hint",style:{marginBottom:"0.75rem"},children:"Credits refund requests are read-only in this admin surface."}),S?e.jsxs("div",{className:"cedros-admin__loading",children:[$.Icons.loading," Loading credits refunds..."]}):k.length===0?e.jsx("div",{className:"cedros-admin__empty",children:"No credits refund requests found."}):e.jsx("div",{className:"cedros-admin__table-container",children:e.jsxs("table",{className:"cedros-admin__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{"aria-sort":f?.key==="id"?f?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>B("id"),children:["Request ID",U(f?.key==="id",f?.direction)]})}),e.jsx("th",{"aria-sort":f?.key==="original"?f?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>B("original"),children:["Original Tx",U(f?.key==="original",f?.direction)]})}),e.jsx("th",{"aria-sort":f?.key==="user"?f?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>B("user"),children:["User",U(f?.key==="user",f?.direction)]})}),e.jsx("th",{"aria-sort":f?.key==="amount"?f?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>B("amount"),children:["Amount",U(f?.key==="amount",f?.direction)]})}),e.jsx("th",{"aria-sort":f?.key==="reason"?f?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>B("reason"),children:["Reason",U(f?.key==="reason",f?.direction)]})}),e.jsx("th",{"aria-sort":f?.key==="status"?f?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>B("status"),children:["Status",U(f?.key==="status",f?.direction)]})}),e.jsx("th",{"aria-sort":f?.key==="date"?f?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>B("date"),children:["Date",U(f?.key==="date",f?.direction)]})})]})}),e.jsx("tbody",{children:oe.map(i=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("code",{children:i.id})}),e.jsx("td",{children:e.jsx("code",{children:i.originalTransactionId})}),e.jsx("td",{children:e.jsx("code",{children:i.userId??"—"})}),e.jsx("td",{children:ae(i.amountLamports,i.currency)}),e.jsx("td",{children:i.reason??"—"}),e.jsx("td",{children:e.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${le(i.status)}`,children:i.status})}),e.jsx("td",{children:de.formatDateTime(i.createdAt)})]},i.id))})]})}),e.jsx("div",{className:"cedros-admin__section-header",style:{marginTop:"2rem"},children:e.jsx("h3",{className:"cedros-admin__section-title",children:"x402 Refund Requests"})}),e.jsx("p",{className:"cedros-admin__hint",style:{marginBottom:"0.75rem"},children:"x402 refund approvals use the signed refund workflow, not this dashboard table."}),N?e.jsxs("div",{className:"cedros-admin__loading",children:[$.Icons.loading," Loading x402 refunds..."]}):p.length===0?e.jsx("div",{className:"cedros-admin__empty",children:"No x402 refund requests found."}):e.jsx("div",{className:"cedros-admin__table-container",children:e.jsxs("table",{className:"cedros-admin__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{"aria-sort":g?.key==="id"?g?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>X("id"),children:["ID",U(g?.key==="id",g?.direction)]})}),e.jsx("th",{"aria-sort":g?.key==="transaction"?g?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>X("transaction"),children:["Transaction",U(g?.key==="transaction",g?.direction)]})}),e.jsx("th",{"aria-sort":g?.key==="amount"?g?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>X("amount"),children:["Amount",U(g?.key==="amount",g?.direction)]})}),e.jsx("th",{"aria-sort":g?.key==="reason"?g?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>X("reason"),children:["Reason",U(g?.key==="reason",g?.direction)]})}),e.jsx("th",{"aria-sort":g?.key==="status"?g?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>X("status"),children:["Status",U(g?.key==="status",g?.direction)]})}),e.jsx("th",{"aria-sort":g?.key==="date"?g?.direction==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"cedros-admin__table-sort",onClick:()=>X("date"),children:["Date",U(g?.key==="date",g?.direction)]})})]})}),e.jsx("tbody",{children:re.map(i=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("code",{children:i.id})}),e.jsx("td",{children:e.jsx("code",{children:i.transactionId})}),e.jsxs("td",{children:["$",i.amount.toFixed(2)]}),e.jsx("td",{children:i.reason||"—"}),e.jsx("td",{children:e.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${i.status}`,children:i.status})}),e.jsx("td",{children:de.formatDateTime(i.createdAt)})]},i.id))})]})})]})}exports.CouponsSection=we;exports.ProductsSection=ke;exports.RefundsSection=Ae;exports.TransactionsSection=Se;
|